Search code examples
jsonansiblejinja2json-query

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.


Solution

  • 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