実現したいこと
Lambda経由でAMI取得する際に、「Name」タグに値を出力する方法が分かりません。
Python歴がかなり浅いので、有識者の方どなたか教えていただけないでしょうか。
現在の状況
とあるサイトより、下記のソースコードをコピペして(若干改変してます。)Lambdaで実行すると、「AMI名」や「説明」には値が出力されるのですが、「Name」タグには出力されません。
ソースコード
Python3
1import os 2import boto3 3import collections 4from time import sleep 5from datetime import datetime, timedelta 6from botocore.client import ClientError 7from logging import getLogger, INFO 8 9logger = getLogger() 10 11ec2_client = boto3.client('ec2') 12 13def lambda_handler(event, context): 14 descriptions = create_image() 15 delete_old_images(descriptions) 16 17def create_image(): 18 instances = get_instances(['AMI-Backup-Generation']) 19 descriptions = {} 20 for instance in instances: 21 tags = { tag['Key']: tag['Value'] for tag in instance['Tags'] } 22 generation = int( tags.get('AMI-Backup-Generation', 0) ) 23 24 if generation < 1: 25 continue 26 27 instance_id = instance.get('InstanceId') 28 create_data_jst = (datetime.now() + timedelta(hours=9)).strftime("%Y%m%d_%H%M%S") 29 ami_name = tags['Name'] 30 ami_name = ami_name + "_" + create_data_jst 31 description = tags['Name'] + " is automatically generated from lambda" 32 33 image_id = _create_image(instance_id, ami_name, description) 34 logger.info('Create Image: ImageId:%s (%s) ' % (image_id['ImageId'], ami_name)) 35 print('Create Image: ImageId:%s (%s) ' % (image_id['ImageId'], ami_name)) 36 descriptions[description] = generation 37 38 return descriptions 39 40def get_instances(tag_names): 41 reservations = ec2_client.describe_instances( 42 Filters=[ 43 { 44 'Name': 'tag-key', 45 'Values': tag_names 46 } 47 ] 48 )['Reservations'] 49 50 return sum([ 51 [instance for instance in reservation['Instances']] 52 for reservation in reservations 53 ], []) 54 55def _create_image(instance_id, ami_name, description): 56 for i in range(1, 3): 57 try: 58 return ec2_client.create_image( 59 Description = description, 60 NoReboot = True, 61 InstanceId = instance_id, 62 Name = ami_name 63 ) 64 except ClientError as e: 65 logger.exception(str(e)) 66 print(str(e)) 67 sleep(2) 68 raise Exception('cannot create image ' + ami_name) 69 70def delete_old_images(descriptions): 71 images_descriptions = get_images_descriptions(list(descriptions.keys())) 72 for description, images in images_descriptions.items(): 73 delete_count = len(images) - descriptions[description] 74 if delete_count <= 0: 75 continue 76 77 images.sort(key=lambda x:x['CreationDate']) 78 old_images = images[0:delete_count] 79 80 for image in old_images: 81 _deregister_image(image['ImageId']) 82 logger.info('Deregister Image: ImageId:%s (%s)' % (image['ImageId'], image['Description'])) 83 print('Deregister Image: ImageId:%s (%s)' % (image['ImageId'], image['Description'])) 84 85def get_images_descriptions(descriptions): 86 images = ec2_client.describe_images( 87 Owners = [ 88 os.environ['AWS_ACCOUNT'] 89 ], 90 Filters = [ 91 { 92 'Name': 'description', 93 'Values': descriptions, 94 } 95 ] 96 )['Images'] 97 98 groups = collections.defaultdict(lambda: []) 99 { groups[ image['Description'] ].append(image) for image in images } 100 101 return groups 102 103def _deregister_image(image_id): 104 for i in range(1, 3): 105 try: 106 return ec2_client.deregister_image( 107 ImageId = image_id 108 ) 109 except ClientError as e: 110 logger.exception(str(e)) 111 print(str(e)) 112 sleep(2) 113 raise Exception('Cannot Deregister image: ' + image_id)
試したこと
上記ではNameタグに値を付与することはできないので、やはり関数を新しく作成した方が
望ましいでしょうか。
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/12/09 10:33
2019/12/09 10:58