import json
def get_user_params(job_data):
try:
user_parameters = job_data['actionConfiguration']['configuration']['UserParameters']
decoded_parameters = json.loads(user_parameters)
except Exception as e:
raise Exception('UserParameters could not be decoded as JSON')
if 'branch' not in decoded_parameters:
raise Exception('UserParameters JSON must include the "branch"')
if 'instance_name' not in decoded_parameters:
raise Exception('UserParameters JSON must include the "instance_name"')
return decoded_parameters
メインの処理では、CodePipelineにレスポンスを返すようにします。
def lambda_handler(event, context):
codepipeline = boto3.client('codepipeline')
try:
# Get CodePipeline user params.
job_data = event['CodePipeline.job']['data']
params = get_user_params(job_data)
name_tag_value = params['instance_name']
github_branch = params['branch']
print(name_tag_value)
print(github_branch)
# Get target instance id.
target_instance = get_instance(name_tag_value)
instance_id = target_instance['InstanceId']
print(instance_id)
# Get target launch template id.
for tag in target_instance['Tags']:
if tag['Key'] == 'aws:ec2launchtemplate:id':
target_launch_template_id = tag['Value']
break
print(target_launch_template_id)
# Make AMI name.
image_name = make_image_name(name_tag_value)
print(image_name)
# Create AMI from target instance.
description = f'Lambda create. branch:{github_branch} id:{instance_id}'
ami_id = create_ami(image_name, instance_id, description)
print(ami_id)
# Update Launch Template
update_launch_template(target_launch_template_id, ami_id, description)
# Update Launch Template default version.
set_launch_template_default_version(target_launch_template_id)
# Return Success to CodePipeline.
codepipeline.put_job_success_result(
jobId = event['CodePipeline.job']['id'])
except ClientError as e:
print(e)
# Return Failure to CodePipeline.
codepipeline.put_job_failure_result(
jobId = event['CodePipeline.job']['id'],
failureDetails={
'type': 'JobFailed',
'message': str(e)
}
)
Auto Scalingグループに紐付いた起動設定の更新作業って、デプロイ後とかに毎回やっていたのですが、手作業でやると地味に面倒です。 AMI取得 ↓ 起動設定を作成(既存のものからコピーしてName等変更) ↓ Auto Scalingグループの設定更新 この3ステップめんどくないですか?めんどいですよね?自動化しませんか?します(しました)。
{
"targets": [
{
"auto_scaling_group_name": "example-group-name",
"description": ""
},
{
"auto_scaling_group_name": "awesome-group-name",
"description": "The bug was gone with a great fix."
}
]
}
これにより、デプロイ後に行う作業が Auto Scalingグループの名前と説明文を書き換える ↓ テストを走らせる だけになりました(エラーが無ければ)。
import json
def get_user_params(job_data):
try:
user_parameters = job_data['actionConfiguration']['configuration']['UserParameters']
decoded_parameters = json.loads(user_parameters)
except Exception as e:
raise Exception('UserParameters could not be decoded as JSON')
if 'branch' not in decoded_parameters:
raise Exception('UserParameters JSON must include the "branch"')
if 'instance_name' not in decoded_parameters:
raise Exception('UserParameters JSON must include the "instance_name"')
return decoded_parameters