Bookmark this page

Lab: Managing Variables and Facts

Write and run an Ansible Playbook that uses variables and facts, and which gets values for its variables from a survey when run in automation controller.

Outcomes

  • Configure variable files for playbooks.

  • Use filters to format output.

  • Create a survey to prompt for variables used by a job template.

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

This command installs the required software, downloads an automation execution environment, and creates the required resources for the exercise.

[student@workstation ~]$ lab start manage-review

Instructions

This lab contains two parts. In the first part of the lab, you work with files on the workstation machine and push your changes to remote Git repositories. In the second part of the lab, you synchronize your changes with two automation controller projects and then add a survey to an existing job template.

You can access the automation controller web UI at https://controller.lab.example.com using admin as the username and redhat as the password.

  1. Your automation controller instance contains the Inventories project resource, which uses the git@git.lab.example.com:student/inventories Git repository. The Common inventory resource uses the inventory file in that Git repository to populate automation controller host resources.

    Rather than defining variables in a single inventory file, you have decided to move group variables into their own files.

    Clone the git@git.lab.example.com:student/inventories Git repository into the /home/student/git-repos directory and then check out the exercise branch.

    1. Use either VS Code or the git clone command to clone the git@git.lab.example.com:student/inventories Git repository into the /home/student/git-repos directory:

      [student@workstation ~]$ cd ~/git-repos/
      [student@workstation git-repos]$ git clone \
      git@git.lab.example.com:student/inventories
    2. Use either VS Code or the git checkout exercise command to check out the exercise branch:

      [student@workstation git-repos]$ cd inventories
      [student@workstation inventories]$ git checkout exercise
      Switched to branch 'exercise'
  2. Create the necessary directories and then create the following files. Move the connection variables from the /home/student/git-repos/inventories/inventory file into the corresponding variable file for each inventory group and ensure that the variables use YAML format. When finished, the /home/student/git-repos/inventories/inventory file should no longer contain variables.

    • /home/student/git-repos/inventories/group_vars/ios/connection.yml

    • /home/student/git-repos/inventories/group_vars/junos/connection.yml

    1. Open the /home/student/git-repos/inventories directory in VS Code. Click FileOpen Folder.

      Navigate to Homegit-reposinventories 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.

    2. Click the inventory file. The file contains the following content. Notice that the file defines variables for the ios and junos groups:

      [ios]
      iosxe1.lab.example.com
      iosxe2.lab.example.com
      
      [ios:vars]
      ansible_connection=ansible.netcommon.network_cli
      ansible_network_os=cisco.ios.ios
      
      [junos]
      junos1.lab.example.com
      junos2.lab.example.com
      
      [junos:vars]
      ansible_connection=ansible.netcommon.netconf
      ansible_network_os=junipernetworks.junos.junos
    3. Switch to the Terminal tab in VS Code, or change to the /home/student/git-repos/inventories directory in a GNOME terminal. Create the group_vars/ios and group_vars/junos directories to hold the variables files for the managed nodes. Use separate mkdir commands, or use the following mkdir command. If desired, use the -v option to display the four directories created by the command:

      [student@workstation inventories]$ mkdir -pv group_vars/{ios,junos}
      mkdir: created directory 'group_vars'
      mkdir: created directory 'group_vars/ios'
      mkdir: created directory 'group_vars/junos'
    4. Create the group_vars/ios/connection.yml file and define the two variables currently found in the inventory file for the ios group:

      ---
      ansible_connection: ansible.netcommon.network_cli
      ansible_network_os: cisco.ios.ios
    5. Create the group_vars/junos/connection.yml file and define the two variables currently found in the inventory file for the junos group:

      ---
      ansible_connection: ansible.netcommon.netconf
      ansible_network_os: junipernetworks.junos.junos
    6. Update the inventory file so that it does not contain variables. The updated file contains the following content:

      [ios]
      iosxe1.lab.example.com
      iosxe2.lab.example.com
      
      [junos]
      junos1.lab.example.com
      junos2.lab.example.com
  3. Define the following logging variables for the ios group in the /home/student/git-repos/inventories/group_vars/ios/syslog_config.yml file. Create the file and any directories as needed.

    VariableValue
    severity_level warnings
    facility local5
    log_host_1 192.168.10.10/24
    log_host_2 192.168.11.10/24
    1. Create the group_vars/ios/syslog_config.yml file with the following content:

      ---
      severity_level: warnings
      facility: local5
      log_host_1: 192.168.10.10/24
      log_host_2: 192.168.11.10/24
  4. Commit and push all the changes that you made in the /home/student/git-repos/inventories directory to the remote Git repository. Add a descriptive commit message, such as Move variables to separate files.

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

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

      [student@workstation inventories]$ git status
      On branch exercise
      Your branch is up to date with 'origin/exercise'.
      
      Changes to be committed:
        (use "git restore --staged <file>..." to unstage)
              new file:   group_vars/ios/connection.yml
              new file:   group_vars/ios/syslog_config.yml
              new file:   group_vars/junos/connection.yml
              modified:   inventory
    3. Use VS Code or the git commit command to commit the files. Use a descriptive commit message.

      [student@workstation inventories]$ git commit \
      -m 'Move variables to separate files'
      [exercise ce28988] Move variables to separate files
       4 files changed, 11 insertions(+), 8 deletions(-)
       create mode 100644 group_vars/ios/connection.yml
       create mode 100644 group_vars/ios/syslog_config.yml
       create mode 100644 group_vars/junos/connection.yml
    4. Use VS Code or the git push command to update the remote Git repository.

      [student@workstation inventories]$ git push -u origin exercise
      ...output omitted...
      To git.lab.example.com:student/inventories
         ef6f142..ce28988  exercise -> exercise
      Branch 'exercise' set up to track remote branch 'exercise' from 'origin'.
  5. Click FileClose Folder in VS Code to close the /home/student/git-repos/inventories directory, or run the cd command in a GNOME terminal to return to the student home directory.

    [student@workstation inventories]$ cd
  6. The Syslog automation controller project resource uses the git@git.lab.example.com:student/syslog Git repository. Clone that Git repository into the /home/student/git-repos directory and then check out the exercise branch. Update the syslog.yml playbook in that repository so that it uses the severity_level, facility, log_host_1, and log_host_2 variables, which you defined in the /home/student/git-repos/inventories/group_vars/ios/syslog_config.yml file.

    Important

    Use an option to the ansible.utils.ipaddr filter to extract the IP addresses of the log_host_1 and log_host_2 variables. For example, if the log_host_1 variable has a value of 192.168.0.5/24, then the filter should return the 192.168.0.5 IP address.

    1. Use either VS Code or the git clone command to clone the git@git.lab.example.com:student/syslog Git repository into the /home/student/git-repos directory:

      [student@workstation ~]$ cd ~/git-repos/
      [student@workstation git-repos]$ git clone \
      git@git.lab.example.com:student/syslog
    2. Use either VS Code or the git checkout exercise command to check out the exercise branch:

      [student@workstation git-repos]$ cd syslog
      [student@workstation syslog]$ git checkout exercise
      Switched to branch 'exercise'
    3. Open the /home/student/git-repos/syslog directory in VS Code. Click FileOpen Folder.

      Navigate to Homegit-repossyslog and click Open.

    4. Update the syslog.yml playbook so that it uses variables. Replace the specific values in the playbook with their associated variable names. Use the ansible.utils.ipaddr('address') filter to extract the IP address from the log_host_1 and log_host_2 variables. The updated playbook uses the following highlighted lines:

      ---
      - name: Confgure syslog on IOS managed nodes
        hosts: ios
        gather_facts: false
        tasks:
          - name: Remove syslog configuration
            cisco.ios.ios_logging_global:
              state: deleted
      
          - name: Configure syslog
            cisco.ios.ios_logging_global:
              config:
                trap: "{{ severity_level }}"
                facility: "{{ facility }}"
                hosts:
                  - host: "{{ log_host_1 | ansible.utils.ipaddr('address') }}"
                  - host: "{{ log_host_2 | ansible.utils.ipaddr('address') }}"
                logging_on: enable
              state: replaced
  7. Verify that the syslog.yml playbook runs successfully.

    Important

    The automation controller Cisco IOX XE Auth machine credential defines the student username and authenticates using an SSH private key.

    Add the -u student and -k options when running the ansible-navigator command. When prompted for the SSH password, type student and press Enter.

    1. Switch to the Terminal tab in VS Code, or change to the /home/student/git-repos/syslog directory in a GNOME terminal. Run the syslog.yml playbook and use the -u student and -k options. When prompted for the SSH password, type student and press Enter.

      [student@workstation syslog]$ ansible-navigator run syslog.yml -u student -k
      SSH password: student
      
      PLAY [Confgure syslog on IOS managed nodes] ************************************
      
      TASK [Remove syslog configuration] *********************************************
      ok: [iosxe1.lab.example.com]
      ok: [iosxe2.lab.example.com]
      
      TASK [Configure syslog] ********************************************************
      changed: [iosxe1.lab.example.com]
      changed: [iosxe2.lab.example.com]
      
      PLAY RECAP *********************************************************************
      iosxe1.lab.example.com     : ok=2    changed=1    unreachable=0    failed=0  ...
      iosxe2.lab.example.com     : ok=2    changed=1    unreachable=0    failed=0  ...
  8. Update the /home/student/git-repos/syslog/check_syslog_config.yml playbook.

    • The playbook must target managed nodes in the ios inventory group.

    • The playbook must gather configuration facts about the managed nodes. Your playbook does this correctly if it defines the ansible_facts['net_config'] fact.

    • Add a task that uses the ansible.builtin.debug module to display any line that matches the ^logging .*$ pattern in the ansible_facts['net_config'] fact.

      Important

      You can use the regex_findall filter to search for the specified pattern. Add the multiline=true option to the filter.

    1. Update the check_syslog_config.yml playbook to target managed nodes in the ios inventory group.

      ---
      - name: Display existing logging settings
        hosts: ios
      ...output omitted...
    2. Add a task to gather configuration facts. Your task might look similar to the following and should use either the config or all subset:

      ---
      - name: Display existing logging settings
        hosts: ios
        gather_facts: false
        tasks:
          - name: Gather configuration facts
            cisco.ios.ios_facts:
              gather_subset:
                - config
      ...output omitted...
    3. Update the Show logging configuration task so that it uses the regex_findall filter. The completed playbook should have content similar to the following:

      ---
      - name: Display existing logging settings
        hosts: ios
        gather_facts: false
        tasks:
          - name: Gather configuration facts
            cisco.ios.ios_facts:
              gather_subset:
                - config
      
          - name: Show logging configuration
            ansible.builtin.debug:
              var: >-
                ansible_facts['net_config'] |
                regex_findall('^logging .*$', multiline=true)
  9. Run the /home/student/git-repos/syslog/check_syslog_config.yml playbook to display the current logging configuration of the managed nodes in the ios inventory group. Add the -u student and -k options when running the ansible-navigator command. When prompted, use student for the password.

    If the playbook succeeds, then add, commit, and push the changes that you made to the syslog.yml and check_syslog_config.yml files to the remote Git repository. Add a descriptive commit message, such as Use variables and show configuration.

    1. Run the check_syslog_config.yml playbook and use the -u student and -k options. When prompted for the SSH password, type student and press Enter.

      The logging settings use the values of the variables defined in the /home/student/git-config/inventories/group_vars/ios/syslog_config.yml file.

      [student@workstation syslog]$ ansible-navigator run check_syslog_config.yml \
      -u student -k
      SSH password: student
      
      PLAY [Display existing logging configuration] **********************************
      
      TASK [Gather configuration facts] **********************************************
      ok: [iosxe2.lab.example.com]
      ok: [iosxe1.lab.example.com]
      
      TASK [Show logging configuration] **********************************************
      ok: [iosxe2.lab.example.com] => {
          "ansible_facts['net_config'] | regex_findall('^logging .*$', multiline=true)": [
              "logging trap warnings",
              "logging facility local5",
              "logging host 192.168.10.10",
              "logging host 192.168.11.10"
          ]
      }
      ok: [iosxe1.lab.example.com] => {
          "ansible_facts['net_config'] | regex_findall('^logging .*$', multiline=true)": [
              "logging trap warnings",
              "logging facility local5",
              "logging host 192.168.10.10",
              "logging host 192.168.11.10"
          ]
      }
      
      PLAY RECAP *********************************************************************
      iosxe1.lab.example.com     : ok=2    changed=0    unreachable=0    failed=0  ...
      iosxe2.lab.example.com     : ok=2    changed=0    unreachable=0    failed=0  ...
    2. Use VS Code or the git add command to add the updated files:

      [student@workstation syslog]$ git add syslog.yml check_syslog_config.yml
    3. Use VS Code or the git commit command to commit the files. Use a descriptive commit message.

      [student@workstation syslog]$ git commit \
      -m 'Use variables and show configuration'
      [exercise f769bdd] Use variables and show configuration
       2 files changed, 19 insertions(+), 20 deletions(-)
       rewrite check_syslog_config.yml (73%)
    4. Use VS Code or the git push command to update the remote Git repository:

      [student@workstation syslog]$ git push -u origin exercise
      ...output omitted...
      To git.lab.example.com:student/syslog
         17e7962..f769bdd  exercise -> exercise
      Branch 'exercise' set up to track remote branch 'exercise' from 'origin'.
  10. From the automation controller web UI, update the Inventories and Syslog projects so that the projects contain the most recent Git repository changes. For the Common inventory, synchronize its source and then verify that the ios host group uses the variables that you defined in the syslog_config.yml file.

    1. Navigate to https://controller.lab.example.com and log in as admin using redhat as the password.

    2. Synchronize the Inventories project.

      Navigate to ResourcesProjects and then click the Sync Project icon for the Inventories project. The project status changes from Pending, to Running, to Successful.

    3. Synchronize the Syslog project.

      Navigate to ResourcesProjects and then click the Sync Project icon for the Syslog project. The project status changes from Pending, to Running, to Successful.

    4. Synchronize the Common Inventories source for the Common inventory.

      Navigate to ResourcesInventories and then click Common. Click the Sources tab and then click the Start sync process icon for the Common Inventories source. The source status changes from Pending, to Running, to Successful.

    5. View the populated variables for the ios group.

      Click the Groups tab and then click ios. The Variables field displays the following variables in JSON format:

      {
        "ansible_connection": "ansible.netcommon.network_cli",
        "ansible_network_os": "cisco.ios.ios",
        "facility": "local5",
        "log_host_1": "192.168.10.10/24",
        "log_host_2": "192.168.11.10/24",
        "severity_level": "warnings"
      }
  11. Although the inventory variables defined for the ios group provide one method for configuring logging settings, you want to make it easier to change those settings when someone runs the Configure IOS syslog job template.

    Add a survey to the Configure IOS syslog job template with the following questions:

    Table 4.6. Survey Question 1

    FieldValue
    Question Primary syslog destination host
    Answer variable name log_host_1
    Answer type Text
    Required (not selected)
    Minimum length 1
    Maximum length 18

    Table 4.7. Survey Question 2

    FieldValue
    Question Secondary syslog destination host
    Answer variable name log_host_2
    Answer type Text
    Required (not selected)
    Minimum length 1
    Maximum length 18

    Table 4.8. Survey Question 3

    FieldValue
    Question Logging facility
    Answer variable name facility
    Answer type Text
    Required (not selected)
    Minimum length 1
    Maximum length 6

    Table 4.9. Survey Question 4

    FieldValue
    Question Logging severity level
    Answer variable name severity_level
    Answer type Text
    Required (not selected)
    Minimum length 1
    Maximum length 13

    1. Navigate to ResourcesTemplates and then click the Configure IOS syslog link. Click the Survey tab.

    2. Click Add and then use the settings in the "Survey Question 1" table to create the Primary syslog destination host survey question. Click Save.

    3. Click Add and then use the settings in the "Survey Question 2" table to create the Secondary syslog destination host survey question. Click Save.

    4. Click Add and then use the settings in the "Survey Question 3" table to create the Logging facility survey question. Click Save.

    5. Click Add and then use the settings in the "Survey Question 4" table to create the Logging severity level survey question. Click Save.

  12. Enable the survey for the Configure IOS syslog job template.

    1. Navigate to ResourcesTemplates and click the Configure IOS syslog link. Click the Survey tab.

    2. Click Survey Disabled and verify that the label changes to Survey Enabled.

  13. Launch the Configure IOS syslog job template and use the following answers to the survey questions. After the job completes, run the /home/student/git-repos/syslog/check_syslog_config.yml playbook to display the updated logging configuration.

    • Primary syslog destination host: 192.168.80.10/24

    • Secondary syslog destination host: 192.168.80.11/24

    • Logging facility: local2

    • Logging severity level: errors

    1. Navigate to ResourcesTemplates and click the Launch Template icon for the Configure IOS syslog job template.

      The automation controller web UI opens a dialog box with the job template survey.

    2. Answer the survey questions using the following table and then click Next to preview the settings for the job template.

      Survey QuestionAnswer
      Primary syslog destination host 192.168.80.10/24
      Secondary syslog destination host 192.168.80.11/24
      Logging facility local2
      Logging severity level errors
    3. Click Launch to launch the job template and use the variables defined by the survey. The Configure IOS syslog job displays a status of Successful.

    4. Switch back to the Terminal tab in VS Code, or ensure that you are in the /home/student/git-repos/syslog directory in a GNOME terminal.

      Run the check_syslog_config.yml playbook. The playbook output displays the values that you entered using the job template survey.

      [student@workstation syslog]$ ansible-navigator run check_syslog_config.yml \
      -u student -k
      SSH password: student
      
      ...output omitted...
      TASK [Show logging configuration] **********************************************
      ok: [iosxe2.lab.example.com] => {
          "ansible_facts['net_config'] | regex_findall('^logging .*$', multiline=true)": [
              "logging trap errors",
              "logging facility local2",
              "logging host 192.168.80.10",
              "logging host 192.168.80.11"
          ]
      }
      ok: [iosxe1.lab.example.com] => {
          "ansible_facts['net_config'] | regex_findall('^logging .*$', multiline=true)": [
              "logging trap errors",
              "logging facility local2",
              "logging host 192.168.80.10",
              "logging host 192.168.80.11"
          ]
      }
      ...output omitted...
  14. Click FileClose Folder in VS Code to close the /home/student/git-repos/syslog directory, or run the cd command in a GNOME terminal to return to the student home directory.

    [student@workstation syslog]$ 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 manage-review

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 manage-review

Revision: do457-2.3-7cfa22a