简体   繁体   English

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

[英]Adding tags to EC2 AWS lambda backup script

I am trying to add a tag to an AWS lambda function which creates AMIs of EC2 instances. 我试图将标签添加到创建EC2实例的AMI的AWS lambda函数。 Below is the lambda function I am using: 以下是我正在使用的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")

Now the issues I am facing in this code is related to this part: 现在,我在这段代码中面临的问题与这部分有关:

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

I want to add tags to AMIs when the instance has tag of the format: 当实例具有以下格式的标签时,我想向AMI添加标签:

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

Where XYZ is the value. 其中XYZ是值。

But somehow when the above loop ends, all my instances are getting tagged with the value which comes at the last iteration of the loop. 但是以某种方式,当上述循环结束时,我所有的实例都被标记为循环的最后一次迭代中的值。

Ex. 例如

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

At the end of these three, all the respective AMIs are getting tagged with: {'Key': 'Client', 'Value': 'XYZ'} 在这三个末尾,所有各自的AMI都被标记为: {'Key': 'Client', 'Value': 'XYZ'}

Is there anything I am missing? 我有什么想念的吗?

Any help would be appreciated. 任何帮助,将不胜感激。

PS - There is no indentation issue at the start of the code. PS-代码开头没有缩进问题。

As I used a very similar script for my backups I can comment - 当我使用非常相似的脚本进行备份时,我可以发表评论-

You are setting you variable in the loop for devices and then doing the tagging by groups of instances that have the same retention period. 您要在设备循环中设置变量,然后按具有相同保留期的实例组进行标记。 SO you get the last update to the variable instancename and are updating all of the instances (assuming most share a retention schedule) at once. 因此,您将获得变量实例名称的最新更新,并立即更新所有实例(假设大多数实例共享一个保留计划)。

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

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