{Auto Scaling}チュートリアル:Lambda 関数を呼び出すライフサイクルフックの設定

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

 

-- 1. コマンド等のインストール

-- 1.1 aws cli version 2 インストール

curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
unzip awscliv2.zip
sudo ./aws/install
aws --version

-- 1.2 jqインストール
sudo yum -y install jq

-- 2. 起動テンプレートの作成

vim a.json

{
  "ImageId": "ami-02c3627b04781eada",
  "InstanceType": "t3.nano",
  "SecurityGroupIds": ["sg-11111111111111111"]
}


aws ec2 create-launch-template \
--launch-template-name lt01 \
--launch-template-data file://a.json

 

aws ec2 describe-launch-templates


aws ec2 describe-launch-template-versions --launch-template-id lt-22222222222222222


-- 3. オートスケーリンググループの作成


aws autoscaling create-auto-scaling-group \
--auto-scaling-group-name asg01 \
--launch-template '{
                "LaunchTemplateName": "lt01",
                "Version": "$Default"
            }' \
--min-size 1 \
--max-size 1 \
--desired-capacity 1 \
--default-cooldown 300 \
--health-check-type "EC2" \
--health-check-grace-period 300 \
--vpc-zone-identifier "subnet-33333333333333333" \
--no-new-instances-protected-from-scale-in


aws autoscaling describe-auto-scaling-groups

 

-- 4. IAMポリシー作成
vim policy01.json

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


aws iam create-policy \
--policy-name policy01 \
--policy-document file://policy01.json

-- 5. IAMロール作成
vim role01.json

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Service": "lambda.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}

aws iam create-role \
--role-name role01 \
--assume-role-policy-document file://role01.json

-- 6. ポリシーをロールにアタッチ
aws iam attach-role-policy \
--policy-arn arn:aws:iam::999999999999:policy/policy01 \
--role-name role01

aws iam attach-role-policy \
--policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole \
--role-name role01

 

-- 7. Lambda関数作成

vim test.js

var aws = require("aws-sdk");
exports.handler = (event, context, callback) => {
    console.log('LogAutoScalingEvent');
    console.log('Received event:', JSON.stringify(event, null, 2));
    var autoscaling = new aws.AutoScaling({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; 
    autoscaling.completeLifecycleAction(params, function(err, data) {
        if (err) { 
            console.log(err, err.stack); // an error occurred
            response = {
                statusCode: 500,
                body: JSON.stringify('ERROR'),
            };
        } else {
            console.log(data);           // successful response
            response = {
                statusCode: 200,
                body: JSON.stringify('SUCCESS'),
            };
        }
    });
    return response;
};


chmod 755 test.js
zip test.zip test.js

aws lambda create-function \
--function-name func01 \
--zip-file fileb://test.zip \
--handler test.handler  \
--runtime nodejs14.x  \
--role arn:aws:iam::999999999999:role/role01


aws lambda list-functions | grep func01

aws lambda get-function --function-name func01

 

-- 8. ルールの作成

aws events put-rule \
--name rule01 \
--event-pattern '{"source": ["aws.autoscaling"],"detail-type": ["EC2 Instance-launch Lifecycle Action"]
}' \
--state ENABLED

 

aws events list-rules
aws events describe-rule --name rule01

 

-- 9. ターゲットの作成

aws events put-targets \
--rule rule01 \
--targets "Id"="1","Arn"="arn:aws:lambda:ap-northeast-1:999999999999:function:func01"

aws events list-targets-by-rule \
--rule rule01

 


-- 10. Lambda関数に権限を追加する

aws lambda add-permission \
--function-name func01 \
--statement-id events \
--action lambda:InvokeFunction \
--principal events.amazonaws.com \
--source-arn arn:aws:events:ap-northeast-1:999999999999:rule/rule01

aws lambda get-policy \
--function-name func01 | jq -r .Policy  | jq .

 

-- 11. ライフサイクルフックを追加

aws autoscaling put-lifecycle-hook \
--lifecycle-hook-name lh01 \
--auto-scaling-group-name asg01 \
--lifecycle-transition "autoscaling:EC2_INSTANCE_LAUNCHING" \
--heartbeat-timeout 300 \
--default-result "ABANDON"

 

aws autoscaling describe-lifecycle-hooks \
--auto-scaling-group-name asg01


-- 12. 動作確認

aws autoscaling describe-auto-scaling-groups

aws autoscaling update-auto-scaling-group \
--auto-scaling-group-name asg01 \
--max-size 2 \
--desired-capacity 2

 


-- 13. クリーンアップ


-- ライフサイクルフックの削除
aws autoscaling describe-lifecycle-hooks \
--auto-scaling-group-name asg01

 

aws autoscaling delete-lifecycle-hook \
--auto-scaling-group-name asg01 \
--lifecycle-hook-name lh01

-- ターゲットの削除
aws events list-targets-by-rule \
--rule rule01

aws events remove-targets \
--rule rule01 \
--ids 1


-- ルールの削除
aws events list-rules

aws events delete-rule \
--name rule01

-- Lambda関数の削除
aws lambda get-function --function-name func01
aws lambda delete-function --function-name func01

-- IAMロールの削除
aws iam list-roles | grep role01

aws iam detach-role-policy \
--role-name role01 \
--policy-arn arn:aws:iam::999999999999:policy/policy01

aws iam detach-role-policy \
--role-name role01 \
--policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole


aws iam delete-role --role-name role01


-- IAMポリシーの削除
aws iam list-policies | grep policy01

aws iam delete-policy \
--policy-arn arn:aws:iam::999999999999:policy/policy01

-- オートスケーリンググループの削除

aws autoscaling describe-auto-scaling-groups


aws autoscaling delete-auto-scaling-group \
--auto-scaling-group-name asg01 --force-delete 


-- 起動テンプレートの削除

aws ec2 describe-launch-templates

aws ec2 delete-launch-template \
--launch-template-name lt01