I am sorry for a simple question, but tried multiple options without any solution. he Problem I have is the for loop is taking only the last value in the list(Regions).
JavaScript
x
68
68
1
import boto3
2
import csv
3
import io
4
from io import BytesIO
5
from email.mime.text import MIMEText
6
from email.mime.application import MIMEApplication
7
from email.mime.multipart import MIMEMultipart
8
9
10
ses = boto3.client('ses')
11
email_from = 'example@gmail.com'
12
email_to = 'example@gmail.com'
13
email_cc = 'example@gmail.com'
14
emaiL_subject = 'Unused_Security'
15
email_body = '***Link to S3 Object***'
16
17
18
def lambda_handler(event, context):
19
regions = ['eu-west-1','eu-west-2','us-east-2','us-west-1','us-west-2','us-east-1']
20
for region in regions:
21
csvio = io.BytesIO()
22
writer = csv.writer(csvio)
23
writer.writerow([
24
'Account Name',
25
'Region',
26
'Id'
27
])
28
ec2 = boto3.resource('ec2', region_name=region)
29
sgs = list(ec2.security_groups.all())
30
insts = list(ec2.instances.all())
31
all_sgs = set([sg.group_id for sg in sgs])
32
all_inst_sgs = set([sg['GroupId'] for inst in insts for sg in
33
inst.security_groups])
34
unused_sgs = all_sgs - all_inst_sgs
35
for elem in unused_sgs:
36
writer.writerow([
37
Account_Name,
38
region,
39
elem
40
])
41
s3 = boto3.client('s3')
42
s3.put_object(Body=csvio.getvalue(), ContentType='application/vnd.ms-excel', Bucket='unused-sg', Key='Unused_Security.csv', ACL='public-read')
43
44
csvio.close()
45
s3.get_object(Bucket='unused-sg', Key='Unused_Security.csv')
46
response = ses.send_email(
47
Source = email_from,
48
Destination={
49
'ToAddresses': [
50
email_to,
51
],
52
'CcAddresses': [
53
email_cc,
54
]
55
},
56
Message={
57
'Subject': {
58
'Data': emaiL_subject
59
},
60
'Body': {
61
'Text': {
62
'Data': email_body
63
}
64
}
65
}
66
)
67
68
This is the list and it takes only the last value
JavaScript
1
2
1
regions = ['eu-west-1','eu-west-2','us-east-2','us-west-1','us-west-2','us-east-1']
2
It has to take all the values in the list(Regions) and display the result. But it takes only the last value(us-east-1). Please advice what is causing the error.
Advertisement
Answer
Here:
JavaScript
1
6
1
for region in regions:
2
csvio = io.BytesIO()
3
writer = csv.writer(csvio)
4
# ...
5
s3.put_object(Body=csvio.getvalue(), ContentType='application/vnd.ms-excel', Bucket='unused-sg', Key='Unused_Security.csv', ACL='public-read')
6
you are creating a new csv file for each region, overwriting the previous one. You want to keep this out of the loop:
JavaScript
1
12
12
1
csvio = io.BytesIO()
2
writer = csv.writer(csvio)
3
for region in regions:
4
# massage the data
5
# write to the csv
6
# ...
7
8
# now we're outside the loop we write the full thing
9
s3 = boto3.client('s3')
10
s3.put_object(Body=csvio.getvalue(), ContentType='application/vnd.ms-excel', Bucket='unused-sg', Key='Unused_Security.csv', ACL='public-read')
11
csvio.close()
12