- Architecture

cdp-asg-architecture
  1. 배포 생성
  2. CodeDeploy 서비스에 의해 ASG 그룹 복제
  3. 배포 실패
  4. CodeDeploy 서비스에서 DeploymentFailure 이벤트에 수신 후, SNS topic 트리거
  5. SNS 서비스를 통해 Lambda function invoke

위 과정을 통해 자동삭제를 지원한다.

- Demo

1. Create SNS Topic.

  1. Move to menu (Amazon SNS -> Topics -> Create topic)
  2. Input
  1. Create Topic

2. Configure CodeDeploy Trigger

  1. Move to CodeDeploy (CodeDeploy > Applications > Click > Click > Edit > Advanced > Triggers > Create trigger)
  2. Input
  1. Save changes

3. Create AWS Lambda function and IAM Role

  1. Move to Lambda (Lambda > Functions > Create function)
  2. Input
  1. Create function

  2. Move to IAM (IAM > Roles > Search ‘CodeDeployDeploymentHandler-role’ > Click CodeDeployDeploymentHandler-role- > Permission tab > Add permission > Attach policies)

  3. Input

  1. Add permissions

4. Create subscription in SNS topic

  1. Move to subscription (Amazon SNS > Topics > CodeDeploy_CDP_BG_FailedTopic(Created in step one) > Subscriptions tab > Create subscription)
  2. Input
  1. Create subscription

5. Modify AWS Lambda code

  1. Move to Lambda (Lambda > Functions > CodeDeployDeploymentHandler)
  2. Input
import json
import boto3


def lambda_handler(event, context):
    # TODO implement
    message = event['Records'][0]['Sns']['Message']

    # Print the message content for debugging purposes (optional)
    print(f"Received SNS message: {message}")

    # Parse the JSON message (if applicable)
    try:
        sns_data = json.loads(message)
    except json.JSONDecodeError:
        sns_data = 'JSONDecodeError Occurred'  # Handle non-JSON messages

    print(f"Processing message data: {sns_data}")
    deploymentGroupName = sns_data['deploymentGroupName']
    deploymentId = sns_data['deploymentId']

    print(f"deploymentGroupName: {deploymentGroupName}")
    print(f"deploymentId: {deploymentId}")

    response = delete_failed_asg(deploymentGroupName, deploymentId)
    return response


def delete_failed_asg(deploymentGroupName, deploymentId):
    asg_client = boto3.client('autoscaling')
    asg_name = "CodeDeploy_" + deploymentGroupName + "_" + deploymentId

    print(f"asg_name: {asg_name}")

    response = asg_client.delete_auto_scaling_group(
        AutoScalingGroupName=asg_name,
        ForceDelete=True
    )
    return response

6. Test

Deploy a new deployment using EC2 Autoscaling Group deployment group and make it fails. Then, CodeDeploy trigger SNS and Lambda function subscribing SNS works. Now, you can see the ASG created by CodeDeploy as a part of failure is removed automatically.

The Lambda code is sample source code. You can develop on your own language or change.