Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save denisse-dev/f482d149125ef08d1b82b499bf969efb to your computer and use it in GitHub Desktop.
Save denisse-dev/f482d149125ef08d1b82b499bf969efb to your computer and use it in GitHub Desktop.
cheaply dump ec2 info to csv
import boto3
import csv
# define header row and start a row_list with the header present
header_row = ["account_id", "aws_region", "environment", "instance_id", "instance_name", "security_groups"]
row_list = [header_row]
regions = ["us-east-1", "us-west-2"]
# ---------------------------------------------------------------------------------------------------------------------
# DEFINE FUNCTIONS
# ---------------------------------------------------------------------------------------------------------------------
def get_ec2_sg_info(region, environment):
"""Get EC2 with Security Group info.
>>> get_ec2_sg_info(region)
"""
# Get account_id and region
sts_client = boto3.client("sts")
account_id = sts_client.get_caller_identity()["Account"]
aws_region = region
# Get EC2 info
ec2client = boto3.client('ec2', region_name=region)
response = ec2client.describe_instances()
for reservation in response["Reservations"]:
for instance in reservation["Instances"]:
# start an empty list to hold info
ec2_instance_info = []
# append account_id, environment and region
ec2_instance_info.append(account_id)
ec2_instance_info.append(environment)
ec2_instance_info.append(aws_region)
# append instance_id
ec2_instance_info.append(instance["InstanceId"])
# append instance_name
instancename = ''
for tags in instance["Tags"]:
# print(tags)
if tags["Key"] == 'Name':
instancename = tags["Value"]
ec2_instance_info.append(instancename)
# append security_groups
AttachedSecurityGroups = []
for groups in instance["SecurityGroups"]:
AttachedSecurityGroups.append(groups["GroupName"])
ec2_instance_info.append(AttachedSecurityGroups)
# add instance list to row list
row_list.append(ec2_instance_info)
# reset list for next instance
ec2_instance_info = []
# ---------------------------------------------------------------------------------------------------------------------
# MAIN
# ---------------------------------------------------------------------------------------------------------------------
alias = boto3.client('iam').list_account_aliases()['AccountAliases'][0]
if "nonprod" in alias:
aws_environment = "nonprod"
elif "prod" in alias:
aws_environment = "prod"
else:
aws_environment = "n/a"
get_ec2_sg_info("us-east-1", aws_environment)
get_ec2_sg_info("us-west-2", aws_environment)
# Write CSV
with open('aws_ec2_and_sgs.csv', 'a', newline='') as file:
writer = csv.writer(file)
writer.writerows(row_list)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment