sherri
sherri

Reputation: 461

How to do Json query in ansible with matched value

Can someone tell me if it is possible to do? I have the following list

list:
  - dev
  - uat

I want to iterate through the above list and grab the value of respective IpAddress from the below output.

{
    "Tags": [
        {
            "ResourceType": "instance", 
            "ResourceId": "i-8dh7435490fjksfd", 
            "Environment": "production", 
            "IpAddress": "10.0.0.8"
        }, 
        {
            "ResourceType": "instance", 
            "ResourceId": "i-8dh7435dsj89jfe", 
            "Environment": "dev", 
            "IpAddress": "10.0.0.3"
        },
        {
            "ResourceType": "instance", 
            "ResourceId": "i-8dsdj456ovfvfd", 
            "Environment": "uat", 
            "IpAddress": "10.0.0.7"
        }
    ]
}

This is the output I am looking for

[
 "10.0.0.3",
 "10.0.0.7"
]

I am trying with this filter Tags| json_query('[*].IpAddress'). But it gives me all IpAddress from the list.

Upvotes: 2

Views: 502

Answers (1)

Vladimir Botka
Vladimir Botka

Reputation: 67959

For example

- hosts: localhost
  vars:
    my_list: [dev, uat]
    my_Tags: [
        {
            "ResourceType": "instance", 
            "ResourceId": "i-8dh7435490fjksfd", 
            "Environment": "production", 
            "IpAddress": "10.0.0.8"
        }, 
        {
            "ResourceType": "instance", 
            "ResourceId": "i-8dh7435dsj89jfe", 
            "Environment": "dev", 
            "IpAddress": "10.0.0.3"
        },
        {
            "ResourceType": "instance", 
            "ResourceId": "i-8dsdj456ovfvfd", 
            "Environment": "uat", 
            "IpAddress": "10.0.0.7"
        }
    ]
  tasks:
    - debug:
        msg: "{{ my_Tags|selectattr('Environment', 'in', my_list)|
                 map(attribute='IpAddress')|list }}"

gives

  msg:
  - 10.0.0.3
  - 10.0.0.7

Upvotes: 2

Related Questions