How To Use Variables in Ansible Playbooks

Ansible supports the use of variables to better customize the execution of tasks and playbooks. This way, it’s possible to use the same playbook with different targets and environments.

Variables can come from different sources, such as the playbook file itself or external variable files that are imported in the playbook. Special precedence rules will apply when working with multiple variable sources that define a variable with the same name.

To see how variables work in practice, we’ll create a new test playbook that will print the value of two variables, username and home_dir. Create a new file called playbook-02.yml in your ansible-practice directory:

  • nano ~/ansible-practice/playbook-02.yml

Then add the following lines to the new playbook file:


--- - hosts: all   vars:     - username: sammy     - home: /home/sammy      tasks:     - name: print variables       debug:         msg: "Username: {{ username }}, Home dir: {{ home }}" 

Save and close the file when you’re done editing.

The vars section of the playbook defines a list of variables that will be injected in the scope of that play. All tasks, as well as any file or template that might be included in the playbook, will have access to these variables.

To try this playbook on servers from your inventory file, run ansible-playbook with the same connection arguments you’ve used before when running our first example. Again, we’ll be using an inventory file named inventory and the sammy user to connect to the remote servers:

  • ansible-playbook -i inventory playbook-02.yml -u sammy

You’ll see output like this:

Output PLAY [all] ***********************************************************************************************************************************************************************************  TASK [Gathering Facts] *********************************************************************************************************************************************************************** ok: []  TASK [print variables] *********************************************************************************************************************************************************************** ok: [] => {     "msg": "Username: sammy, Home dir: /home/sammy" }  PLAY RECAP ***********************************************************************************************************************************************************************************              : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0     

The print variables task will use the debug module to print the values of the two variables we defined in the vars section of the playbook.