Search code examples
jsonamazon-web-servicesjqjson-query

Trying to extract values from aws-cli response using jq but failing, what am I doing wrong?


I have the following json structure:

[
  {
    "IsDefault": false,
    "CidrBlock": "172.19.0.0/16",
    "DhcpOptionsId": "dopt-37fd70550",
    "State": "available",
    "CidrBlockAssociationSet": [
      {
        "CidrBlockState": {
          "State": "associated"
        },
        "CidrBlock": "172.19.0.0/16",
        "AssociationId": "vpc-cidr-assoc-f3c1559a"
      }
    ],
    "Tags": [
      {
        "Key": "Name",
        "Value": "product-Production"
      }
    ],
    "InstanceTenancy": "default",
    "VpcId": "vpc-1f0e197d"
  },
  {
    "IsDefault": false,
    "CidrBlock": "10.0.0.0/16",
    "DhcpOptionsId": "dopt-0a550861",
    "State": "available",
    "CidrBlockAssociationSet": [
      {
        "CidrBlockState": {
          "State": "associated"
        },
        "CidrBlock": "10.0.0.0/16",
        "AssociationId": "vpc-cidr-assoc-8955dae0"
      }
    ],
    "Tags": [
      {
        "Key": "Name",
        "Value": "Marketing VPC"
      }
    ],
    "InstanceTenancy": "default",
    "VpcId": "vpc-36b5585d"
  },
  .
  .
  .
]

I'm trying to print all VpcId's using jq but I can't find the right way to do it.

Here's what I've tried:

command | jq -r '.VpcId[]'
command | jq -r '.VpcId'
command | jq -r '.[] | .VpcId'

What am I doing wrong?


Solution

  • It looks like the command you are using is aws ec2 describe-vpcs.

    This command actually returns the following structure:

    {
        "Vpcs": [
            {
                "VpcId": "vpc-xxxxxxxx", 
            }
        ]
    }
    

    So you want to reach into the Vpcs key before you iterate over the array, Like this:

    aws ec2 describe-vpcs | jq -r '.Vpcs | .[] | .VpcId'