首页 > 解决方案 > 如何在用 python 3.7 编写的 lambda 函数中传递 AMI 标签值

问题描述

我有以下 Python 3.7 Lambda 函数,我想删除超过 90 天的 AMI,但我想排除任何具有“amiarchive”/“yes”标签/值组合的 AMI。当我运行它时,我收到错误“列表索引必须是整数或切片,而不是 str”。我已经做了很多研究,但我无法完全弄清楚这一点。

import collections
import sys
from datetime import datetime, timedelta, timezone
from botocore.exceptions import ClientError

region ='us-east-1'

aws_account_numbers = {"accountA":"xxxxxxxxxxxx"}

def lambda_handler(event, context):

    delete_time = datetime.now() - timedelta(days=90)  

   
    for name, acctnum in aws_account_numbers.items():
        roleArn = "arn:aws:iam::%s:role/EOTSS-Snapshot-Cleanup-90days" % acctnum
        stsClient = boto3.client('sts')
        sts_response = stsClient.assume_role(RoleArn=roleArn,RoleSessionName='AssumeCrossAccountRole', DurationSeconds=1800)
        ec2 = boto3.resource(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'])
                
        ec = boto3.client('ec2', 'us-east-1')
        images = ec2.images.filter(Owners=["self"])
        tag=[{"Name" :"tag:amiarchive", "Values":[] }]
        
        for image in images:  

                t = datetime.strptime(image.creation_date, "%Y-%m-%dT%H:%M:%S.%fZ")
                
                try:
                    if delete_time > t and (tag['Value']) != yes:
                        print ("AMI %s deregistered in acct: %s" % (image.image_id, acctnum))
                        response = image.deregister()
                                
                except ClientError as e:
                    if e.response['Error']['Code'] == 'InvalidImage.InUse':
                        print("Image in use")
                        continue
                    else:
                        print("Unexpected error: %s" % e)
                        continue
                        
    return 'Execution Complete'```

标签: python-3.xaws-lambda

解决方案


你声明

tag=[{"Name" :"tag:amiarchive", "Values":[] }]

包含一个项目(这tag是一个对象)的列表(数组)也是如此。您需要使用整数索引来访问它,例如 tag[0]。然后,一旦您在 tag[0] 处拥有对象,您就可以获取其属性,例如NameValues。您的代码调用tag['Value']并创建您看到的错误。


推荐阅读