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

时间:2017-08-21 12:22:15

标签: python amazon-web-services amazon-ec2 lambda boto3

我正在尝试向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")

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

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'}

我有什么遗失的吗?

任何帮助都将不胜感激。

P.S。 - 代码开头没有缩进问题。

1 个答案:

答案 0 :(得分:0)

由于我使用了非常类似的备份脚本,我可以发表评论 -

您在设备循环中设置变量,然后通过具有相同保留期的实例组进行标记。因此,您获得了变量实例名的最后一次更新,并且正在更新所有实例(假设大多数共享保留计划)。