You can overcome this by using external input to an Ansible playbook using extra variables.
This article will learn how to use Ansible Extra variables to provide custom or dynamic values without editing the playbooks.
What is Ansible Extra Vars?
Ansible extra vars is a feature that allows you to include more flexibility in your Ansible playbooks by providing you with the ability to specify dynamic values when executing the playbook.
Ansible extra vars are helpful when:
- You have a variable whose value may change more than once when running the playbook.
- You do not need to edit the playbook to change the variable’s value in the playbook.
How to use Ansible Extra Vars
Ansible extra vars will overwrite the value stored in a playbook or a variable file. They are also called command-line variables.
Let us now look at an example of how to use extra vars.
A typical example of the extra vars in Ansible is when you hard-code the hosts’ value. Assume you have a playbook that runs on hosts with the group “development” when you need to run the playbook on “production” hosts, you will be forced to edit the playbook.
This can be tiresome and prone to errors, especially on an extensive collection of host groups.
To solve this issue, we can use the Ansible extra vars feature. We can define a variable representing the hosts’ group and specify its value when running the playbook.
Consider the example playbook below:
- hosts: "{{group}}"
become:yes
gather_facts: no
tasks:
- name: InstallApache
apt:
name: httpd
state: present
update_cache: yes
Now that we have an example playbook as above, we can pass the value to the “group” variable using the –extra-vars option while running the playbook.
An example command is as shown:
To change the group to “development,” you do not need to edit the playbook; pass the variable as shown:
The example below uses extra vars to specify the service to start based on the target distribution.
- hosts: "{{group}}"
become:yes
gather_facts: no
tasks:
- name: InstallApache
service:
name: "{{pkg_name}}"
state: started
Using the playbook above, we can specify the extra variables as:
If you want to pass variables with spaces, you use single quotation marks as shown in the example below:
Conclusion
This tutorial illustrates how to implement and use Ansible extra variables to add flexibility to playbooks. Check the documentation to learn more.