向EC2 AWS lambda备份脚本添加标记

2024-04-29 11:29:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图向AWS lambda函数添加一个标记,该函数创建EC2实例的ami。下面是我使用的lambda函数:

import boto3
import collections
import datetime
import sys
import pprint

ec = boto3.client('ec2')
retention_days = 7
def lambda_handler(event, context):

reservations = ec.describe_instances(
    Filters=[
        {'Name': 'tag-key', 'Values': ['backup', 'Backup', 'Client']},
    ]
).get(
    'Reservations', []
)
print (reservations)
instances = sum(
    [
        [i for i in r['Instances']]
        for r in reservations

    ], [])

print "Found %d instances that need backing up" % len(instances)

to_tag = collections.defaultdict(list)

for instance in instances:
        name_tag = [
            str(t.get('Value')) for t in instance['Tags']
            if t['Key'] == 'Name'][0]
        print (name_tag)
        print ("check_loop")

        create_time = datetime.datetime.now()
        create_fmt = create_time.strftime('%Y-%m-%d')

        AMIid = ec.create_image(InstanceId=instance['InstanceId'], Name="Lambda12 - " + instance['InstanceId'] + " " + name_tag +" from " + create_fmt, Description="Lambda created AMI of instance " + instance['InstanceId'] + " " + name_tag + " from " + create_fmt, NoReboot=True, DryRun=False)
        to_tag[retention_days].append(AMIid['ImageId'])

        delete_date = datetime.date.today() + datetime.timedelta(days=retention_days)
        delete_fmt = delete_date.strftime('%m-%d-%Y')


        instancename = ''
        for tags in instance["Tags"]:
            if tags["Key"] == 'Client':
                print ("This is instance inside if with key" + tags["Key"])
                instancename = tags["Value"]
                print ("This is instancename" + instancename )
                ec.create_tags (
                    DryRun=False,
                    Resources=to_tag[retention_days],
                    Tags=[
                          {'Key': 'Client', 'Value': instancename},
                    ]
                )
            print "This is last instancename" + instancename

        ec.create_tags(
            Resources=to_tag[retention_days],
            Tags=[
                    {'Key': 'DeleteOn', 'Value': delete_fmt},
                ]
        )


        print ("Name tag " + name_tag)
        print ("check_loopend")

现在我在这段代码中遇到的问题与此部分有关:

^{pr2}$

我想在实例具有以下格式的标记时向AMIs添加标记:

{'Key': 'Client', 'Value': 'XYZ'}

其中XYZ是值。

但是,当上面的循环结束时,我的所有实例都被标记为循环最后一次迭代时的值。

例如

实例1-{'Key': 'Client', 'Value': 'ABC'} 实例2-密钥不存在 实例3-{'Key': 'Client', 'Value': 'XYZ'}

在这三项的最后,所有的非盟驻苏特派团都被标记为: {'Key': 'Client', 'Value': 'XYZ'}

我有什么遗漏吗?

任何帮助都将不胜感激。

注:代码开头没有缩进问题。


Tags: 实例instancekey标记importclientdatetimevalue
1条回答
网友
1楼 · 发布于 2024-04-29 11:29:18

因为我在备份时使用了一个非常相似的脚本,所以我可以评论-

在循环中为设备设置变量,然后按具有相同保留期的实例组进行标记。因此,您将获得对变量instancename的最后一次更新,并同时更新所有实例(假设大多数实例共享一个保留计划)。在

相关问题 更多 >