| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 
 | import boto3
 import logging
 import datetime
 import argparse
 
 logging.basicConfig(
 format='%(levelname)s %(asctime)s\n%(message)s',
 datefmt='%Y-%m-%d %H:%M:%S',
 filename='./auto_ami.log',
 level=logging.INFO,
 filemode='a'
 )
 
 
 def get_all_amis(client):
 """
 获取本账户下的所以映像
 :param client:
 :return:
 """
 params = {'Owners': ['909440319734']}
 result = client.describe_images(**params)
 return result['Images']
 
 
 def create_image(client, instanceid, name):
 """
 为指定的实例创建映像
 :param client: boto3 ec2 client
 :param instanceid: EC2 InstanceId
 :param name: 映像名称
 :return: ImageId
 """
 params = {
 'InstanceId': instanceid,
 'NoReboot': True,
 'Name': name,
 'Description': 'Auto created for auto scaling at {time}.'.format(time=datetime.datetime.now().strftime('%Y%m%d%H%M%S'))
 }
 logging.info('try to create image({name}) for {instance}.'.format(name=name, instance=instanceid))
 try:
 result = client.create_image(**params)
 imageid = result['ImageId']
 logging.info('start create image({name}) for {instance}.'.format(name=name, instance=instanceid))
 return imageid
 except Exception as e:
 logging.exception('failed to create image({name}) for {instance}.'.format(name=name, instance=instanceid))
 return None
 
 
 def create_launch_template_version(client, templateid, ami):
 """
 使用指定映像创建指定启动模板的新版本
 :param client: boto3 ec2 client
 :param templateid: Launch TemplateId
 :param ami: ImageId
 :return: Launch Template Version Number
 """
 try:
 result = client.describe_launch_templates(LaunchTemplateIds=[templateid])
 template = result['LaunchTemplates'][0]
 except Exception as e:
 logging.exception(str(e))
 logging.error('can not found launch template({templateid}) to create new version with ami(imageid).'.format(templateid=templateid, imageid=ami))
 return
 
 logging.info('try to create launch template({template}) new version with image({image}).'.format(template=templateid, image=ami))
 try:
 latest_version = str(template['LatestVersionNumber'])
 result = client.create_launch_template_version(
 LaunchTemplateId=templateid,
 SourceVersion=latest_version,
 VersionDescription='Auto created for autoscaling at {time}'.format(time=datetime.datetime.now().strftime('%Y%m%d%H%M%S')),
 LaunchTemplateData={'ImageId': ami}
 )
 return result['LaunchTemplateVersion']['VersionNumber']
 except Exception as e:
 logging.exception(str(e))
 logging.error('create launch template({templateid}) new version with ami(imageid) failed.'.format(templateid=templateid, imageid=ami))
 return
 
 
 def main(args, config):
 region, app, layer, env, group = args.region, args.app, args.layer, args.env, args.group
 
 app_instance_map = config['app_instance_map']
 aws_ak = config['aws_ak']
 aws_sk = config['aws_sk']
 
 client = boto3.client('ec2', aws_access_key_id=aws_ak, aws_secret_access_key=aws_sk, region_name='us-east-1')
 
 info = app_instance_map[region][app][layer][env][group]
 
 image_name = '{region}-{app}-{layer}-{env}-{group}-{time}'.format(region=region, app=app, layer=layer, env=env, group=group, time=datetime.datetime.now().strftime('%Y%m%d%H%M%S'))
 imageid = create_image(client=client, instanceid=info['instance'], name=image_name)
 if not imageid:
 logging.error('can not get imageid. program exit.')
 return
 logging.info('create instance({instance})\'s image({image}) successfully.'.format(instance=info['instance'], image=imageid))
 
 
 version_number = create_launch_template_version(client=client, templateid=info['launch_template'], ami=imageid)
 if not version_number:
 logging.error('can not get launch template new version number. program exit.')
 return
 logging.info('create launch template({template}) new version({version}) successfully.'.format(template=info['launch_template'], version=version_number))
 
 logging.info('SUCCESS')
 
 
 
 if __name__ == '__main__':
 parser = argparse.ArgumentParser()
 parser.add_argument('--region', type=str, choices=['vg', 'bj'], help='Please specify the region')
 parser.add_argument('--app', type=str, help='Please specify the app')
 parser.add_argument('--layer', type=str, choices=['web', 'app'], help='Please specify the layer')
 parser.add_argument('--env', type=str, choices=['prod', 'release'], help='Please specify the env')
 parser.add_argument('--group', type=str, choices=['a', 'b'], help='Please specify the group')
 args = parser.parse_args()
 
 config = {
 'aws_ak': '你的 AWS AccessKey',
 'aws_sk': '你的 AWS AccessSecret',
 'app_instance_map': {
 
 'vg': {
 'xxx': {
 'app': {
 'release': {
 'a': {
 'instance': 'i-xxxxxxxxxxxxxxxxx',
 'launch_template': 'lt-xxxxxxxxxxxxxxxxx'
 },
 'b': {
 'instance': 'i-xxxxxxxxxxxxxxxxx',
 'launch_template': 'lt-xxxxxxxxxxxxxxxxx'
 }
 },
 },
 },
 }
 }
 }
 main(args, config)
 
 
 |