from collections import defaultdict | |
import boto3 | |
""" | |
A tool for retrieving basic information from the running EC2 instances. | |
""" | |
# Connect to EC2 | |
ec2 = boto3.resource('ec2') | |
# Get information for all running instances | |
running_instances = ec2.instances.filter(Filters=[{ | |
'Name': 'instance-state-name', | |
'Values': ['running']}]) | |
ec2info = defaultdict() | |
for instance in running_instances: | |
for tag in instance.tags: | |
if 'Name'in tag['Key']: | |
name = tag['Value'] | |
# Add instance info to a dictionary | |
ec2info[instance.id] = { | |
'Name': name, | |
'Type': instance.instance_type, | |
'State': instance.state['Name'], | |
'Private IP': instance.private_ip_address, | |
'Public IP': instance.public_ip_address, | |
'Launch Time': instance.launch_time | |
} | |
attributes = ['Name', 'Type', 'State', 'Private IP', 'Public IP', 'Launch Time'] | |
for instance_id, instance in ec2info.items(): | |
for key in attributes: | |
print("{0}: {1}".format(key, instance[key])) | |
print("------") |
This comment has been minimized.
This comment has been minimized.
I like this code because I was unable to find any other code example of using boto3 and printing the specific tag values. However, looks like this code would not run properly if the running EC2s have multiple tag names that have "Name" in the tag names. For example, the running instances has a tag name "Name" and value "web1" and has another tag name "Cluster Name" and value "US-West". I have not tested it yet, but I will circle back after I test it. |
This comment has been minimized.
This comment has been minimized.
@sandygvs / anyone else looking for an answer to the above (if I understand the question correctly) - if you're referring to filtering this code by VPC, subnets etc or limiting to a region you can add things like:
If you mean ASG as in outputting security groups, you can add 'SG': instance.security_groups at the end of ec2info, and include it as an attribute. |
This comment has been minimized.
This comment has been minimized.
As @ikekim said this will not work properly if
I used
...because if you examine the |
This comment has been minimized.
This comment has been minimized.
Hola buen dia tengo una duda, como podria obtener el nombre de la instancia ? |
This comment has been minimized.
This comment has been minimized.
Thanks a lot!! |
This comment has been minimized.
This comment has been minimized.
@TacMechMonkey, is there anyway we can filter Instance Status for specific VPCID? resource does not have status option. running_instances = ec2.instances.filter( |
This comment has been minimized.
This comment has been minimized.
@nakkanar you're on the right track, you'll have to use the ec2 client: |
This comment has been minimized.
is there a way to filter out ASG specific to VPC or subnets via python boto? I tried with filter but no luck.
Any help is much appreciated