본문 바로가기

Compute/Lambda

AWS Lambda 활용 태깅 없는 EC2 Instance 정지

Sample Code(Python boto3)

import boto3
def lambda_handler(event, context):
    no_tag_instances = []
    ec2 = boto3.client('ec2')
    instances = [i for i in boto3.resource('ec2', region_name='ap-northeast-2').instances.all()]
    # Print instance_id of instances that do not have a Tag of Key='Foo'
    for i in instances:
        if i.tags is None:
            no_tag_instances.append(i.instance_id);
    response = ec2.stop_instances(
        InstanceIds = no_tag_instances
    )
    return response

 

Sample Code(Node.js) / 람다 핸들러 추가 필요(아직 ES6는 지원되지 않음)

'use strict'
const AWS = require('aws-sdk');
AWS.config.region = 'ap-northeast-2'
const ec2 = new AWS.EC2();
const waterfall = require('async-waterfall');
const no_tag_ec2 = new Array();
const ec2Describe = function(params, callback) {
        ec2.describeInstances(params, function(err, data){
                for(const i in data.Reservations){
                        if(!data.Reservations[i].Instances[0].Tags.length){
                                no_tag_ec2.push(data.Reservations[i].Instances[0].InstanceId);
                        };
                }
                callback(no_tag_ec2);
        });
}
waterfall([
callback => {
                const params = {
                }
                ec2Describe(params, (data) => {
                        callback(null, data);
                })
        },
        (data, callback) => {
                const params = {
                        InstanceIds:data
                }
                ec2.stopInstances(params, (err, data) => {
                        if(err) console.log(err, err.stack);
                        else console.log(data);
                })
        }
],(err, result) => {
        if(err) console.log(err);
        else console.log(result);
}
)

 

CloudWatch Event Trigger -> Lambda 호출

 

이 외 예외처리, SES 알람 API 호출 추가 등 필요