0

I'm trying to combine a servers Hostname and Cluster attributes from the servers facts into a dictionary so that I get hostname:cluster When i have the hostname:cluster pairs for a number of servers, i'd like to group them by Cluster.

The fact is

"esxi_facts": {
    "ansible_facts": {
        "ansible_all_ipv4_addresses": [
            "10.10.10.21"
        ],
        "ansible_bios_version": "2.12.2",
        "ansible_distribution": "VMware ESXi",
        "ansible_host_connection_state": "connected",
        "ansible_hostname": "server1-abcdef123.acme.com",
        "ansible_in_maintenance_mode": false,
        "ansible_interfaces": [
            "vmk0"
        ],
        "ansible_memfree_mb": 1506569,
        "ansible_memtotal_mb": 1571452,
        "ansible_product_serial": "abcdef123",
        "ansible_uptime": 3005745,
        "ansible_vmk0": {
            "device": "vmk0",
            "ipv4": {
                "address": "10.10.10.21",
                "netmask": "255.255.255.128"
            },
            "mtu": 1500
        },
        "cluster": "bigcluster",
        "host_date_time": {},
    },
    "changed": false,
    "failed": false
}

I can grab the hostname and cluster name as follow

- name: create list of hostname and cluster attributes  
  set_fact:
    name_cluster: "{{ esxi_facts.ansible_facts|json_query('[ansible_hostname, cluster]') }}"

This returns

    "ansible_facts": {
        "name_cluster": [
            "server1-abcdef123.acme.com",
            "bigcluster"
        ]
    }

When i try to create a dict from name_cluster using

- name: create dictionary from the above 
  set_fact:
    name_cluster_dict: "{{ name_cluster | items2dict(key_name='ansible_hostname', value_name='cluster') }}"

I get the following

"msg": "Unexpected templating type error occurred on ({{ name_cluster | items2dict(key_name='ansible_hostname', value_name='cluster') }}): string indices must be integers

piercjs
  • 133
  • 8
  • I am pretty sure the path you are heading in is not the right one. Could you share a more extensive example having more than one hosts, spanning on multiple clusters and along with the desired output? – β.εηοιτ.βε Apr 03 '23 at 16:11
  • 1
    For the moment being the best I could advise would be to investigate the [`groupby`](https://jinja.palletsprojects.com/en/3.1.x/templates/#jinja-filters.groupby) and [`groupby_as_dict`](https://docs.ansible.com/ansible/latest/collections/community/general/docsite/filter_guide_abstract_informations_grouping.html#) filters – β.εηοιτ.βε Apr 03 '23 at 16:14

0 Answers0