1

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.

β.εηοιτ.βε
  • 33,893
  • 13
  • 69
  • 83
Jeetendra Pujari
  • 1,286
  • 2
  • 17
  • 31

2 Answers2

2

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:

John Rotenstein
  • 241,921
  • 22
  • 380
  • 470
  • not necessarily in sequence, i am looking for pattern matching using "contains" – Jeetendra Pujari Feb 11 '22 at 00:07
  • Added a `contains` example – John Rotenstein Feb 11 '22 at 00:23
  • _Those back-ticks always cause me problems._ The best advise, would be _"don't use them in projection or conditional"_, as `contains` already returns a boolean: [`boolean contains(array|string $subject, any $search)`](https://jmespath.org/specification.html#contains). But if you are curious, reading the _literal expressions_ and _raw string literals_ chapters of the [spec](https://jmespath.org/specification.html#literal-expressions) can come in handy. Spoiler alert: it all comes down to one being parsed as a JSON and the other being treated as a simple "raw" string. – β.εηοιτ.βε Feb 11 '22 at 00:33
2

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]"
β.εηοιτ.βε
  • 33,893
  • 13
  • 69
  • 83