AWS - Create AMI Using EC2 Instance Tags To Name The AMI

时间:2017-06-09 12:58:23

标签: amazon-web-services ami

I'm trying to do something I believe is so simple but I'm not a Python expert, so I need your help on this, let me show you what I'm trying to do:

I have this part of a code that I had found and is working very well, but I'm trying to change it a little bit:

AMIid = ec.create_image(InstanceId=instance['InstanceId'], Name="BKP - " + **instance['InstanceId']** + " from " + create_fmt, Description="Lambda created AMI of instance " + instance['InstanceId'] + " from " + create_fmt, NoReboot=True, DryRun=False)

I'm trying to add the TAG "Name" from my EC2 instances in the field "Name" of the new AMI that is being created, something like this:

AMIid = ec.create_image(InstanceId=instance['InstanceId'], Name="BKP - " + **Tags=[Key:"Name",'Value']** + " from " + create_fmt, Description="Lambda created AMI of instance " + instance['InstanceId'] + " from " + create_fmt, NoReboot=True, DryRun=False)

Any ideas on how to do that?

Editing: I've found a solution for this, maybe this is not the best way, but worked, follow what I've done so far:

Created a variable to get the EC2 Tag name:

nameTag = "".join([str(t.get('Value')) for t in instance['Tags'] if t['Key'] == 'Name'])

Then, included the "nameTag" variable to the code:

AMIid = ec.create_image(InstanceId=instance['InstanceId'], Name="BKP - " + **nameTag** + " from " + create_fmt, Description="Lambda created AMI of instance " + instance['InstanceId'] + " from " + create_fmt, NoReboot=True, DryRun=False)

Hope this could help more people that needs something like that!

Thank you!

1 个答案:

答案 0 :(得分:0)

不确定这是否有用,因为这已经是2年的帖子了,但是

details = ec.describe_instances(InstanceIds=[instance['InstanceId']])
            for tags in details['Reservations'][0]['Instances'][0]['Tags']:
                if tags['Key'] == "Name":
                    instance['Name'] = tags['Value']

            print("Instance Name:" + instance['Name'])

上面的脚本将为您提供实例的名称

相关问题