Bootstrap FreeKB - Ansible - Create variables on the command line using the -e or --extra-vars option
Ansible - Create variables on the command line using the -e or --extra-vars option

Updated:   |  Ansible articles

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.

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:
  - debug:
      var: foo

  - 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:
    - 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 Buy Me A Coffee



Comments


Add a Comment


Please enter adfb81 in the box below so that we can be sure you are a human.