很抱歉,我提出了一个简单的问题,但尝试了多种选择,但没有任何解决方案。 他的问题是for循环仅采用列表(区域)中的最后一个值。
import boto3
import csv
import io
from io import BytesIO
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
ses = boto3.client('ses')
email_from = 'example@gmail.com'
email_to = 'example@gmail.com'
email_cc = 'example@gmail.com'
emaiL_subject = 'Unused_Security'
email_body = '***Link to S3 Object***'
def lambda_handler(event, context):
regions = ['eu-west-1','eu-west-2','us-east-2','us-west-1','us-west-2','us-east-1']
for region in regions:
csvio = io.BytesIO()
writer = csv.writer(csvio)
writer.writerow([
'Account Name',
'Region',
'Id'
])
ec2 = boto3.resource('ec2', region_name=region)
sgs = list(ec2.security_groups.all())
insts = list(ec2.instances.all())
all_sgs = set([sg.group_id for sg in sgs])
all_inst_sgs = set([sg['GroupId'] for inst in insts for sg in
inst.security_groups])
unused_sgs = all_sgs - all_inst_sgs
for elem in unused_sgs:
writer.writerow([
Account_Name,
region,
elem
])
s3 = boto3.client('s3')
s3.put_object(Body=csvio.getvalue(), ContentType='application/vnd.ms-excel', Bucket='unused-sg', Key='Unused_Security.csv', ACL='public-read')
csvio.close()
s3.get_object(Bucket='unused-sg', Key='Unused_Security.csv')
response = ses.send_email(
Source = email_from,
Destination={
'ToAddresses': [
email_to,
],
'CcAddresses': [
email_cc,
]
},
Message={
'Subject': {
'Data': emaiL_subject
},
'Body': {
'Text': {
'Data': email_body
}
}
}
)
这是列表,仅包含最后一个值
regions = ['eu-west-1','eu-west-2','us-east-2','us-west-1','us-west-2','us-east-1']
它必须获取列表(区域)中的所有值并显示结果。但是它只接受最后一个值(us-east-1)。请告知是什么原因引起的错误。
答案 0 :(得分:2)
这里:
for region in regions:
csvio = io.BytesIO()
writer = csv.writer(csvio)
# ...
s3.put_object(Body=csvio.getvalue(), ContentType='application/vnd.ms-excel', Bucket='unused-sg', Key='Unused_Security.csv', ACL='public-read')
您正在为每个区域创建一个新的csv文件,并覆盖前一个。您想让它脱离循环:
csvio = io.BytesIO()
writer = csv.writer(csvio)
for region in regions:
# massage the data
# write to the csv
# ...
# now we're outside the loop we write the full thing
s3 = boto3.client('s3')
s3.put_object(Body=csvio.getvalue(), ContentType='application/vnd.ms-excel', Bucket='unused-sg', Key='Unused_Security.csv', ACL='public-read')
csvio.close()
答案 1 :(得分:2)
此行 const scores = [
{ day: '1', Barcelona: 1, Real: 3, Valencia: 0},
{ day: '2', Barcelona: 4, Real: 6, Valencia: 3},
{ day: '3', Barcelona: 7, Real: 7, Valencia: 3},
{ day: '4', Barcelona: 7, Real: 8, Valencia: 6},
]
const calculateAverageByTeam = team =>{
const total = scores.map(x=> x[team]).reduce((a,c) => a +c)
return total / scores.length
}
const barcelona = calculateAverageByTeam('Barcelona')
const real = calculateAverageByTeam('Real')
const valencia = calculateAverageByTeam('Valencia')
console.log(barcelona, real, valencia)
中的每个循环都将覆盖csv文件。
将其放在for循环之外,因此仅在循环完成后才写入s3