How to extract one attribute from a list of dictionaries

Let’s suppose the following list of dictionaries:

`

  • domain_definition:
  • name: server11
    cluster: cluster1
    port: ‘8080’
  • name: server12
    cluster: cluster2
    port: ‘8090’
  • name: server21
    cluster: cluster3
    port: ‘9080’
  • name: server22
    cluster: cluster4
    port: ‘9090’

`

The aim is to extract all name: 'value' from domain_definition into a list:

`

  • name: server11
  • name: server12
  • name: server21
  • name: server22

`

I tried for instance the following:

`

  • set_fact:
    domain_definition_names_list: “{{ [‘name’] |
    intersect(domain_definition.keys()|list) }}”

`
but it fails:

`

fatal: [localhost]: FAILED! => {
“msg”: "The task includes an option with an undefined variable. The error was: ‘list object’ has no attribute ‘keys’…}

`

Any suggestion?

I’m using:

  • ansible 2.9.7
  • python 3.8.2

just to make sure - this is a list of list of dictionaries.
If this is your source of truth, and you intend to have a list of dicts, then it could look like this:

domain_definition:

  • name: server11
    cluster: cluster1
    port: ‘8080’
  • name: server12
    cluster: cluster2
    port: ‘8090’
  • name: server21
    cluster: cluster3
    port: ‘9080’
  • name: server22
    cluster: cluster4
    port: ‘9090’

This will make a difference when manipulating the data.

More accurately, the data structure you posted isn’t a variable, it’s an item from a “upper” list variable - which we don’t know the name of.

An example:

That’s what I meant (just a typo in the structure).

Thanks. :slight_smile:

Can we give the same information in hosts file and still work?

what do you mean. Examples with code?

Yes, of course: you can define the variable anywhere, including in the hosts file.
There are 2 differences though:

  • the precedence.
  • the way the variables are defined: the inventory file is not a yaml file (ini format). Refer to this post for how to define your dictionary(ies) in the hosts file.

Yes, of course: you can define the variable anywhere, including in the hosts file.
There are 2 differences though:

  * the precedence
    <https://docs.ansible.com/ansible/latest/user_guide/playbooks_variables.html#variable-precedence-where-should-i-put-a-variable&gt;\.
  * the way the variables are defined: the inventory file is not a yaml file (ini format). Refer to this post
    <https://stackoverflow.com/questions/29856738/how-to-define-hash-dict-in-ansible-inventory-file&gt; for how to define
    your dictionary(ies) in the hosts file.

The second statement is correct only if you refer to the host file (defaults to /etc/ansible/host). The inventory for
your playbook can be written completely in YAML.

Regards
        Racke

Thank you guys that helps!