-
-
Save jjikin/69a5171e1a01f4ec4fa8a0a0408731c3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json | |
import boto3 | |
import os | |
import logging | |
from datetime import datetime | |
logger = logging.getLogger() | |
logger.setLevel(logging.INFO) | |
ec2_name = os.environ['EC2_INSTANCE_NAME'] | |
iam_profile_arn = os.environ['IAM_PROFILE_ARN'] | |
instance_type = os.environ['INSTANCE_TYPE'] | |
key_pair = os.environ['KEY_PAIR'] | |
lt_name = os.environ['LAUNCH_TEMPLATE_NAME'] | |
resource_tag = os.environ['RESOURCE_TAG'] | |
sg_ids = os.environ['SG_IDS'] | |
def lambda_handler(event, context): | |
# 현재시간 계산 | |
now = datetime.utcnow() | |
current_date = now.strftime("%Y-%m-%d") | |
#test_date = '2022-11-15' | |
# 최신 ami id를 가져오기 | |
client = boto3.client('ec2') | |
response = client.describe_images( | |
Filters = [ | |
{ | |
'Name' : 'name', | |
'Values' : ['AwsBackup_*'] | |
}, | |
{ | |
'Name' : 'tag:Name', | |
'Values' : [ec2_name] | |
}, | |
{ | |
'Name' : 'creation-date', | |
'Values' : [current_date + '*'] | |
#'Values' : [test_date + '*'] | |
} | |
] | |
) | |
logger.info(response) | |
latest_ami_id = response['Images'][0]['ImageId'] | |
# sorted_ami_list = sorted(raw['Images'], key = lambda x:x['CreationDate'], reverse = True) | |
# latest_ami_id = sorted_ami_list[0]['ImageId'] | |
sg_list = [ i for i in sg_ids.split(',') ] | |
# 최신 ami로 교체한 Launch Template 새 버전 생성 | |
response = client.create_launch_template_version( | |
LaunchTemplateName = lt_name, | |
LaunchTemplateData = { | |
'ImageId' : latest_ami_id, | |
'InstanceType' : instance_type, | |
'SecurityGroupIds': sg_list, | |
'KeyName': key_pair, | |
'IamInstanceProfile': { 'Arn': iam_profile_arn }, | |
'TagSpecifications': [ | |
{ 'ResourceType':'instance', 'Tags' : [{'Key' : 'Name', 'Value' : resource_tag}]}, | |
{ 'ResourceType':'volume', 'Tags' : [{'Key' : 'Name', 'Value' : resource_tag}]}, | |
{ 'ResourceType':'network-interface', 'Tags' : [{'Key' : 'Name', 'Value' : resource_tag}]} | |
] | |
} | |
) | |
logger.info(response) | |
latest_version_number = str(response['LaunchTemplateVersion']['VersionNumber']) | |
# Launch Template 기본 버전 설정 | |
response = client.modify_launch_template( | |
LaunchTemplateName = lt_name, | |
DefaultVersion = latest_version_number | |
) | |
logger.info(response) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
test