Python 3.x AWS Lambda Python脚本未遍历';aws#U账号';果然
我有一个用Python 3.7编写的AWS Lambda函数,该函数设置为删除超过120天的快照。我从一个管理帐户运行这个,并使用“aws\U帐户\U编号”点击两个子帐户。该函数成功运行,但在CloudWatch中,日志显示每个帐户删除的快照相同。日志显示已删除accountA的快照x y z,但随后显示已删除accountB的相同快照x y z。实际情况是,所有这些快照都不存在于accountA或accountB中,但它们实际上存在于管理帐户中Python 3.x AWS Lambda Python脚本未遍历';aws#U账号';果然,python-3.x,amazon-web-services,aws-lambda,Python 3.x,Amazon Web Services,Aws Lambda,我有一个用Python 3.7编写的AWS Lambda函数,该函数设置为删除超过120天的快照。我从一个管理帐户运行这个,并使用“aws\U帐户\U编号”点击两个子帐户。该函数成功运行,但在CloudWatch中,日志显示每个帐户删除的快照相同。日志显示已删除accountA的快照x y z,但随后显示已删除accountB的相同快照x y z。实际情况是,所有这些快照都不存在于accountA或accountB中,但它们实际上存在于管理帐户中 from datetime import dat
from datetime import datetime, timedelta, timezone
import boto3
import collections
import sys
from botocore.exceptions import ClientError
region ='us-east-1'
aws_account_numbers = {"accountA":"xxxxxxxxxxxx", "accountB":"xxxxxxxxxxxx"}
def lambda_handler(event, context):
delete_time = datetime.now(tz=timezone.utc) - timedelta(days=120)
ec2_resource = boto3.resource('ec2')
snapshots = ec2_resource.snapshots.filter(OwnerIds=['self'])
for name, acctnum in aws_account_numbers.items():
roleArn = "arn:aws:iam::%s:role/EOTSS-Snapshot-Cleanup-120days" % 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'])
for snapshot in snapshots:
try:
if not snapshot.description.startswith('Snapshot created by task soe-backup') and delete_time > snapshot.start_time:
#snapshot.delete()
print ("Snapshot %s is deleted in acct: %s" % (snapshot, acctnum))
except ClientError as e:
if e.response['Error']['Code'] == 'InvalidSnapshot.InUse':
print ("Snapshot %s in use in acct: %s" % (snapshot, acctnum))
continue
else:
print("Unexpected error: %s" % e)
continue
return 'Execution Complete'
您正在管理帐户上调用
snapshots=ec2\u资源。它应该在你担任其他帐户的角色后调用。你所说的对我来说是合乎逻辑的,我做了更改并修复了缩进,但我仍然得到了相同的结果。我不确定如何在这里发布我的新代码,但行'snapshots=ec2_resource.snapshots.filter(OwnerIds=['self'])已下移到“for name,acctnum”部分下。