Search code examples
ansiblejinja2

Ansible Jinja2: How to get nth value of nested dict?


My Playbook looks like this

- set_fact:
    vcenter_cluster: "{{ cluster_info.clusters.values[cluster_input.user_input] }}"   

- debug:
    var:  vcenter_cluster

The data in cluster_info.clusters looks like this

ok: [localhost] => {
    "cluster_info.clusters": {

        "DMZ": {
            "datacenter": "dc",

        },
        "K8S": {
            "datacenter": "dc",

        },
        "Win": {
            "datacenter": "dc",
        }
    }
}

My goal is to set vcenter_cluster to K8S when cluster_input.user_input is 1.


Solution

  • A minimal example playbook

    ---
    - hosts: localhost
      become: false
      gather_facts: false
    
      vars:
    
        cluster_info:
          clusters:
            DMZ:
              datacenter: dc
            K8S:
              datacenter: dc
            WIN:
              datacenter: dc
    
        user_input: 1
    
      tasks:
    
      - name: Show
        debug:
          msg: "{{ (cluster_info.clusters | list)[user_input] }}"
    

    will result in the requested output of

    TASK [Show] ******
    ok: [localhost] =>
      msg: K8S
    

    Please notice that under certain circumstances there might be a difference in where a list index can start counting with, 0 versus 1. As well that Ansible / Python probably will not maintain the order of the dictionary keys.

    Thanks To

    Further Reading

    regarding the order of dictionary keys