Skip to content

Instantly share code, notes, and snippets.

@digarok
Created February 6, 2019 16:36
Show Gist options
  • Select an option

  • Save digarok/075bc73d7c3eafdade55ced877266481 to your computer and use it in GitHub Desktop.

Select an option

Save digarok/075bc73d7c3eafdade55ced877266481 to your computer and use it in GitHub Desktop.
This will find EC2 resources across multiple accounts and regions (see CONFIG section). Use like, "python swell.py --find myserver"
import boto3, argparse, prettytable
# CONFIG START - PUT YOUR PROFILE NAMES AND REGIONS TO SCAN HERE
account_profiles=['abc-prod-account', 'abc-staging-account', 'abc-dev-account']
regions=['us-east-1','us-west-2']
# CONFIG END
def match_in_keys(o, keys, match):
m = False
for k in keys:
if match.lower() in str(o.get(k,'')).lower():
m = True
return m
parser=argparse.ArgumentParser()
parser.add_argument('--find', help='Match any internal/external IP or Name tag')
args=parser.parse_args()
matchstr = False
if args.find:
matchstr = args.find
instances = []
for account in account_profiles:
for region in regions:
session = boto3.Session(profile_name=account, region_name=region)
ec2client = session.client('ec2')
response = ec2client.describe_instances()
for reservation in response["Reservations"]:
for instance in reservation["Instances"]:
Name = False
for t in instance.get("Tags",[]):
if t['Key'] == 'Name':
Name = t['Value']
instance["Account"] = account
instance["Name"] = Name
search_keys = [
'InstanceId',
'PrivateDnsName',
'PrivateIpAddress',
'PublicDnsName',
'Name'
]
m = match_in_keys(instance, search_keys, matchstr)
if m:
instances.append(instance)
t = prettytable.PrettyTable(['Name', 'InstanceId', 'PrivateIp', 'PublicIp', 'Az', 'Launched', 'State', 'Type', 'Ami', 'Vpc'])
for i in instances:
t.add_row([i.get('Name'), i.get('InstanceId'), i.get('PrivateIpAddress'), i.get('PublicIpAddress'), i['Placement']['AvailabilityZone'], i.get('LaunchTime'), i['State']['Name'], i.get('InstanceType'), i.get('ImageId'), i.get('VpcId')])
print(t)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment