Tony Stark
Tony Stark

Reputation: 2468

How do I filter elements from a list correctly with JMESPath and Ansible?

I have the following structure.

[
            {
                "ami_launch_index": 0, 
                "architecture": "x86_64",                     
                "instance_type": "t2.micro", 
                "monitoring": {
                    "state": "disabled"
                } ,
                "placement": {
                    "availability_zone": "eu-central-1a", 
                    "group_name": "", 
                    "tenancy": "default"
                },                 
                "tags": {
                    "Name": "MYNAME 1", 
                    "Project": "MY PROJECT", 
                    "Purpose": "MYTEST"
                }, 
                "virtualization_type": "hvm"
            }, 
            {
                "ami_launch_index": 2, 
                "architecture": "x86_64",              
                "instance_type": "t2.micro", 
                "monitoring": {
                    "state": "disabled"
                }, 
                "placement": {
                    "availability_zone": "eu-central-1a", 
                    "group_name": "", 
                    "tenancy": "default"
                },
                "tags": {
                    "Name": "MYNAME 2", 
                    "Project": "MY SECOND PROJECT", 
                    "Purpose": "WHY THE HECK NOT"
                }, 
                "virtualization_type": "hvm"
            }
        ]

I want to print all elements where [].tags.Name contains the string "SECOND" (so just the second element. How do I achieve this?

This is what I've tried, but it's not working.

- debug:
        msg: "{{ instances.stdout | from_json | json_query(\"[][?contains(tags.Name, 'SECOND')]\") }}"

I tried using http://jmespath.org but can't extract the data the way I want either.

Upvotes: 1

Views: 1502

Answers (1)

Konstantin Suvorov
Konstantin Suvorov

Reputation: 68229

To fetch items that has SECOND in tags.Name you can use this query:

[?contains(tags.Name,'SECOND')]

But it seems that your sample data will not match anything, as SECOND is only in Project property and not Name.

Upvotes: 2

Related Questions