Ansible Variables

Variables in Ansible are nothing but similar to the variables in a programming language. Ansible makes use of variables to better customize the execution of tasks and playbooks. Using variables it's possible to use the same playbook with different targets and environments.

You can assign a value to the variable and use it anywhere in the playbook. You can define these variables in your playbooks, in the inventory file, or at the command line. You can also create them during runtime by assigning a return value to the new variable. Once created, you can use them in conditional statements, in loops, or as arguments.

Defining a variable

A variable name can only include letters, numbers, and underscores and it cannot begin with a number. You can define a variable using standard YAML syntax. For example:

- hosts: webserver1
  vars:
    servicename: apache2

Referencing variables

In Ansible, a variable is referenced using Jinja2 syntax. Jinja2 variables use double curly braces. Like, the expression servicename is referenced as

{{ servicename }}

Consider below playbook file:

- name: usign variable in playbookhosts: webserver1vars:servicename: apache2tasks:- name: 'creating file using variable'service: name={{ servicename }} state=started

Running a playbook with variables

Before we execute the playbook, we will stop the apache2 service on webserver1 - ansible-plybook-output

If you don't have install apache2 in webserver1 then you can install and stop it using the below commands.

apt-get update
apt-get install apache2
service apache2 stop

Run the playbook variable1.yml using the below command -

$ansible-playbook variable1.yml -i final_inventory.yml

output:

ansible-plybook-output

Verifying the result of the above command, Apache2 service should be in running state on webserver1. Below is the snippets of webserver1 after executing the playbook - ansible-plybook-output

Now let's modify the "state" in the playbook to "stopped" and execute the playbook again. Here we will stop the service "vsftpd"

- name: usign variable in playbook
  hosts: webserver1
  vars:
    servicename: vsftpd
  tasks:
    - name: "creating file using variable"
      service: name={{ servicename }} state=stopped

Run command again -

$ansible-playbook variable1.yml

Verify the service state on webserver1 -

Ansible variables come very handy to manage differences between systems in large organizations and can be very useful in handling complex infrastructure.