본문 바로가기
자습

AWS ASG lifecycle Hook (remotely run shell command on EC2)

by litaro 2024. 3. 29.

https://docs.aws.amazon.com/autoscaling/ec2/userguide/lifecycle-hooks-overview.html

https://docs.aws.amazon.com/autoscaling/ec2/userguide/tutorial-lifecycle-hook-lambda.html

 

Tutorial: Configure a lifecycle hook that invokes a Lambda function - Amazon EC2 Auto Scaling

Tutorial: Configure a lifecycle hook that invokes a Lambda function In this exercise, you create an Amazon EventBridge rule that includes a filter pattern that when matched, invokes an AWS Lambda function as the rule target. We provide the filter pattern a

docs.aws.amazon.com

 

1. Policy 와 Role 생성

{
	"Version": "2012-10-17",
	"Statement": [
		{
			"Effect": "Allow",
			"Action": [
				"autoscaling:CompleteLifecycleAction"
			],
			"Resource": "arn:aws:autoscaling:*:...:autoScalingGroup:...:autoScalingGroupName/..."
		},
        {
            "Effect": "Allow",
            "Action": [
                "ssm:SendCommand",
                "ssm:GetCommandInvocation"
            ],
            "Resource": [
                "*"
            ]
        }
	]
}

2. Lambda 함수 생성

Lambda 코드는 AWS Tutorial 코드 활용

import { AutoScalingClient, CompleteLifecycleActionCommand } from "@aws-sdk/client-auto-scaling";
export const handler = async(event) => {
  console.log('LogAutoScalingEvent');
  console.log('Received event:', JSON.stringify(event, null, 2));
  var autoscaling = new AutoScalingClient({ region: event.region });
  var eventDetail = event.detail;
  var params = {
    AutoScalingGroupName: eventDetail['AutoScalingGroupName'], /* required */
    LifecycleActionResult: 'CONTINUE', /* required */
    LifecycleHookName: eventDetail['LifecycleHookName'], /* required */
    InstanceId: eventDetail['EC2InstanceId'],
    LifecycleActionToken: eventDetail['LifecycleActionToken']
  };
  var response;
  const command = new CompleteLifecycleActionCommand(params);
  try {
    var data = await autoscaling.send(command);
    console.log(data); // successful response
    response = {
      statusCode: 200,
      body: JSON.stringify('SUCCESS'),
    };
  } catch (err) {
    console.log(err, err.stack); // an error occurred
    response = {
      statusCode: 500,
      body: JSON.stringify('ERROR'),
    };
  }
  return response;
};

3. EventBridge Rule 생성

4. Lifecyel Hook 추가

5. Test ~~ Log 확인

Desired capacity 수정 

...     INFO    Received event: {
    "version": "0",
    "id": "123...",
    "detail-type": "EC2 Instance-terminate Lifecycle Action",
    "source": "aws.autoscaling",
    "account": "123456789",
    "time": "2024-03-28T05:49:33Z",
    "region": "eu-west-1",
    "resources": [
        "arn:aws:autoscaling:...:autoScalingGroup:...:autoScalingGroupName/CodeDeploy_abc"
    ],
    "detail": {
        "LifecycleActionToken": "abcd",
        "AutoScalingGroupName": "CodeDeploy_abc",
        "LifecycleHookName": "LogAutoScalingEvent-hook",
        "EC2InstanceId": "i-abc",
        "LifecycleTransition": "autoscaling:EC2_INSTANCE_TERMINATING",
        "Origin": "AutoScalingGroup",
        "Destination": "EC2"
    }
}
  
 
    INFO    {
  '$metadata': {
    httpStatusCode: 200,
    requestId: '123...',
    extendedRequestId: undefined,
    cfId: undefined,
    attempts: 1,
    totalRetryDelay: 0
  }
}

6. 실제 동작 확인

Run Command HIstory 에서 실행 결과 확인

 

이제 아래 flow 를 완성하기 위해서는 EC2 권한 추가만 하면 끝~!!

7. Command 를 실행할 EC2 Role 에 권한 추가

AmazonSSMFullAccess
AmazonSSMManagedInstanceCore

'자습' 카테고리의 다른 글

AWS EC2 X-Ray Enable  (0) 2024.02.24
Go Thread-Safety : sync.Mutex, sync.Map  (0) 2023.08.26
Spring Native  (0) 2022.05.14
go gRPC Server & gRPC Gateway  (0) 2021.09.20
Kong Gateway + Konga  (0) 2021.08.29