Following are the differet ways that variables can be set in Ansible. This list is in the order of precedence, where the option higher in the list takes precedence over options lower in the list.
- --extra-vars command line option or Extra Variables in Tower
- set_fact module
- include_vars module
- vars_prompt
- vars_files plugin
- vars plugin
- roles vars
- group_vars
- /etc/ansible/hosts or your own inventory file
- lookup vars plugin
- register parameter and debug module
The -e or --extra-vars command line option can be used to create variables on the command line, like this.
ansible-playbook playbook.yml --extra-vars foo=Hello --extra-vars bar=World
Or like this, with a single -e or --extra-vars option with the key value pairs wrapped in quotes.
ansible-playbook playbook.yml --extra-vars "foo=Hello bar=World"
Or like using, using the JSON format.
ansible-playbook playbook.yml --extra-vars '{"foo": "Hello", "bar": "World"}'
In a playbook, the debug module can be used to print each variable.
---
- hosts: localhost
tasks:
- ansible.builtin.debug:
var: foo
- ansible.builtin.debug:
var: bar
...
Something like this should be returned.
TASK [debug]
ok: [localhost] => {
"msg": "Hello"
}
TASK [debug]
ok: [localhost] => {
"msg": "World"
}
Here is how you would pass in a list.
ansible-playbook playbook.yml --extra-vars '{"greeting": ["Hello", "World"] }'
Or like this, with quotes and double quotes reversed.
ansible-playbook playbook.yml --extra-vars "{'greeting': ['Hello', 'World'] }"
with_items can be used to loop over the list.
---
- hosts: localhost
tasks:
- debug:
msg: "{{ item }}"
with_items: "{{ greeting }}"
...
Booleans
Here is how you would create boolean variables.
ansible-playbook playbook.yml --extra-vars "{foo: true, bar: false}"
Precedence
The -e or --extra-vars command line option will take precedence over every other way that a variable can be set. For example, let's say you attempt to update the foo variable to contain a value of "Goodbye" using the vars plugin.
---
- hosts: all
vars:
foo: Goodbye
tasks:
- ansible.builtin.debug:
msg: "{{ foo }}"
...
The foo variable will retain it's value of "Hello" because the -e or --extra-vars command line options take precedence.
TASK [debug]
ok: [server1.example.com] => {
"msg": "Hello"
}
Did you find this article helpful?
If so, consider buying me a coffee over at