Creating an AMI using Labda

I lifted a script which I’m using to create regular AMIs of my production servers and clear out old AMIs .

The script works well but I would like it to use the friendly name instead of the instance ID. Currently the line in question looks like this:

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

This procudes an AMI described thus: Lambda - i-f4f8f869 from 2017-06-28 so if I’m launching an AMI I need to cross-reference the instanceID against the Name tag.

I’m assuming I need to swap out 'InstanceID for something like Name but that doesn’t work.

When I get-help on describe-instance I can’t find a lable for ‘name’ so I’m thinking maybe it can’t be done.

Any help would be appreciated as I’m a noob with this.


Related discussions:

Name is usually a Tag and you should probably use Tags anyways so you can filter however you want, now and in the future. You can then query by whatever tags you want.

I’m pretty sure you want to use instance[‘tag:Name’].

This also has nothing to do with Lambda.

create_image will only take an InstanceId as a way to specify an instance, can’t use the instance’s name directly.

The Name field is actually a tag, so you’ll see it under Tags in the response. It looks like this script is written in Python; here’s the documentation on the describe_instances call:

http://boto3.readthedocs.io/en/latest/reference/services/ec2.html#EC2.Client.describe_instances

Thanks for your reply, I tried this:

AMIid = ec.create_image(InstanceId=instance[‘InstanceId’], Name="Lambda - " + instance[‘InstanceId’] +
instance[‘tag:Name’] + " from " + create_fmt, Description="Lambda created AMI of instance " +
instance[‘InstanceId’] + " from " + create_fmt, NoReboot=True, DryRun=False)

I got: KeyError: ‘tag:Name’

Any further help would be greatly appreciated.

Sector95 is right here. You are going to want to use describe_instances first with your instance[‘InstanceId’] to get the Name tag of the instance in question and then maybe add that to your dict as instance[‘Name’] to use later in the create_image call.

Something like this:

details = ec.describe_instances(InstanceIds=[instance[‘InstanceId’]])

for tags in details[‘Reservations’][0][‘Instances’][0][‘Tags’]:
if tags[‘Key’] == “Name”:
instance[‘Name’] = tags[‘Value’]

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

Look at the documentation link I posted, you should see a Tag key. Name would be under that.

Thank you so much, I’m going to give it a go.