vars is used to create variables and arrays (aka lists).
In this example, var1 contains a string (AnsibleUnicode), var2 contains a boolean, and var3 contains an integer. It is important that var2 (boolean) and var3 (integer) are not wrapped in quotes. If these were to be wrapped in quotes, they would be interpreted as a string (AnsibleUnicode). The debug module can be used to print the value of each variable.
AVOID TROUBLE
The -e or --extra-vars command line option, Extra Variables in Tower and set_fact module will take precedence over the vars plugin.
---
- hosts: localhost
vars:
var1: "Hello World"
var2: true
var3: 123
tasks:
- debug:
var: var1
- debug:
var: var2
- debug:
var: var3
...
Something like this should be returned.
TASK [debug]
ok: [localhost] => {
"var1": "Hello World"
}
TASK [debug]
ok: [localhost] => {
"var2": true
}
TASK [debug]
ok: [localhost] => {
"var3": 123
}
Variable with multiple values (array / list)
In this example, the "foo" variable has two values, "Hello" and "World". When there are two or more items, this is now an array (aka list).
vars:
foo:
- Hello
- World
Or like this.
vars:
foo: ['Hello', 'World']
The debug module can be used to output the array, like this.
- name: "output the contents of the 'foo' array"
debug:
msg: "{{ foo }}"
Which should return the following. Notice the bracket characters [ ], which means this is indeed an array.
TASK [output the contents of the 'foo' array]
ok: [server1.example.com] => {
"msg": [
"Hello"
"World",
]
}
Additionally, the loop or with_items parameters can be used to loop through each item in the array, like this.
- name: "loop through the 'foo' array"
debug:
msg: "{{ item }}"
loop: "{{ foo }}"
Which should return the following.
TASK [loop through the 'foo' array]
ok: [server1.example.com] => (item=Hello) => {
"msg": "Hello"
}
ok: [server1.example.com] => (item=World) => {
"msg": "World"
}
key value pairs
Or, key value pair can be created like this.
vars:
variables:
- key: foo
value: Hello
- key: bar
value: World
The debug and loop modules can be used to print the key value pairs.
- debug:
msg: "{{ item }}"
loop: "{{ variables }}"
Which should return the following.
TASK [debug]
ok: [server1.example.com] => (item={u'value': u'Hello', u'key': u'foo'}) => {
"msg": {
"key": "foo",
"value": "Hello"
}
}
ok: [server1.example.com] => (item={u'value': u'World', u'key': u'bar'}) => {
"msg": {
"key": "bar",
"value": "World"
}
}