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

 

If the variable contains whitespace you'll want to wrap quotes around the value.

ansible-playbook playbook.yml --extra-vars foo="Hello World"

 

Or you may need to wrap double quotes around the key and value and single quotes around the value.

ansible-playbook playbook.yml --extra-vars "foo='Hello 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 Buy Me A Coffee



Comments


Add a Comment


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