Skip to content

Instantly share code, notes, and snippets.

@joelwking
Last active May 8, 2019 12:46
Show Gist options
  • Save joelwking/d52b6dd081cf038e4841e542c13cb2a9 to your computer and use it in GitHub Desktop.
Save joelwking/d52b6dd081cf038e4841e542c13cb2a9 to your computer and use it in GitHub Desktop.
Example of dynamically creating scalar variables using the Ansible set_fact module.

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


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment