Last active
November 15, 2019 17:18
-
-
Save mflopez79/173e358d4fb1ca4dae7afa7383fd47d0 to your computer and use it in GitHub Desktop.
Script that returns ip and other data from aws instances (useful when you've got several ASGs/servers on different accounts)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import argparse | |
import subprocess | |
from collections import defaultdict | |
import boto3 | |
# | |
# On OSX, install boto3 with | |
# $ pip install boto3 --user | |
# | |
parser = argparse.ArgumentParser(description='List aws servers and their private ip addresses') | |
parser.add_argument('servers_prefix',help='search server\'s name with prefix',nargs='?') | |
parser.add_argument('--profile','-p',help='aws profile') | |
parser.add_argument('--region','-r',help='aws region') | |
parser.add_argument('--ip',help='use this flag to search by IP // Output would be only the instance_id (this would be used for SSM access)') | |
args = parser.parse_args() | |
if args.servers_prefix is not None: | |
search_term="*" + args.servers_prefix + "*" | |
else: | |
search_term="*" | |
if args.region is None: | |
session = boto3.Session(aws_access_key_id='',aws_secret_access_key='',profile_name=args.profile) | |
else: | |
session = boto3.Session(aws_access_key_id='',aws_secret_access_key='',region_name=args.region,profile_name=args.profile) | |
ec2 = session.resource("ec2") | |
# Get information for all running instances | |
if args.ip is not None: | |
running_instances = ec2.instances.filter(Filters=[ | |
{'Name': 'private-ip-address','Values': [args.ip]} | |
]) | |
else: | |
running_instances = ec2.instances.filter(Filters=[ | |
{'Name': 'instance-state-name','Values': ['running']}, | |
{'Name': 'tag:Name', 'Values': [search_term]} | |
]) | |
ec2info = defaultdict() | |
if args.ip is None: | |
for instance in running_instances: | |
for tag in instance.tags: | |
if 'Name' == tag['Key']: | |
name = tag['Value'] | |
# Add instance info to a dictionary | |
ec2info[instance.id] = { | |
'name': name, | |
'type': instance.instance_type, | |
'instance id': instance.instance_id, | |
'private ip': instance.private_ip_address, | |
'launch time': instance.launch_time, | |
'vpc id': instance.vpc_id | |
} | |
attributes = ['name', 'type', 'instance id','private ip', 'launch time','vpc id'] | |
for instance_id, instance in ec2info.items(): | |
print("------") | |
for key in attributes: | |
print("{0}: {1}".format(key, instance[key])) | |
print("------") | |
else: | |
for instance in running_instances: | |
print instance.id | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment