在Python代码中嵌套了for语句的意外结果

时间:2019-04-23 19:32:29

标签: python-3.x aws-lambda boto3

我有2个AWS账户。我正在编写代码(具有交叉帐户角色)来监视EC2标签值(日期xx / xx / xx)中的标签“ expenddate”。这适用于单个帐户,但是我在代码的多个帐户结构上遇到麻烦。我在一个帐户(主帐户)中有3个标签,在另一个帐户(子帐户)中有2个标签,应进行报告。

import boto3
import collections
import datetime
import time
import sys

sns_client = boto3.client('sns')

from datetime import date as dt

aws_account_numbers = { "MassIT-Core":"xxxxxxxxxxxx", "MassIT-Engineering-Sandbox":"xxxxxxxxxxxx"}

def lambda_handler(event, context):
    roleArn = "arn:aws:iam::%s:role/CrossAccount-CostExplorer-Role" % account_num
     stsClient = boto3.client('sts')
     sts_response = stsClient.assume_role(RoleArn=roleArn,RoleSessionName='AssumeCrossAccountRole', DurationSeconds=1800)
     ec2 = boto3.client(service_name='ec2',region_name=region,aws_access_key_id = sts_response['Credentials']['AccessKeyId'],
                       aws_secret_access_key = sts_response['Credentials']['SecretAccessKey'], aws_session_token = sts_response['Credentials']['SessionToken'])

def lambda_handler(event, context):
    acctnum2 = (boto3.client('sts').get_caller_identity()['Account'])
    today = datetime.date.today()
    mdy = today_string = today.strftime('%m/%d/%y')
    ec2 = boto3.resource('ec2')
        for name, acctnum in aws_account_numbers.items():
            for instance in ec2.instances.all():
                if instance.tags is None:
                    continue
                for tag in instance.tags:
                    if tag['Key'] == 'expenddate':
                        expiredInstances=[]
                        if (tag['Value']) <= mdy:
                            sns_client.publish(
                                TopicArn = 'arn:aws:sns:us-east-1:xxxxxxxxxxxx:EOTSS-Monitor-Tag-Exceptions',
                                Subject = '!!!! Tag Exception has Expired.',
                                Message = str("The tag exception for instance %s has expired in account %s" % (instance.id,acctnum2)))
                        else:
                            print ("end")

我得到的结果是报告3个标签的6封电子邮件(sns),一次是主帐户,一次是子帐户。这3个EC2实例不存在于子帐户中。我是Python的新手。我想要得到的是3个来自主帐户的电子邮件和2个来自子帐户的电子邮件,这两个电子邮件代表的是expdenddate已通过的手动标签。

0 个答案:

没有答案