繁体   English   中英

将标签添加到EC2 AWS lambda备份脚本

[英]Adding tags to EC2 AWS lambda backup script

我试图将标签添加到创建EC2实例的AMI的AWS lambda函数。 以下是我正在使用的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")

现在,我在这段代码中面临的问题与这部分有关:

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

当实例具有以下格式的标签时,我想向AMI添加标签:

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

其中XYZ是值。

但是以某种方式,当上述循环结束时,我所有的实例都被标记为循环的最后一次迭代中的值。

例如

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

在这三个末尾,所有各自的AMI都被标记为: {'Key': 'Client', 'Value': 'XYZ'}

我有什么想念的吗?

任何帮助,将不胜感激。

PS-代码开头没有缩进问题。

当我使用非常相似的脚本进行备份时,我可以发表评论-

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM