There are 20+ ways to create variables in Ansible, such as on the command line, in a playbook, or from a file, just to name a few. Refer to Ansible - Getting Started with Variables.
Here is how you would create an hash of food using the vars plugin.
vars:
food:
- { key: 'fruit', value: 'banana' }
- { key: 'fruit', value: 'orange' }
- { key: 'veggy', value: 'onion' }
- { key: 'veggy', value: 'pepper' }
Or like this.
vars:
food:
- key: fruit
value: banana
- key: fruit
value: orange
- key: veggy
value: onion
- key: veggy
value: pepper
The debug module can be used to output the hash, like this.
- name: output the contents of the 'food' hash
debug:
var: food
Which should return the following.
TASK [output the contents of the 'food' hash]
ok: [server1.example.com] => {
"food": [
{
"key": "fruit",
"value": "apple"
},
{
"key": "fruit",
"value": "banana"
},
{
"key": "veggy",
"value": "onion"
},
{
"key": "veggy",
"value": "pepper"
}
]
}
Looping through a hash
The following parameters can be used to loop through each item in a hash.
In this example, the loop parameter is used to loop over the food hash.
- name: "loop through the 'food' hash"
debug:
msg: "{{ item }}"
loop:
- { key: 'fruit', value: 'banana' }
- { key: 'fruit', value: 'orange' }
- { key: 'veggy', value: 'onion' }
- { key: 'veggy', value: 'pepper' }
Which should return the following. Note that some or all of the output can be suppressed or limited using the no_log or loop_control parameters.
TASK [loop through the 'food' hash]
ok: [server1.example.com] => (item=apple) => {
"msg": {
"key": "fruit",
"value": "apple"
}
}
ok: [openshift1.software.eng.us] => (item={'key': 'fruit', 'value': 'banana'}) => {
"msg": {
"key": "fruit",
"value": "banana"
}
}
ok: [openshift1.software.eng.us] => (item={'key': 'veggy', 'value': 'onion'}) => {
"msg": {
"key": "veggy",
"value": "onion"
}
}
ok: [openshift1.software.eng.us] => (item={'key': 'veggy', 'value': 'pepper'}) => {
"msg": {
"key": "veggy",
"value": "pepper"
}
}