Variables in Ansible

There are times when we have a bunch of similar servers but they are not exactly the same. For example, consider webservers. They may all run a webserver and might have same set of users accounts and acls but they may vary slightly in configuration. For such scenarios, variables are very helpful. A variable name can only consist of letters, numbers, and underscores and should always start with a letter. Below is an example of a variable definition in a playbook.

- hosts: webservers
  vars:
    http_port: 80
    domain: owncloud

While variables can be used in defining task blocks, most widespread use of variables is in defining configurations. We can use variable and templates to dynamically generate configurations and deploy on wide range of servers.

Ansible provides several variables off the shelf. Some of the most common ones are:

A full list can be obtained by using the following command:

$ ansible -i ~/tmp/inventory all -m setup

Setting up custom facts

Ansble can read custom facts from a remote machine. These facts are communicated to during an Ansible run and can be utilized to run playbooks and tasks in conditional manner.

Ansible can read any INI or json style file created in directory /etc/ansible/facts.d and make them available under ansible_local fact.

[general]
fact1=myfact1
fact2=myfact2

Now we can access these facts normally. To check if these facts are available, we can check out the facts.

ansible -i ~/tmp/inventory all -m setup -a "filter=ansible_local"

Registering Variables

Ansible can register and save the output of a task in a variable. This variable can be used later to invoke tasks conditionally.

- hosts: web_servers
  tasks:
  - shell: exit 5
    register: result_var
    ignore_errors: True

  - shell: echo return was 5
    when: result_var.rc == 5

Templates

Templates help in generating configurations on the fly. Ansible uses Jinja2 templates which ends with .j2 extension. Based on variables, these templates fill the blanks and generate configurations. These configurations are then uploaded to the target server. Example template:

<VirtualHost *:{{ http_port }} >
        ServerAdmin aditya@adityapatawari.com
        ServerName {{ domain }}
        Options Indexes MultiViews FollowSymLinks
        DirectoryIndex index.php
        DocumentRoot /var/www/html/owncloud
        <Directory /var/www/html/owncloud>
        Options FollowSymLinks
        AllowOverride All
    </Directory>
</VirtualHost>

Now we can use template module to read variables and fit the correct values and then put the configuration at the right place.