I have a Python Script that gets the details of the unused security groups. I want that to write into a CSV file and upload to S3 Bucket.
When I test it in local machine it writes to CSV in the local machine. But when I execute that as a lambda function, it needs a place to save the CSV. So I am using s3.
JavaScript
x
32
32
1
import boto3
2
import csv
3
4
ses = boto3.client('ses')
5
6
def lambda_handler(event, context):
7
with open('https://unused******-
8
1.amazonaws.com/Unused.csv', 'w') as csvfile:
9
writer = csv.writer(csvfile)
10
writer.writerow([
11
'Account Name',
12
'Region',
13
'Id'
14
])
15
ec2 = boto3.resource('ec2')
16
sgs = list(ec2.security_groups.all())
17
insts = list(ec2.instances.all())
18
19
all_sgs = set([sg.group_id for sg in sgs])
20
all_inst_sgs = set([sg['GroupId'] for inst in insts for sg in
21
inst.security_groups])
22
23
unused_sgs = all_sgs - all_inst_sgs
24
25
26
for elem in unused_sgs:
27
writer.writerow([
28
Account_Name,
29
region,
30
elem
31
])
32
I want to write the result of “elem” into csv file and upload to S3 Bucket. Kindly advice.
Advertisement
Answer
By using StringIO()
, you don’t need to save the csv to local and just upload the IO to S3. Try my code and let me know if something wrong because I can’t test the code but it was worked for other cases.
JavaScript
1
36
36
1
import boto3
2
import csv
3
import io
4
5
s3 = boto3.client('s3')
6
ses = boto3.client('ses')
7
8
def lambda_handler(event, context):
9
csvio = io.StringIO()
10
writer = csv.writer(csvio)
11
writer.writerow([
12
'Account Name',
13
'Region',
14
'Id'
15
])
16
17
ec2 = boto3.resource('ec2')
18
sgs = list(ec2.security_groups.all())
19
insts = list(ec2.instances.all())
20
21
all_sgs = set([sg.group_id for sg in sgs])
22
all_inst_sgs = set([sg['GroupId'] for inst in insts for sg in
23
inst.security_groups])
24
25
unused_sgs = all_sgs - all_inst_sgs
26
27
for elem in unused_sgs:
28
writer.writerow([
29
Account_Name,
30
region,
31
elem
32
])
33
34
s3.put_object(Body=csvio.getvalue(), ContentType='application/vnd.ms-excel', Bucket='bucket', Key='name_of.csv')
35
csvio.close()
36