Managing Variables and Gathering Facts in Ansible

Managing Variables and Gathering Facts in Ansible

Introduction

In the realm of IT automation, Ansible stands out for its simplicity and power. Understanding how to manage variables and gather facts is crucial for creating dynamic, flexible and efficient playbooks. This guide will take you through the essentials of defining and using variables, understanding variable precedence and scope, gathering facts about your hosts and using registered variables to capture command outputs.

Defining and Using Variables in Playbooks

Variables in Ansible allow you to store values that can be reused across your playbooks. They help in making your playbooks dynamic and more manageable. Variables can be defined in various places, including inventory files, playbooks or even external files.

Example of Defining Variables

Here’s how you can define variables within a playbook :-

---
- name: Install Apache on web servers
  hosts: webservers
  vars:
    http_port: 80
    max_clients: 200
  tasks:
    - name: Install Apache
      apt:
        name: apache2
        state: present
    - name: Configure Apache
      template:
        src: /path/to/httpd.conf.j2
        dest: /etc/apache2/httpd.conf
      notify:
        - Restart Apache

In this example http_port and max_clients are variables that can be used within tasks.

Variable Precedence and Scope

Ansible variables can be defined in multiple locations and their precedence determines which value gets applied when there are conflicts. The order of precedence is as follows (from lowest to highest) :-

  1. Role defaults

  2. Inventory file or script group vars

  3. Inventory group_vars/all

  4. Playbook group_vars/all

  5. Inventory group_vars/*

  6. Playbook group_vars/*

  7. Inventory file or script host vars

  8. Inventory host_vars/*

  9. Playbook host_vars/*

  10. Host facts

  11. Play vars

  12. Play vars_prompt

  13. Play vars_files

  14. Role vars (defined in role/vars/main.yml)

  15. Block vars (only for tasks in block)

  16. Task vars (only for the task)

  17. Role (and include) params

  18. Set_facts / registered vars

  19. Command line vars (e.g., -e "var=value")

Example of Variable Precedence

---
- name: Variable precedence
  hosts: webservers
  vars:
    message: "This is from play vars"
  tasks:
    - name: Print the message
      debug:
        msg: "{{ message }}"

If you override the message variable using -e "message='This is from command line'" the command line value will take precedence.

Gathering and Using Facts About Your Hosts

Ansible automatically gathers facts about your hosts which are stored as variables. These facts provide useful information such as OS type, IP addresses and available memory.

Gathering Facts

Facts are gathered using the setup module which runs by default at the start of a play. You can also explicitly gather facts using :-

- name: Gather facts
  hosts: all
  tasks:
    - name: Gather facts
      setup:

Using Facts

Facts can be used just like any other variable. For example to display the OS type of a host :-

- name: Display OS type
  hosts: all
  tasks:
    - name: Show OS type
      debug:
        msg: "The OS type is {{ ansible_os_family }}"

Using Registered Variables to Capture Command Outputs

Registered variables capture the output of a task which can then be used in subsequent tasks. This is useful for conditional operations based on the output of a command.

Example of Using Registered Variables

---
- name: Using registered variables
  hosts: webservers
  tasks:
    - name: Check if Apache is installed
      shell: dpkg -l | grep apache2
      register: apache_installed
      ignore_errors: yes

    - name: Display installation status
      debug:
        msg: "Apache is installed" 
      when: apache_installed.rc == 0

In this example the output of the command is captured in apache_installed and the next task is executed based on whether Apache is installed.

Example Playbook :- Using Variables and Facts

Let's put everything together in an example playbook that defines variables, gathers facts and uses registered variables :-

---
- name: Using variables and facts
  hosts: webservers
  vars:
    http_port: 80
    document_root: /var/www/html
  tasks:
    - name: Gather facts
      setup:
    - name: Display OS type
      debug:
        msg: "The OS type is {{ ansible_os_family }}"
    - name: Check available memory
      debug:
        msg: "Available memory is {{ ansible_memtotal_mb }} MB"
    - name: Install Apache
      apt:
        name: apache2
        state: present
    - name: Start Apache
      service:
        name: apache2
        state: started
    - name: Check if Apache is running
      shell: systemctl status apache2
      register: apache_status
      ignore_errors: yes
    - name: Display Apache status
      debug:
        msg: "Apache is running"
      when: apache_status.rc == 0
    - name: Display HTTP port
      debug:
        msg: "The HTTP port is {{ http_port }}"
    - name: Display Document Root
      debug:
        msg: "The Document Root is {{ document_root }}"

Running the Playbook

Save the playbook as variables_facts.yml and run it using the following command :-

ansible-playbook -i inventory.ini variables_facts.yml

This playbook demonstrates how to use variables, gather facts and register command outputs.

Conclusion

Understanding how to manage variables and gather facts in Ansible is crucial for creating robust and flexible automation scripts. By leveraging variables you can make your playbooks dynamic and reusable. Gathering facts allows you to make informed decisions based on the state of your hosts and registered variables enable conditional operations based on command outputs.

With this foundational knowledge, you're now equipped to craft more advanced and powerful Ansible playbooks. Let's continue exploring the capabilities of Ansible in future posts diving deeper into advanced topics and real-world use cases to further enhance your automation skills.

Let's connect and grow on Linkedin :Click Here

Let's connect and grow on Twitter :Click Here

Happy Automation!!!

Happy Reading!!!

Sudha Yadav