This example illustrates that variables names can be created dynamically in an Ansible playbook.
Given we have a list of dictionaries representing DHCP Servers in our playbook. In this case, the list of DHCP servers was read from a spreadsheet and exposed as variables to the playbook.
ok: [localhost] => (item=dhcp_servers) => {
"ansible_facts": {
"dhcp_servers": [
{
"addr": "203.0.113.17",
"label": "DHCP_DC1_PRD"
},
{
"addr": "198.51.100.17",
"label": "DHCP_DC2_PRD"
}
]
},
"changed": false,
"item": "dhcp_servers"
}
Then we can dynamically create scalar variables using the set_fact
module.
- set_fact:
'{{ item.label }}': '{{ item.addr }}'
loop: '{{ dhcp_servers }}'
- debug:
msg: '{{ DHCP_DC1_PRD }}'
The output of the sample playbook is as follows:
TASK [set_fact] ***************************************************************************************************************
ok: [localhost] => (item={u'addr': u'203.0.113.17', u'label': u'DHCP_DC1_PRD'}) => {
"ansible_facts": {
"DHCP_DC1_PRD": "203.0.113.17"
},
"changed": false,
"item": {
"addr": "203.0.113.17",
"label": "DHCP_DC1_PRD"
}
}
ok: [localhost] => (item={u'addr': u'198.51.100.17', u'label': u'DHCP_DC2_PRD'}) => {
"ansible_facts": {
"DHCP_DC2_PRD": "198.51.100.17"
},
"changed": false,
"item": {
"addr": "198.51.100.17",
"label": "DHCP_DC2_PRD"
}
}
TASK [debug] ******************************************************************************************************************
ok: [localhost] => {}
MSG:
203.0.113.17