Friday, February 4, 2022

[SOLVED] How to Display EC2 Instance name using Boto 3

Issue

I am using the below code for displaying instance_id,instance_type but I am unable to display the Instance name which I want

print (instance.id, instance.instance_type, region) this is working but this not instance.instance_name

import boto3
access_key = "AKIAJ5G2FAUVO3TXXXXXXXX"
secret_key = "nk7eytkWfoSDU0GwvBZVawQvXXXXXX"
client = boto3.client('ec2', aws_access_key_id=access_key, aws_secret_access_key=secret_key,region_name='us-east-1')
ec2_regions = [region['RegionName'] for region in client.describe_regions()['Regions']]
for region in ec2_regions:
                conn = boto3.resource('ec2', aws_access_key_id=access_key, aws_secret_access_key=secret_key,region_name=region)
                instances = conn.instances.filter()
                for instance in instances:
                    if instance.state["Name"] == "running":
                        print (instance.instance_name,instance.id, instance.instance_type, region)

Solution

There instance object you are using does not have a name attribute. The reason is that the "Name" of an instance, is only based on a tag called Name. So you have to get tags, and find a tag name of Name:

def get_tag(tags, key='Name'):

  if not tags: return ''

  for tag in tags:
  
    if tag['Key'] == key:
      return tag['Value']
    
  return ''

ec2_regions = [region['RegionName'] for region in client.describe_regions()['Regions']]

for region in ec2_regions:
    conn = boto3.resource('ec2', aws_access_key_id=access_key, aws_secret_access_key=secret_key,region_name=region)
    instances = conn.instances.filter()
    for instance in instances:
        instance_name = get_tag(instance.tags)        
        print (instance_name, instance.id, instance.instance_type, region)



Answered By - Marcin
Answer Checked By - Robin (WPSolving Admin)