python-3.x - 如何在用 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'```
解决方案
你声明
tag=[{"Name" :"tag:amiarchive", "Values":[] }]
包含一个项目(这tag
是一个对象)的列表(数组)也是如此。您需要使用整数索引来访问它,例如 tag[0]。然后,一旦您在 tag[0] 处拥有对象,您就可以获取其属性,例如Name
和Values
。您的代码调用tag['Value']
并创建您看到的错误。
推荐阅读
- r - 如何使用 quanteda 查找句子中某些单词出现在某些其他单词之前的实例
- php - 在可以重新访问的 PHP 脚本中设置临时变量
- javascript - 将所有内部标签放入其容器中
- javascript - javascript从单独的字符串中替换循环中的文本
- html - 当我使用 Django Jinjna 模板将“schemaname.tablename”发送到 id 字段时,引导模式弹出中断
- javascript - 为什么履行的诺言没有定义?
- python - 在 DataFrame 中保留一些特定值并将其他值设置为零
- firebase - 更改包名称后应用程序在电话身份验证时崩溃 - Flutter
- python - 如何将逻辑约束转换为一组线性(整数)约束?
- python - 将 2D 数组转换为 3D 数组