Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a list of names and ARNs of instances using AWS CLI

I'd like to get a simple list of all instances in a certain region, each record should include id, ARN and name of an instance. I've tried using

ec2 describe-instances --region us-east-1

but can't find an ARN in the output.

like image 915
dimid Avatar asked Jan 04 '23 15:01

dimid


1 Answers

You could construct the ARN if it's possible in your use case by knowing the region, account id + the instance ID:

arn:aws:ec2:region:account-id:instance/instance-id
arn:aws:ec2:us-east-1:123456789012:instance/i-1234567890abcdef0

And actually -- as I look at the JSON response, OwnerId appears to contain the account-id so constructing this from the result of describe-instances should be fairly simple.

EDIT: An example using jq to construct the output you're looking for:

aws ec2 describe-instances --region us-east-1 | jq -r '.Reservations[] | .OwnerId as $OwnerId | ( .Instances[] | { "ARN": "arn:aws:ec2:\(.Placement.AvailabilityZone[:-1]):\($OwnerId):instance/\(.InstanceId)", "AvailabilityZone": "\(.Placement.AvailabilityZone)", InstanceId, PublicDnsName, PrivateDnsName, Tags} )' | jq -s .

which would produce output like:

[
  {
    "ARN": "arn:aws:ec2:us-east-1:123456789012:instance/i-0a9842b2da1xxxxxx",
    "AvailabilityZone": "us-east-1a",
    "InstanceId": "i-0a9842b2da1xxxxxx",
    "PublicDnsName": "ec2-72-32-69-225.compute-1.amazonaws.com",
    "PrivateDnsName": "ip-10-0-0-68.ec2.internal",
    "Tags": [
      {
        "Value": "my-beanstalk",
        "Key": "elasticbeanstalk:environment-name"
      },
      {
        "Value": "awseb-e-emiwxxxxxx-stack",
        "Key": "aws:cloudformation:stack-name"
      }
    ]
  },
  {
    "ARN": "arn:aws:ec2:us-east-1:123456789012:instance/i-0a9842b2ca1xxxxxx",
    "AvailabilityZone": "us-east-1a",
    "InstanceId": "i-0a9842b2ca1xxxxxx",
    "PublicDnsName": "ec2-72-32-69-226.compute-1.amazonaws.com",
    "PrivateDnsName": "ip-10-0-0-69.ec2.internal",
    "Tags": [
      {
        "Value": "my-beanstalk-2",
        "Key": "elasticbeanstalk:environment-name"
      },
      {
        "Value": "awseb-e-emizxxxxxx-stack",
        "Key": "aws:cloudformation:stack-name"
      }
    ]
  }
]
like image 152
Dave Maple Avatar answered Jan 13 '23 12:01

Dave Maple