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-variable


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-variable



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 -