问题
I am trying to query keypair names that are attached to each EC2 instance, the ec2 describe-instances below works fine, it does exactly what I need, but the column under the {keypair.Name} displays [NONE] I am not sure if I am using the proper parameter name - I know there are few keypairNames.epm attached on my EC2 instances when I login to the console, but I am not seeing that on my report that I run by the command below. Any input is much appreciated.. Thx !
aws ec2 describe-instances --filters Name=instance-state-name,Values=running --query 'Reservations[].Instances[].[Tags[?Key==`Name`].Value | [0],InstanceId,Platform,State.Name,PrivateIpAddress,PublicIpAddress,InstanceType,PublicDnsName,keypair.Name]' --output table --region us-west-2
回答1:
There is no field called keypair
in the Instances
dictionary.
The closest is KeyName
:
{
"Reservations": [
{
"Instances": [
{
"InstanceId": "i-xxx",
"KeyName": "foo",
...
Therefore, you would use:
aws ec2 describe-instances --filters Name=instance-state-name,Values=running --query 'Reservations[].Instances[].[Tags[?Key==`Name`].Value | [0],InstanceId,Platform,State.Name,PrivateIpAddress,PublicIpAddress,InstanceType,PublicDnsName,KeyName]'
See: describe-instances — AWS CLI Command Reference
回答2:
I did find a way to sort this out by using pipe. exp: | sort -k5
Please note, before I used {sort}, the report had {windows} and {None} allover the place under column PLATFORM. Please see attached, I uploaded a sample result of my report..
The new statement looks like this:
aws ec2 describe-instances --filters Name=instance-state-name,Values=running --query 'Reservations[].Instances[].[Tags[?Key==`Name`].Value | [0],InstanceId,Platform,State.Name,PrivateIpAddress,PublicIpAddress,InstanceType,KeyName]' --output table | sort -k5
Report shows that is sorted by PLATFORM IN Asc order
回答3:
I do the following for a few reasons
- it can be easily piped to grep
- you don't need to query aws api's repeatedly if you want to improve your data
- I have multiple regions that I'm usually iterating through, so this makes it easy to scan through all regions (and accounts)
instances=`aws ec2 describe-instances `
echo $instances | jq '.Reservations[].Instances[] | "[\(.InstanceId) \(.Platform) \(.State.Name) \(.PrivateIpAddress) \(.PublicIpAddress) \(.InstanceType) \(.PublicDnsName) \(.KeyName)]"'
来源:https://stackoverflow.com/questions/54299615/aws-cli-aws-ec2-describe-instances-to-retrieve-keypair-mame-for-each-ec2-insta