AWS CLI parse error when listing more than two tags

96 Views Asked by At

Why does this command work?:

aws ec2 describe-instances \
    --profile ike \
    --query 'Reservations[].Instances[].[InstanceId,State.Name,InstanceType,PublicIpAddress, Tags[?Key==`Name`]|[0].Value, Tags[?Key==`Owner`]|[0].Value]' \
    --filter 'Name=instance-state-name,Values=running' \
    --output table

But not this command when I add a third tag?:

aws ec2 describe-instances \
    --profile ike \
    --query 'Reservations[].Instances[].[InstanceId,State.Name,InstanceType,PublicIpAddress, Tags[?Key==`Name`]|[0].Value, Tags[?Key==`Owner`]|[0].Value], Tags[?Key==`Schedule`]|[0].Value]' \
    --filter 'Name=instance-state-name,Values=running' \
    --output table

Error output:

Bad value for --query Reservations[].Instances[].[InstanceId,State.Name,InstanceType,PublicIpAddress, Tags[?Key==Name]|[0].Value, Tags[?Key==Owner]|[0].Value], Tags[?Key==Schedule]|[0].Value]: Unexpected token: ,: Parse error at column 140, token "," (COMMA), for expression: "Reservations[].Instances[].[InstanceId,State.Name,InstanceType,PublicIpAddress, Tags[?Key==Name]|[0].Value, Tags[?Key==Owner]|[0].Value], Tags[?Key==Schedule]|[0].Value]"

Ii only works if I remove one of the tags.

I can change one of the TWO tags, and it works, but not with all three tags.

I'm still learning, obviously.

1

There are 1 best solutions below

1
On

describe-instances accepts a valid JMESPath expression as a value for the parameter --query.

Your first expression is a valid JMESPath which I will paste here with indentations to make it more legible:

Reservations[].Instances[].[
   InstanceId,
   State.Name,
   InstanceType,
   PublicIpAddress,
   Tags[?Key==`Name`] | [0].Value,
   Tags[?Key==`Owner`] | [0].Value
]

It means:

  1. Flatten all Instances (take every instance from every reservation and put them into a flat array).

  2. Project each Instance to an array with the following members:

    1. .InstanceId
    2. .State.Name
    3. .InstanceType
    4. .PublicIpAddress
    5. Take the first object within the .Tags array which has a {"key": "Name"} element, and project its .Value
    6. Take the first object within the .Tags array which has a {"key": "Owner"} element, and project its .Value

Your second expression has an unbalanced bracket which you will easily find if you indent it properly.