๐Ÿš€ Languege/DevOps

AWS Codepipeline lambda ์‹คํ–‰ํ•˜๊ธฐ

mini_world 2022. 8. 10. 22:33
๋ชฉ์ฐจ ์ ‘๊ธฐ

Codepipeline์—์„œ lambda๋ฅผ ์‹คํ–‰ํ•˜๋ ค๋ฉด, Codepipelin์—๊ฒŒ ์™„๋ฃŒ๋˜์—ˆ๋Š”์ง€ ์—ฌ๋ถ€๋ฅผ ์•Œ๋ ค์ค˜์•ผ ํ•œ๋‹ค.

์•„๋ž˜ ์ฝ”๋“œ๋Š” ๋‹จ๋…์‹คํ–‰ task๋ฅผ ์œ„ํ•œ ์ƒ˜ํ”Œ ์ฝ”๋“œ์ด๋‹ค. 

import urllib3
import json
import boto3
import json
import botocore.exceptions

def lambda_handler(event, context):

    client = boto3.client("ecs", region_name="ap-northeast-2")
    waiter = client.get_waiter('tasks_stopped')
    code_pipeline = boto3.client('codepipeline')
    job_id = event['CodePipeline.job']['id']
    
    #ECS
    task_id='<TaskId>'
    cluster_id='<ClusterId>'
    cp_id='<์šฉ๋Ÿ‰๊ณต๊ธ‰์žID>'
    
    try:
        response = client.run_task(
            taskDefinition=task_id,
            cluster=cluster_id,
            count=1,
            capacityProviderStrategy=[
            {
                'capacityProvider': cp_id,
                'weight': 1,
                'base': 1
            }])
        container_task_id = response["tasks"][0]["containers"][0]["taskArn"].split('/')[2]
        print(container_task_id)

        waiter.wait(
            cluster=cluster_id,
            tasks=[container_task_id],
            WaiterConfig={
                'Delay': 10,
                'MaxAttempts': 10
            }
        )
    except botocore.exceptions.ClientError as e:
        code_pipeline.put_job_failure_result(jobId=job_id, failureDetails={'message': 'task ์‹คํ–‰ ์‹คํŒจ', 'type': 'JobFailed'})      
        print(e.response['Error']['Message'])

    else:
        code_pipeline.put_job_success_result(jobId=job_id)

    print('Function complete.')   
    return "Complete."