Home > Back-end >  AWS CLI JMESPath Query help using query option in cli
AWS CLI JMESPath Query help using query option in cli

Time:02-11

I have the following cli command

aws ecs list-services --cluster ecs-cluster-1

Giving this JSON

{
    "serviceArns": [
        "arn:aws:ecs:us-east-1:XXXXXXXXXXXXX:service/ecs-cluster-1/app4",
        "arn:aws:ecs:us-east-1:XXXXXXXXXXXXX:service/ecs-cluster-1/app3",
        "arn:aws:ecs:us-east-1:XXXXXXXXXXXXX:service/ecs-cluster-1/app1",
        "arn:aws:ecs:us-east-1:XXXXXXXXXXXXX:service/ecs-cluster-1/app4"
    ]
}

How do I get app1 ARN back by matching name of the app (app1) using --query option?

Expected Output

arn:aws:ecs:us-east-1:XXXXXXXXXXXXX:service/ecs-cluster-1/app1

Please note that this JSON array is not ordered.

CodePudding user response:

Assuming it is the first entry in the list, you can use:

--query servicesArns[0]

Depending on your operating system, you might need to quote it:

--query 'servicesArns[0]'

If you are looking for the entry that 'contains' app1, use:

--query serviceArns[?contains(@, 'app1') == `true`]|[0]

Those back-ticks always cause me problems. You can play around and potentially use other tick-marks.

Good references for JMESPath:

CodePudding user response:

You can either use contains or ends_with for the filtering part.

Then you want to stop the project and get the first item of the array in order to have only the application ARN you are interested in.
Stopping a projection is covered in the pipe expression tutorial of the documentation.

So, given the expression

serviceArns[?ends_with(@,'app1')]|[0]

You end up with the expected

"arn:aws:ecs:us-east-1:XXXXXXXXXXXXX:service/ecs-cluster-1/app1"

In the AWS command line interface, this will then be:

aws ecs list-service \
  --cluster ecs-cluster-1 \
  --query "serviceArns[?ends_with(@,'app1')]|[0]"
  • Related