Skip to content

Commit 9692b35

Browse files
authored
Create fetchEC2VolumeDetailsUsingBoto3
fetch EC2 Volume details and write at a csv file. upload the file to a S3 bucket. Script to be used on Lambda (using python3.8 setup)
0 parents  commit 9692b35

File tree

1 file changed

+120
-0
lines changed

1 file changed

+120
-0
lines changed

fetchEC2VolumeDetailsUsingBoto3

Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
1+
import json
2+
import boto3
3+
import csv
4+
import datetime
5+
import logging
6+
from os import environ
7+
import collections
8+
import time
9+
import sys
10+
from botocore.exceptions import ClientError
11+
12+
13+
14+
15+
### ENABLE The profilename below, while testing from local. Disable this and session line in 63, enable line 64 session before pushing to Lambda#######
16+
profilename='<>'
17+
aws_Acct='/tmp/temp.csv'
18+
volume_id_list=[]
19+
result = []
20+
#regions = ['us-east-1', 'us-east-2', 'us-west-1', 'us-west-2']
21+
regions = ['us-east-1']
22+
23+
#Name Tag
24+
def get_tag(each, tag_name):
25+
if 'Tags' in each:
26+
for tag in each['Tags']:
27+
if tag['Key'] == tag_name:
28+
return tag['Value']
29+
return ''
30+
31+
#Volumes
32+
def get_vol(each, ec2):
33+
resultVol = {
34+
"vol_id": "",
35+
"vol_size": "",
36+
"vol_type": ""
37+
}
38+
resp = ec2.describe_volumes(
39+
Filters=[{'Name':'attachment.instance-id','Values':[each['InstanceId']]}]
40+
)
41+
for volume in (resp["Volumes"]):
42+
resultVol['vol_id'] += (str(volume["VolumeId"]) + "\n")
43+
resultVol['vol_size'] += (str(volume["Size"]) + "\n")
44+
resultVol['vol_type'] += (str(volume["VolumeType"]) + "\n")
45+
46+
return resultVol
47+
48+
#Security Groups
49+
def sec_gp(each, ec2):
50+
resultSG = {
51+
"sg_id": "",
52+
"sg_name": ""
53+
}
54+
for sg in each['SecurityGroups']:
55+
resultSG['sg_id'] += (str(sg["GroupId"]) + "\n")
56+
resultSG['sg_name'] += (str(sg["GroupName"]) + "\n")
57+
58+
return resultSG
59+
60+
def lambda_handler(event, context):
61+
try:
62+
logging.basicConfig(level=logging.INFO)
63+
logging.info('EC2 Inventory details')
64+
65+
for region in regions:
66+
#session = boto3.Session(profile_name=profilename, region_name=region)
67+
session = boto3.Session(region_name=region)
68+
ec2 = session.client('ec2')
69+
response = ec2.describe_instances()
70+
for item in response["Reservations"]:
71+
for each in item['Instances']:
72+
volsss = get_vol(each, ec2)
73+
sgss = sec_gp(each, ec2)
74+
#print(sgss)
75+
result.append({
76+
#'ImageId': each.get('ImageId', ''),
77+
'InstanceType': each.get('InstanceType', ''),
78+
#'PublicIp': each.get('PublicIpAddress', ''),
79+
#'PrivateIp': each.get('PrivateIpAddress', ''),
80+
#'InstanceId': each.get('InstanceId', ''),
81+
#'SubnetId': each.get('SubnetId', ''),
82+
#'VpcId': each.get('VpcId', ''),
83+
'InstanceName': get_tag(each, 'Name'),
84+
'volume.size': volsss['vol_size'],
85+
'volume.id': volsss['vol_id'],
86+
'volume.type': volsss['vol_type']
87+
#'DeleteOnTermination': each.get('DeleteOnTermination', ''),
88+
#'SGGroupName': sgss['sg_name'],
89+
#'SGGroupID': sgss['sg_id'],
90+
#'State': each['State']['Name'],
91+
#'Region': each['Placement']['AvailabilityZone']
92+
})
93+
94+
# Write to csv file.
95+
header = ['ImageId', 'InstanceType', 'InstanceId', 'InstanceName', 'PublicIp', 'PrivateIp', 'Region', 'State', 'volume.id', 'volume.size', 'volume.type', 'SubnetId', 'VpcId', 'SGGroupName', 'SGGroupID', 'DeleteOnTermination']
96+
with open(aws_Acct, 'w') as file:
97+
writer = csv.DictWriter(file, fieldnames=header)
98+
writer.writeheader()
99+
writer.writerows(result)
100+
101+
file_name = "/tmp/temp.csv"
102+
bucket = "devaansh-webscale"
103+
object_name = "temp.csv"
104+
105+
# Upload the file to S3 bucket
106+
s3_client = boto3.client('s3')
107+
try:
108+
response = s3_client.upload_file(file_name, bucket, object_name)
109+
print('Step 3: upload done')
110+
except ClientError as e:
111+
logging.error(e)
112+
return False
113+
114+
except Exception as e:
115+
logging.error(
116+
'EC2 inventory with uncaught exception: {}'.format(e)
117+
)
118+
119+
if __name__ == '__main__':
120+
lambda_handler(None, None)

0 commit comments

Comments
 (0)