Bookmark this page

Lab: Creating Playbooks

Create a playbook that includes task files and uses loops, conditional statements, and filters to configure managed nodes.

Outcomes

  • Install collections from a requirements.yml file.

  • Gather and display network resource information using the resource_manager role from the network.base collection.

  • Use loops and variable files to configure interfaces for each network platform (IOS and Junos), based on conditional statements.

  • Run a platform-independent task to verify managed node configurations.

As the student user on the workstation machine, use the lab command to prepare your system for this exercise:

[student@workstation ~]$ lab start compreview-cr2

Specifications

Important

All files in this exercise must be stored on the workstation machine in the /home/student/git-repos/compreview directory, or a subdirectory thereof.

The /home/student/git-repos/compreview directory contains an Ansible project managed by Git. The Git project is cloned to that directory when you run the lab start command.

Create a branch named cr2, commit all your finished work to that branch, and then push it to the remote repository at the end of this activity.

  • Configure the Ansible project to search for Ansible Content Collections in the project collections directory and the /usr/share/ansible/collections directory.

  • Configure the Ansible project so that the ansible-galaxy command retrieves collections from the classroom's private automation hub, enabling access to the rh-certified and validated repositories.

    You can access the classroom's private automation hub at https://hub.lab.example.com. Log in as student using redhat123 as the password.

  • Create a requirements.yml file in the project collections directory to install the following collections:

    Collection nameVersionRepository
    network.base 2.0.0 Validated
    ansible.netcommon 4.1.0 Red Hat Certified
    ansible.utils 2.7.0 Red Hat Certified

    For each collection requirement, specify the source URL for the repository that contains the collection.

  • The source URL for Red Hat Ansible Certified Content is https://hub.lab.example.com/api/galaxy/content/rh-certified/.

  • The source URL for Ansible validated content is https://hub.lab.example.com/api/galaxy/content/validated/. When done, install the required collections.

  • Create the following task files in the /home/student/git-repos/compreview/tasks directory to gather the ansible_facts['network_resources']['interfaces'] fact for IOS and Junos managed nodes respectively:

    • cisco.ios.ios.yml

    • junipernetworks.junos.junos.yml

    Include a task in the junipernetworks.junos.junos.yml file to enable the NETCONF service on the Junos managed nodes.

    Use the to_nice_yaml filter to format the output file contents, and then store the facts in a file with the name of the managed node and the .txt extension.

  • Create the following task files in the /home/student/git-repos/compreview/tasks directory to configure interface descriptions for IOS and Junos managed nodes respectively:

    • cisco.ios.ios_interface.yml

    • junipernetworks.junos.junos_interface.yml

    Use loops to configure interface descriptions for each network platform. The group_vars/ios/interfaces.yml and group_vars/junos/interfaces.yml files contain the interface description configurations to be deployed on the managed nodes.

  • Create a playbook named config_interfaces.yml, with a single play, in the /home/student/git-repos/compreview project directory that targets the ios and junos inventory groups of managed nodes, and disables fact gathering for them.

    The playbook must include the following task files, which you created in the tasks directory, that gather facts and configure interface descriptions for the IOS and Junos network platforms:

    • cisco.ios.ios.yml

    • junipernetworks.junos.junos.yml

    • cisco.ios.ios_interface.yml

    • junipernetworks.junos.junos_interface.yml

  • Add a task to the config_interfaces.yml playbook that uses the resource_manager role from the network.base collection to gather interfaces network resources from managed nodes in the ios and junos inventory groups.

    This task must be the first task in the play.

    Important

    The correct variable for the resource_manager role in the network.base collection in this course is the action variable. You might see documentation that shows a different variable. Use the action variable.

  • Add a task to the config_interfaces.yml playbook that uses the ansible.netcommon.cli_command module to verify that the changes were correctly applied.

    This task must be the last task in the play.

    Create the group_vars/ios/verify_config.yml and group_vars/junos/verify_config.yml variable files to hold the verification commands for each network platform in the show_interfaces variable. The verification commands are listed in the following table:

    Managed nodeVerification command
    iosxe1.lab.example.com show interface description
    iosxe2.lab.example.com show interface description
    junos1.lab.example.com show interfaces descriptions
    junos2.lab.example.com show interfaces descriptions
  • Run the config_interfaces.yml playbook and inspect the output to verify that the interfaces have been correctly configured.

  • Commit and push all the changes that you made in the /home/student/git-repos/compreview directory to the remote Git repository. Use Gather facts and configure interface descriptions as the commit message.

    Important

    Make sure that you are in the /home/student directory before grading your work with the lab grade command.

  1. Change to the /home/student/git-repos/compreview Git repository directory and then create a branch named cr2 for this exercise.

    1. Change to the /home/student/git-repos/compreview Git repository directory:

      [student@workstation ~]$ cd ~/git-repos/compreview
      [student@workstation compreview]$
    2. Create a branch named cr2 and check it out:

      [student@workstation compreview]$ git checkout -b cr2
      Switched to a new branch 'cr2'
  2. Configure the Ansible project to search for collections in the project collections directory and the /usr/share/ansible/collections directory.

    1. Open VS Code and click FileOpen Folder.

    2. Navigate to git-reposcompreview and click Open.

      Note

      If prompted, select Trust the authors of all files in the parent folder 'student', and then click Yes, I trust the authors.

    3. Create the /home/student/git-repos/compreview/ansible.cfg file and set the collections_paths variable:

      [defaults]
      collections_paths = ./collections:/usr/share/ansible/collections
  3. Configure the Ansible project so that the ansible-galaxy command retrieves collections from the classroom's private automation hub, enabling access to the rh-certified and validated repositories.

    You can access the classroom's private automation hub at https://hub.lab.example.com. Log in as student using redhat123 as the password.

    1. Use a browser to navigate to the private automation hub at https://hub.lab.example.com, and then log in as student using redhat123 as the password.

    2. From the private automation hub web UI, navigate to CollectionsRepository Management. This page has the parameters that you need for configuring the ansible.cfg file. Click the Copy to clipboard icon in the CLI configuration column and the rh-certified row. Do not close your web browser window.

      Note

      You might need to collapse the web UI navigation bar or zoom out in your web browser to see the Copy to clipboard icon for the CLI configuration column.

    3. Update the ansible.cfg file and add the lines that you copied to the clipboard in the preceding step. The updated ansible.cfg file contains the following content:

      [defaults]
      collections_paths = ./collections:/usr/share/ansible/collections
      
      [galaxy]
      server_list = rh-certified_repo
      
      [galaxy_server.rh-certified_repo]
      url=https://hub.lab.example.com/api/galaxy/content/rh-certified/
      token=<put your token here>
    4. Return to the Repo Management page in the private automation hub web UI. Click the Copy to clipboard icon in the CLI configuration column and the validated row. Do not close your web browser window.

    5. Update the ansible.cfg file to append the lines that you copied to the clipboard in the preceding step. The updated ansible.cfg file now contains the following content:

      [defaults]
      collections_paths = ./collections:/usr/share/ansible/collections
      
      [galaxy]
      server_list = rh-certified_repo
      
      [galaxy_server.rh-certified_repo]
      url=https://hub.lab.example.com/api/galaxy/content/rh-certified/
      token=<put your token here>
      
      [galaxy]
      server_list = validated_repo
      
      [galaxy_server.validated_repo]
      url=https://hub.lab.example.com/api/galaxy/content/validated/
      token=<put your token here>
    6. Update the ansible.cfg file so that it only contains one [galaxy] section. Update the first [galaxy] section so that it lists both the rh-certified_repo and the validated_repo repositories. Remove the second [galaxy] section. The updated ansible.cfg file now contains the following content:

      [defaults]
      collections_paths = ./collections:/usr/share/ansible/collections
      
      [galaxy]
      server_list = rh-certified_repo, validated_repo
      
      [galaxy_server.rh-certified_repo]
      url=https://hub.lab.example.com/api/galaxy/content/rh-certified/
      token=<put your token here>
      
      [galaxy_server.validated_repo]
      url=https://hub.lab.example.com/api/galaxy/content/validated/
      token=<put your token here>
    7. Return to the private automation hub web UI. Navigate to CollectionsAPI token management and then click Load token. Copy the API token.

      Important

      Loading a new token invalidates all your previous tokens.

    8. Using the copied token, update both token lines in the ansible.cfg file. Your token is different from the token displayed in this example. Save and close the file when done:

      [defaults]
      collections_paths = ./collections:/usr/share/ansible/collections
      
      [galaxy]
      server_list = rh-certified_repo, validated_repo
      
      [galaxy_server.rh-certified_repo]
      url=https://hub.lab.example.com/api/galaxy/content/rh-certified/
      token=6ab90d6835a930fa6cb298aa0d03d11a60735577
      
      [galaxy_server.validated_repo]
      url=https://hub.lab.example.com/api/galaxy/content/validated/
      token=6ab90d6835a930fa6cb298aa0d03d11a60735577
  4. Create a requirements.yml file in the project collections directory to install the following collections:

    Collection nameVersionRepository
    network.base 2.0.0 Validated
    ansible.netcommon 4.1.0 Red Hat Certified
    ansible.utils 2.7.0 Red Hat Certified

    For each collection requirement, specify the source URL for the repository that contains the collection, such as the https://hub.lab.example.com/api/galaxy/content/rh-certified/ URL. When done, install the required collections.

    1. Switch to the Terminal tab in VS Code, or return to the GNOME terminal. Use the mkdir command to create the collections directory:

      [student@workstation compreview]$ mkdir collections
    2. Create the /home/student/git-repos/compreview/collections/requirements.yml file. Add the following content to specify the required collections:

      ---
      collections:
        - name: network.base
          version: 2.0.0
          source: https://hub.lab.example.com/api/galaxy/content/validated/
        - name: ansible.netcommon
          version: 4.1.0
          source: https://hub.lab.example.com/api/galaxy/content/rh-certified/
        - name: ansible.utils
          version: 2.7.0
          source: https://hub.lab.example.com/api/galaxy/content/rh-certified/
    3. In the /home/student/git-repos/compreview directory, use the ansible-galaxy command to install the required collections. Add the -r option to specify the location of the collections/requirements.yml file:

      [student@workstation compreview]$ ansible-galaxy collection install \
      -r collections/requirements.yml
      ...output omitted...
      network.base:2.0.0 was installed successfully
      ...output omitted...
      ansible.netcommon:4.1.0 was installed successfully
      ...output omitted...
      ansible.utils:2.7.0 was installed successfully
    4. Use the ansible-galaxy command to list the installed collections:

      [student@workstation compreview]$ ansible-galaxy collection list
      
      # /home/student/git-repos/compreview/collections/ansible_collections
      Collection        Version
      ----------------- -------
      ansible.netcommon 4.1.0
      ansible.utils     2.7.0
      network.base      2.0.0
      
      # /usr/share/ansible/collections/ansible_collections
      Collection               Version
      ------------------------ -------
      redhat.rhel_system_roles 1.20.1

      Important

      The output in the /usr/share/ansible/collections/ansible_collections section displays collections installed on the local system, which is different from collections installed in an automation execution environment.

      To see collections available to automation content navigator from the project directory, run the following command:

      [student@workstation compreview]$ ansible-navigator collections \
      -m interactive
  5. Create the following task files in the /home/student/git-repos/compreview/tasks directory to gather the ansible_facts['network_resources']['interfaces'] fact for IOS and Junos managed nodes, respectively:

    • cisco.ios.ios.yml

    • junipernetworks.junos.junos.yml

    Include a task in the junipernetworks.junos.junos.yml file to enable the NETCONF service on the Junos managed nodes.

    Use the to_nice_yaml filter to format the output file contents, and then store the facts in a file with the name of the managed node and the .txt extension.

    1. Switch to the Terminal tab in VS Code, or return to the GNOME terminal. Use the mkdir command to create the tasks directory:

      [student@workstation compreview]$ mkdir tasks
    2. Create the tasks/cisco.ios.ios.yml task file with the following content:

      ---
      - name: Gather IOS facts
        cisco.ios.ios_facts:
          gather_network_resources:
            - interfaces
      
      - name: Save facts to file
        ansible.builtin.copy:
          content: "{{ ansible_facts | to_nice_yaml }}"
          dest: "{{ inventory_hostname }}.txt"
          mode: "0644"

      Note

      The mode parameter sets the OS-level permissions of the destination file. This parameter is optional, but omitting the parameter results in a lint warning.

    3. Create the tasks/junipernetworks.junos.junos.yml task file with the following content:

      ---
      - name: Enable the NETCONF service
        vars:
          ansible_connection: ansible.netcommon.network_cli
        junipernetworks.junos.junos_netconf:
          netconf_port: 830
          state: present
      
      - name: Gather Junos facts
        junipernetworks.junos.junos_facts:
          gather_network_resources:
            - interfaces
      
      - name: Save facts to file
        ansible.builtin.copy:
          content: "{{ ansible_facts | to_nice_yaml }}"
          dest: "{{ inventory_hostname }}.txt"
          mode: "0644"
  6. Create the following task files in the /home/student/git-repos/compreview/tasks directory to configure interface descriptions for IOS and Junos managed nodes, respectively:

    • cisco.ios.ios_interface.yml

    • junipernetworks.junos.junos_interface.yml

    Use loops to configure interface descriptions for each network platform. The group_vars/ios/interfaces.yml and group_vars/junos/interfaces.yml files contain the interface description configurations to be deployed on the managed nodes.

    1. In VS Code, examine the group_vars/ios/interfaces.yml file.

      This file contains the interface description configurations to be deployed on IOS managed nodes:

      ---
      interfaces:
        iosxe1.lab.example.com:
          - name: Loopback0
            description: Managed by Ansible
      
          - name: GigabitEthernet2
            description: Managed by Ansible
      
        iosxe2.lab.example.com:
          - name: Loopback0
            description: Managed by Ansible
      
          - name: GigabitEthernet2
            description: Managed by Ansible
    2. In VS Code, examine the group_vars/junos/interfaces.yml file.

      This file contains the interface configurations to be deployed on Junos managed nodes.

      ---
      interfaces:
        junos1.lab.example.com:
          - name: em1
            unit_name: 0
            unit_description: Managed by Ansible
      
          - name: fxp0
            unit_name: 0
            unit_description: Managed by Ansible
      
        junos2.lab.example.com:
          - name: em1
            unit_name: 0
            unit_description: Managed by Ansible
      
          - name: fxp0
            unit_name: 0
            unit_description: Managed by Ansible
    3. Create the tasks/cisco.ios.ios_interface.yml file to configure interface descriptions for IOS managed nodes.

      The task file must consist of the following content:

      ---
      - name: Configure interface descriptions on IOS
        cisco.ios.ios_interfaces:
          config:
            - name: "{{ item['name'] }}"
              description: "{{ item['description'] }}"
          state: merged
        loop: "{{ interfaces[inventory_hostname] }}"
    4. Create the tasks/junipernetworks.junos.junos_interface.yml file to configure interface descriptions for Junos managed nodes.

      The task file must consist of the following content:

      ---
      - name: Configure interface descriptions on Junos
        junipernetworks.junos.junos_interfaces:
          config:
            - name: "{{ item['name'] }}"
              units:
                - name: "{{ item['unit_name'] }}"
                  description: "{{ item['unit_description'] }}"
          state: merged
        loop: "{{ interfaces[inventory_hostname] }}"
  7. Create a playbook named config_interfaces.yml in the /home/student/git-repos/compreview project directory that targets the ios and junos inventory groups, and disables fact gathering for these managed nodes. The playbook must include the tasks under the tasks directory that gather facts and configure interface descriptions for IOS and Junos managed nodes.

    1. In VS Code, create the config_interfaces.yml playbook. Target the ios and junos inventory groups. Disable fact gathering.

      ---
      - name: Gather network resource information
        hosts:
          - ios
          - junos
        gather_facts: false
    2. Add a first task to the config_interfaces.yml playbook that includes the tasks/{{ ansible_network_os }}.yml file:

      ---
      - name: Gather network resource information
        hosts:
          - ios
          - junos
        gather_facts: false
        tasks:
          - name: Facts task
            ansible.builtin.include_tasks:
              file: tasks/{{ ansible_network_os }}.yml

      Note

      Notice that by using the {{ ansible_network_os }} variable as part of the task file name, on Cisco IOS managed nodes the task included is cisco.ios.ios.yml and on Juniper Junos managed nodes the task included is junipernetworks.junos.junos.yml.

      Another way to include the tasks is by using conditionals.

    3. Add a second task to the config_interfaces.yml playbook that includes the tasks/{{ ansible_network_os }}_interface.yml file:

      ---
      - name: Gather network resource information
        hosts:
          - ios
          - junos
        gather_facts: false
        tasks:
          - name: Facts task
            ansible.builtin.include_tasks:
              file: tasks/{{ ansible_network_os }}.yml
      
          - name: Configure interface descriptions
            ansible.builtin.include_tasks:
              file: tasks/{{ ansible_network_os }}_interface.yml
  8. Add a task to the config_interfaces.yml playbook that uses the resource_manager role from the network.base collection to gather interfaces network resources from managed nodes in the ios and junos inventory groups.

    Important

    The resource_manager role in the network.base collection uses a variable to determine the type of actions that the role should perform. The name of this variable changes depending on which version of the collection that you use. The correct variable for the resource_manager role in this course is the action variable.

    1. From the private automation hub web UI, navigate to CollectionsCollections.

    2. In the Filter by repository list, choose Validated.

    3. Click the base collection and go to its Documentation tab to review the documentation.

    4. Edit the config_interfaces.yml playbook in VS Code. Add a third task to the playbook that uses the resource_manager role from the network.base collection to gather interfaces network resources from managed nodes in the ios and junos inventory groups:

      ---
      - name: Gather network resource information
        hosts:
          - ios
          - junos
        gather_facts: false
        tasks:
          - name: Facts task
            ansible.builtin.include_tasks:
              file: tasks/{{ ansible_network_os }}.yml
      
          - name: Configure interface descriptions
            ansible.builtin.include_tasks:
              file: tasks/{{ ansible_network_os }}_interface.yml
      
          - name: Network Resource Manager
            ansible.builtin.include_role:
              name: network.base.resource_manager
            vars:
              action: gather
              resources:
                - 'interfaces'
  9. Add a task to the config_interfaces.yml playbook that uses the ansible.netcommon.cli_command module to verify that the changes were correctly applied.

    Create the group_vars/ios/verify_config.yml and group_vars/junos/verify_config.yml variable files to hold the verification commands for each network platform in the show_interfaces variable. The verification commands are listed in the following table:

    Managed nodeVerification command
    iosxe1.lab.example.com show interface description
    iosxe2.lab.example.com show interface description
    junos1.lab.example.com show interfaces descriptions
    junos2.lab.example.com show interfaces descriptions
    1. Edit the playbook to use the ansible.netcommon.cli_command module to verify that the changes were correctly applied:

      ---
      - name: Gather network resource information
        hosts:
          - ios
          - junos
        gather_facts: false
        tasks:
          - name: Facts task
            ansible.builtin.include_tasks:
              file: "tasks/{{ ansible_network_os }}.yml"
      
          - name: Configure interface descriptions
            ansible.builtin.include_tasks:
              file: tasks/{{ ansible_network_os }}_interface.yml
      
          - name: Network Resource Manager
            ansible.builtin.include_role:
              name: network.base.resource_manager
            vars:
              action: gather
              resources:
                - 'interfaces'
      
          - name: Run a command to verify interface configurations
            vars:
              ansible_connection: ansible.netcommon.network_cli
            ansible.netcommon.cli_command:
              command: "{{ show_interfaces }}"
            register: result
      
          - name: Display the results
            ansible.builtin.debug:
              var: result['stdout_lines']
    2. Create a variable file named group_vars/ios/verify_config.yml that holds the verification commands for IOS managed nodes.

      The variable file must consist of the following content:

      ---
      show_interfaces: "show interface description"
    3. Create a variable file named group_vars/junos/verify_config.yml that holds the verification commands for IOS managed nodes.

      The variable file must consist of the following content:

      ---
      show_interfaces: "show interfaces descriptions"
  10. Run the config_interfaces.yml playbook again and inspect the output to verify that the interfaces have been correctly configured:

    [student@workstation compreview]$ ansible-navigator run config_interfaces.yml
    ...output omitted...
    
    TASK [Display the results] *******************************************************
    ok: [junos1.lab.example.com] => {
        "result['stdout_lines']": [
            "Interface       Admin Link Description",
            "em1.0           up    up   Managed by Ansible",
            "fxp0.0          up    up   Managed by Ansible"
        ]
    }
    ok: [junos2.lab.example.com] => {
        "result['stdout_lines']": [
            "Interface       Admin Link Description",
            "em1.0           up    up   Managed by Ansible",
            "fxp0.0          up    up   Managed by Ansible"
        ]
    }
    ok: [iosxe2.lab.example.com] => {
        "result['stdout_lines']": [
            "Interface                    Status       Protocol Description",
            "Gi1                          up           up       ",
            "Gi2                          up           up       Managed by Ansible",
            "Lo0                          up           up       Managed by Ansible"
        ]
    }
    ok: [iosxe1.lab.example.com] => {
        "result['stdout_lines']": [
            "Interface                    Status       Protocol Description",
            "Gi1                          up           up       ",
            "Gi2                          up           up       Managed by Ansible",
            "Lo0                          up           up       Managed by Ansible"
        ]
    }
    ...output omitted...
  11. Commit and push all the changes that you made in the /home/student/git-repos/compreview directory to the remote Git repository. Use Gather facts and configure interface descriptions as the commit message.

    1. Use VS Code or the git add command to add the new and updated files and directories:

      [student@workstation compreview]$ git add .
    2. Use VS Code or the git status command to display the list of files that you staged for the next commit:

      [student@workstation compreview]$ git status
      On branch cr2
      Changes to be committed:
        (use "git restore --staged <file>..." to unstage)
      ...output omitted...
    3. Use VS Code or the git commit command to commit the files. Use Gather facts and configure interface descriptions as the commit message:

      [student@workstation compreview]$ git commit -m \
      "Gather facts and configure interface descriptions"
      [cr2 46a0ba4] Gather facts and configure interface descriptions
      ...output omitted...
    4. Use VS Code or the git push command to update the remote Git repository:

      [student@workstation compreview]$ git push -u origin cr2
      ...output omitted...
      To git.lab.example.com:student/compreview
       * [new branch]      cr2 -> cr2
      Branch 'cr2' set up to track remote branch 'cr2' from 'origin'.
  12. Close the /home/student/git-repos/compreview directory in VS Code.

    Return to the /home/student directory in the GNOME terminal.

    1. Click FileClose Folder in VS Code to close the /home/student/git-repos/compreview directory.

    2. Run the cd command in the GNOME terminal to return to the student home directory:

      [student@workstation compreview]$ cd

Evaluation

As the student user on the workstation machine, use the lab command to grade your work. Correct any reported failures and rerun the command until successful.

[student@workstation ~]$ lab grade compreview-cr2

Finish

As the student user on the workstation machine, use the lab command to complete this exercise. This step is important to ensure that resources from previous exercises do not impact upcoming exercises.

[student@workstation ~]$ lab finish compreview-cr2

Revision: do457-2.3-7cfa22a