return text list of values one line per instance-id with awscli --query

8.9k views Asked by At

I have instances in AWS that have the same ReservationId (they were launched at the same time and they have AmiLaunchIndex of 0 thru x ). My goal is to produce text output with one line per instance, such as this. I added column headers for clarity.

OwnerId      ReservationId InstanceId  PrivateIpAddress AmiLaunchIndex
12345678910  r-poiu4567    i-asdf1234  10.0.0.1         0
12345678910  r-poiu4567    i-qwer4312  10.0.1.1         1
... etc ...

In the jmespath gitter channel, the map function was suggested as a way to accomplish this, but I can't figure out how to use the function. Any suggestions?

5

There are 5 answers

0
james.haggerty On BEST ANSWER

Unfortunately, to do this right I think we'd need https://github.com/jmespath/jmespath.site/pull/6

In this particular case you can hack this result by using the owner in Network Interfaces, which is almost certain to be the same in practice:

Reservations[].Instances[].[NetworkInterfaces[0].OwnerId, InstanceId, KeyName]

(use an object instead of an array if you want the column headings)

8
Frederic Henri On

you would need to run the following command

aws ec2 describe-instances \
    --filters "Name=reservation-id,Values=r-poiu4567" 
    --query 'Reservations[*].{owner:OwnerId,ReservationId:ReservationId,instance:Instances[].InstanceId | [0]}' \ 
    --output text

You can add the other parameters you want

This will provide the desired output (all elements in one line) without the header as something like

i-08eec92943c9cc576 325979260958    r-0b13a131efa6b3af8
i-07a25c4ae7e6abecb 325979260958    r-05a51aefe5b72358d
....
0
vr00n On
ec2 describe-instances --query 
'Reservations[*].
{
   id:ReservationId,
   requester:RequesterId,
   instance:Instances[].InstanceId |[0],
   lifecycle:Instances[].InstanceLifecycle | [0]
}
'
--output text

....worked for me.

0
LHWizard On

Finally, I was able to get my desired result by using the map function of jmespath as follows. Kudos to folks in the jmespath/chat channel on gitter.

aws ec2 describe-instances --query "map(&[], Reservations[].[OwnerId,ReservationId,Instances[].InstanceId | []])" --output text

An equivalent alternative expression is:

aws ec2 describe-instances --query "Reservations[].[OwnerId,ReservationId,Instances[].InstanceId | []] | map(&[], @)" --output text

see this jmespath issue and this one where this is discussed.

4
martin On
--query Reservations[*].Instances[*].[InstanceId] --output text

Just add the brakets