0

I have the following output of aws ec2 describe-vpcs:

{
    "Vpcs": [
        {
            "VpcId": "vpc-1f0e197d",
            "InstanceTenancy": "default",
            "Tags": [
                {
                    "Value": "Product-Production",
                    "Key": "Name"
                }
            ],
            "CidrBlockAssociationSet": [
                {
                    "AssociationId": "vpc-cidr-assoc-f3c5509a",
                    "CidrBlock": "172.19.0.0/16",
                    "CidrBlockState": {
                        "State": "associated"
                    }
                }
            ],
            "State": "available",
            "DhcpOptionsId": "dopt-37fd5550",
            "CidrBlock": "172.19.0.0/16",
            "IsDefault": false
        },
        {
         another vpc...
        }
    ]
}

I'm using jq to catch the "VpcId" if

.Tags[].Value==Product-Production

but no matter what I try, I can't get the right syntax, how can it be achieved?

peak
  • 105,803
  • 17
  • 152
  • 177
Itai Ganot
  • 5,873
  • 18
  • 56
  • 99
  • This is so-close to being duplicate of [How to filter an array of objects based on values in an inner array with jq?](https://stackoverflow.com/questions/26701538/how-to-filter-an-array-of-objects-based-on-values-in-an-inner-array-with-jq), but need to modify the answer to suit your needs – Inian Aug 06 '18 at 08:47

1 Answers1

1

You are so-close but not quite the right filter. You need to use a select expression here to match the object matching your string condition and filter the value out of it.

jq '.Vpcs[] | select( .Tags[].Value| contains("Product-Production")) | .VpcId'

If you break down the filter,

  1. The part .Vpcs[] lists all the elements within the array on which we apply the condition.
  2. We filter that object whose .Value contains the string you need here. So at the end of first pipe-line output you get the actual element from the list of the elements in the array, matching the condition defined.
  3. From the object returned, you just print out the .VpcId with the last pipeline.

If you haven't used jqplay.org before, you should try it and get your filters into action and work it out online.

Inian
  • 80,270
  • 14
  • 142
  • 161