이두잉의 AWS 세상

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

2017.11.14 17:35 - leedoing leedoing

Sample Code(Python boto3)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
cs


Sample Code(Node.js) / 람다 핸들러 추가 필요

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
'use strict'
const AWS = require('aws-sdk');
AWS.config.region = 'ap-northeast-2'
const ec2 = new AWS.EC2();
const waterfall = require('async-waterfall');
let no_tag_ec2 = new Array();
const ec2Describe = (params, callback) => {
        ec2.describeInstances(params, function(err, data){
                for(let 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([
        function(callback){
                let params = {
                }
                ec2Describe(params, function(data){
                        callback(null, data);
                })
        },
        function(data, callback){
                let params = {
                        InstanceIds:data
                }
                ec2.stopInstances(params, function(err, data){
                        if(err) console.log(err, err.stack);
                        else console.log(data);
                })
        }
],function(err, result){
        if(err) console.log(err);
        else console.log(result);
}
)
 
cs


CloudWatch Event Trigger -> Lambda 호출


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

저작자 표시
신고