Exploring Variables and More in Ansible

Exploring Variables and More in Ansible

This article covers the order of Ansible variable configurations, methods for defining variables, and the concept and usage of fact variables. It discusses decision-making using the "when" keyword and demonstrates combining conditions with loops. The usage of handlers for conditional task execution and the organizational benefits of creating reusable roles in Ansible is also explained. Practical examples and commands to structure and run Ansible playbooks and roles are provided throughout.

Defining Variables

  1. You can define the variables through the command line but it is not used often as it is not the best practice to do.

eg:- ansible-playbook -e USRNM=cliuser -e COMM=cliuser vars_precedence.yaml

  1. Defining the variable directly in the playbook and using register and debug to print out the result stored in the variable "output".

  1. In inventory file you can have group_vars/all, group_vars/groupname, host_vars/hostname. In this kind of variable declaration the group formed in the inventory file will take the variable from group_vars/groupname and if there is a host who is not included in the group than it will use group_vars/all or the variables defined in the host_vars/hostname.

Order of Ansible variable configurations

  1. ANSIBLE_CONFIG (Environmental var if saved)

  2. ansible.cfg (in the current directory)

  3. ~/.ansible.cfg (in the home directory)

  4. /etc/ansible/ansible.cfg

Fact Variables in Ansible

In Ansible, a "fact" is a piece of information about a remote system that Ansible discovers and makes available during the execution of playbooks. These facts are gathered by the setup module and can include details such as the system's operating system, IP addresses, memory, CPU details, and more. Facts are stored as variables and can be used within playbooks to make decisions or customize behavior.

- hosts: all
  gather_facts: yes
  tasks:
    - name: Display all facts
      debug:
        var: ansible_facts

Decision Making - (We use when)

In Ansible, the "when" keyword is used to control whether a task or a set of tasks should be executed based on certain conditions. This allows for decision-making within your playbooks, making them more dynamic and responsive to the state of the target systems.

- hosts: webservers
  tasks:
    - name: Ensure Apache is installed
      apt:
        name: apache2
        state: present
      when: ansible_facts['os_family'] == "Debian"

    - name: Ensure httpd is installed
      yum:
        name: httpd
        state: present
      when: ansible_facts['os_family'] == "RedHat"

Loop integrated with when :-

In here, the "item" will be replaced by the items given in the loop.

 - name: Install packages on RedHat-based systems
      yum:
        name: "{{ item }}"
        state: present
      loop:
        - httpd
        - vim
        - curl
      when: ansible_facts['os_family'] == "RedHat"

Handlers

Handlers are special tasks that are triggered by the notify directive in other tasks. Handlers are typically used to perform actions that should only occur if there has been a change, such as restarting a service after a configuration file has been modified. Handlers are executed at the end of a play, once all tasks have been completed.

- hosts: webservers
  tasks:
    - name: Install Apache
      apt:
        name: apache2
        state: present
      notify: Restart Apache
  handlers:
    - name: Restart Apache
      service:
        name: apache2
        state: restarted

Roles in Ansible

We create roles in Ansible at an organizational level to reuse them in different projects or environments. If you are not utilizing reusability, there is no point in creating roles in Ansible.

The main thing about the roles is that when you write a playbook you define everything in the playbook like :- handlers, tasks, vars etc. , But after creating roles you can create different files for each of these things so you can delete,read and modify different sections of the playbook easily.

Creating role :

  1. Go to the directory in which you want to create the role.

  2. Create a directory by name roles in the folder.

  3. Get in the roles directory and run the command :-

  4.   ansible-galaxy init <role-name>
    
  5. Now run the tree command in the roles directory to see the structure of the directory.

Partitioning the different section of the playbook :

  1. After this you can structure your project by copying the files in the roles folder. like:-

  2.   #For the vars you can do :- 
      vim roles/<role-name>/vars/main.yml
      #OR for the task section you can do :- 
      vim roles/<role-name>/tasks/main.yml
      #OR for the handlers section you can do :- 
      vim roles/<role-name>/handlers/main.yml
    
  3. Here, you store it in the role and delete the previous files.

Defining the roles in the Playbook

- name: Provisioning servers
  hosts: all
  roles:
    - <role-name>

and now when you run this playbook the role will get executed.

Did you find this article valuable?

Support Saurabh's blog by becoming a sponsor. Any amount is appreciated!