Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

aws cli ec2 describe-instances table output

I want to run an ec2 describe-instances command and get output in a table format as follows (where name is the Value of the Tag with Key 'Name'):

----------------------------------------------------------
|                    DescribeInstances                   |
+-------------+----------------+--------------+----------+
| instance_id |  ip_address    |    name      |  state   |
+-------------+----------------+--------------+----------+
|  i-g93g494d |  99.99.99.01   |  name1       |  running |
|  i-a93f754c |  99.99.99.02   |  name2       |  running |
+-------------+----------------+--------------+----------+

I can run the following command:

aws ec2 describe-instances --instance-ids i-g93g494d i-a93f754c --query "Reservations[*].Instances[*].{name: Tags[?Key=='Name'].Value, instance_id: InstanceId, ip_address: PrivateIpAddress, state: State.Name}" --output json

and obtain output:

[
    [
        {
            "instance_id": "i-g93g494d",
            "state": "running",
            "ip_address": "99.99.99.01",
            "name": [
                "name1"
            ]
        }
    ],
    [
        {
            "instance_id": "i-a93f754c",
            "state": "running",
            "ip_address": "99.99.99.02",
            "name": [
                "name2"
            ]
        }
    ]
]

However, when I run the same command with --output table rather than --output json I get an error.

command:

aws ec2 describe-instances --instance-ids i-g93g494d i-a93f754c --query "Reservations[*].Instances[*].{name: Tags[?Key=='Name'].Value, instance_id: InstanceId, ip_address: PrivateIpAddress, state: State.Name}" --output json

output:

list index out of range

I would like the table output to look like the above example but I'm having difficulty solving this. I'd very much appreciate any help anyone can offer on this.

like image 390
Stuart Avatar asked Oct 29 '15 11:10

Stuart


1 Answers

You need to use pipe expression to filter the Tag results and get the first value such as:

aws ec2 describe-instances --instance-ids i-g93g494d i-a93f754c --query "Reservations[*].Instances[*].{name: Tags[?Key=='Name'] | [0].Value, instance_id: InstanceId, ip_address: PrivateIpAddress, state: State.Name}" --output table

There is a nice related blog post here: Get a list of instance with id, name and type

like image 91
Volkan Paksoy Avatar answered Oct 08 '22 00:10

Volkan Paksoy