Variable name includes a variable

37 views
Skip to first unread message

mto...@go2uti.com

unread,
Nov 12, 2015, 6:39:38 PM11/12/15
to Ansible Project

 This is something I have been struggling with for a while: a variable whose name includes a variable.  For instance, Ansible facts for a server includes the following information on the network interfaces:

            "ansible_eth0": {
                "active": true,
                "device": "eth0",
                "ipv4": {
                    "address": "10.105.12.24",
                    "netmask": "255.255.252.0",
                    "network": "10.105.12.0"
                },
                "macaddress": "00:50:56:92:3c:b2",
                "module": "vmxnet3",
                "mtu": 1500,
                "promisc": false,
                "type": "ether"
            },
            "ansible_eth1": {
                "active": true,
                "device": "eth1",
                "ipv4": {
                    "address": "10.104.24.25",
                    "netmask": "255.255.255.248",
                    "network": "10.104.24.24"
                },
                "macaddress": "00:50:56:92:6a:40",
                "module": "vmxnet3",
                "mtu": 1500,
                "promisc": false,
                "type": "ether"
            },
            "ansible_interfaces": [
                "lo",
                "eth1",
                "eth0"
            ],


In a playbook, I want to walk through the list of interfaces and extract information about each one:

      - debug: msg="interface = {{item}}, address = {{ansible_{{item}}.ipv4.address}}
      with_items: ansible_interfaces
      when: 'item != "lo"'

This, of course, does not work because of the nested delimiters.  So how do I call out something like this?
-Mark

Brian Coca

unread,
Nov 13, 2015, 1:37:08 AM11/13/15
to Ansible Project
mustaches don't stack, to do dynamic vars you need to use hostvars:

- debug: msg="interface = {{item}}, address = {{
hostvars[inventory_hostname]['ansible_' + item].ipv4.address }}
with_items: ansible_interfaces
when: 'item != "lo"'

--
Brian Coca

mto...@go2uti.com

unread,
Nov 13, 2015, 10:52:37 AM11/13/15
to Ansible Project

    I knew it would be simple if I just asked!  That worked perfectly!
    Thanks!
    -Mark
Reply all
Reply to author
Forward
0 new messages