Search code examples
ansiblehostvars

Extract hostvar list


I'm trying to get secondary ip addresses from hosts in a group and set them to a fact.

my hostvars contain

{
  "network_interfaces": [
    {
      "private_ip_address": "10.224.1.48",
      "private_ip_addresses": [
        {
          "primary": true,
          "private_dns_name": "ip-10-224-1-48.us-east-2.compute.internal",
          "private_ip_address": "10.224.1.48"
        },
        {
          "primary": false,
          "private_dns_name": "ip-10-224-1-66.us-east-2.compute.internal",
          "private_ip_address": "10.224.1.66"
        },
        {
          "primary": false,
          "private_dns_name": "ip-10-224-1-135.us-east-2.compute.internal",
          "private_ip_address": "10.224.1.135"
        }
      ],
      "source_dest_check": true,
      "status": "in-use",
      "subnet_id": "subnet-0cfc6e2da31b9cf50",
      "vpc_id": "vpc-123456"
    }
  ],
}

Something like

set_fact:
  private_ips: "{{ groups['database'] | map('extract', hostvars, ['network_interfaces[0]','private_ip_addresses[1]','private_ip_address']) | join(',')  }}"

which doesn't work.

set_fact: 
  private_ips: "{{ groups['database'] | map('extract', hostvars, ['network_interfaces']) | map(attribute='private_ip_addresses') }}"  

ends up with "private_ips": "[AnsibleUndefined, AnsibleUndefined]"

I'm looking for the result to be just a single IP out of private_ip_addresses from each host in the group


Solution

  • Create the list of IPs at each host

        - set_fact:
            my_ip: "{{ network_interfaces|json_query(_query) }}"
          vars:
            _query: '[].private_ip_addresses[].private_ip_address'
    

    gives for the data from the example

      my_ip:
      - 10.224.1.48
      - 10.224.1.66
      - 10.224.1.135
    

    Then, select the second item from the lists of all hosts in the group database

        - set_fact:
            private_ips: "{{ groups.database|
                             map('extract', hostvars, 'my_ip')|
                             map(attribute=1)|list }}"
          run_once: true