AWS CLI - aws ec2 describe-instances to retrieve keypair mame for each EC2 instance

感情迁移 提交于 2021-01-29 05:51:42

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!