How would you go about listing instances using aws cli in certain VPC with the Tag Name, private IP address of instance and instance id

aws-cli

The closest I have get is using the following commands.

This command manage to lists all name of instances.

aws ec2 describe-instances --filters Name=vpc-id,Values=vpc-e2f17e8b --query 'Reservations[].Instances[].Tags[?Key==`Name`].Value[]'

This command manage to list all private ip address, instance id and ALL tags which I don't need. I just need the name.

aws ec2 describe-instances --filters Name=vpc-id,Values=vpc-e2f17e8b | jq '.Reservations[].Instances[] | {PrivateIpAddress, InstanceId, Tags}'

I'm not sure why I can't execute command like this way:

aws ec2 describe-instances | jq '.["Reservations"]|.[]|.Instances|.[]|.PrivateIpAddress + " " + .InstanceId + " " + .Tags[?Key==`Name`].Value[]'

This command works but its showing all the Tags Key names.

aws ec2 describe-instances | jq '.["Reservations"]|.[]|.Instances|.[]|.PrivateIpAddress + " " + .InstanceId + " " + .Tags'

Best Answer

You need to escape the backslashes in order to format the answer correctly.

aws ec2 describe-instances --query 'Reservations[].Instances[].[PrivateIpAddress,Tags[?Key==`Name`].Value[]]' --output text | sed '$!N;s/\n/ /'

So this is the actual command you want:

$ aws ec2 describe-instances --filters Name=vpc-id,Values=vpc-ac973bc9 --query 'Reservations[].Instances[].[PrivateIpAddress,InstanceId,Tags[?Key==`Name`].Value[]]' --output text | sed '$!N;s/\n/ /'
10.101.255.10   i-91efd39b Server1
10.101.255.9    i-f1e8d4fb Server2

And you don't need .Value[]. You can just use .Value, and that will give the same output.

This is awesome, btw. I will be implementing this myself!

CORRECTION: The above won't work if the value of .Value is "None". This works better:

$ aws ec2 describe-instances --filters Name=vpc-id,Values=vpc-ac973bc9 --query 'Reservations[].Instances[].[PrivateIpAddress,InstanceId,Tags[?Key==`Name`].Value[]]' --output text | sed 's/None$/None\n/' | sed '$!N;s/\n/ /'
10.101.255.10   i-91efd39b Server1
10.101.255.9    i-f1e8d4fb Server2
10.101.255.8    i-f6c2450a      None
10.101.255.7    i-34a6afce Server3
Related Topic