how to print out ec2 tag name with instanceID (boto3)

1

I got following code and works fine with displaying instanceIDs but I want to print out the TAG name as well. which is just the server name. any idea?

import boto3
from boto3 import Session

boto3.setup_default_session(profile_name='account1')

client = boto3.client("ec2")
clientsns = boto3.client("sns")
filter_for = {
    "running": [{"Name": "instance-state-name", "Values": ["running"]}],
}

status = client.describe_instance_status(IncludeAllInstances = True, Filters=filter_for["running"])
failed_instances = []
for i in status["InstanceStatuses"]:    
        in_status = i['InstanceStatus']['Details'][0]['Status']
        sys_status = i['SystemStatus']['Details'][0]['Status']
        
        # check statuses failed instances
        if ((in_status != 'passed') or (sys_status != 'passed')):
             failed_instances.append(i["InstanceId"])

if len(failed_instances)>0:
    new_line = '\n'
    msg = f'The following instances failed status checks:{new_line} {new_line.join(failed_instances)}'
    clientsns.publish(TopicArn='arn:aws:sns:us-west-1:462518063038:test',Message=msg)

asked 2 years ago9841 views
5 Answers
1

i got this to work


def get_tag(tags, key='Name'):
    if not tags: return ''
    for tag in tags:
        if tag['Key'] == key:
            return tag['Value']
    return ''

conn = boto3.resource('ec2')
instances = conn.instances.filter()
for instance in instances:
    instance_name = get_tag(instance.tags)        
    print (instance_name, instance.id, instance.instance_type)

but I cant get this because I keep getting this error

instances = conn.instances.filter(j) TypeError: filter() takes 1 positional argument but 2 were given

answered 2 years ago
profile picture
SUPPORT ENGINEER
reviewed 2 years ago
0

trying to add that into my origin. My list of failed instances is put in an array.

import boto3
from boto3 import Session

boto3.setup_default_session(profile_name='account1')

client = boto3.client("ec2")
clientsns = boto3.client("sns")

status = client.describe_instance_status(IncludeAllInstances = True)
failed_instances = []
for i in status["InstanceStatuses"]:    
        in_status = i['InstanceStatus']['Details'][0]['Status']
        sys_status = i['SystemStatus']['Details'][0]['Status']
        
        # check statuses failed instances
        if ((in_status != 'passed') or (sys_status != 'passed')):
             failed_instances.append(i["InstanceId"])
 #       print(failed_instances)

ec2_resource = boto3.resource('ec2')
instance_info = ec2_resource.instances.filter(
    InstanceIds=i[{failed_instances}],
)

for instance in instance_info:
     print('EC2 instance {} tags:'.format(instance.id))
     if len(instance.tags) > 0:
         for tag in instance.tags:
             print('  - Tag: {}={}'.format(tag["Key"], tag["Value"]))
        

if len(failed_instances)>0:
    new_line = '\n'
    msg = f'The following instances failed status checks:{new_line} {new_line.join(failed_instances)}'
    #msg = f'The following instances failed status checks, {failed_instances}'
    clientsns.publish(TopicArn='arn:aws:sns:us-west-1:462518063038:test',Message=msg)

But got error

Traceback (most recent call last): File "test3.py", line 22, in <module> InstanceIds=i[{failed_instances}], TypeError: unhashable type: 'list'

answered 2 years ago
  • In this case you would need to iterate over the list.

0

The boto3 response for describe_instance_status does not include tag related information. You would need to make another call something along the following lines

ec2_resource = boto3.resource('ec2')
instance_info = ec2_resource.instances.filter(
    InstanceIds=[
        i["InstanceId"],
    ],
)
for instance in instance_info:
     print('EC2 instance {} tags:'.format(instance.id))
     if len(instance.tags) > 0:
         for tag in instance.tags:
             print('  - Tag: {}={}'.format(tag["Key"], tag["Value"]))
RoB
answered 2 years ago
0

any idea how I can get

instance_info from failed_instances = [] ?

answered 2 years ago
0

when i print my failed_instances they show like so

['i-017357c1c4a1a96f8', 'i-07e399b452c7100c3']

how do i read them from ec2_resource = boto3.resource('ec2')

instance_info = ec2_resource.instances.filter( InstanceIds=i[{failed_instances}], )

answered 2 years ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions