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 호출 추가 등 필요
'Compute > Lambda' 카테고리의 다른 글
AWS Lambda@Edge Redirect / Add Custom Header (0) | 2021.10.08 |
---|---|
AWS Lambda Edge를 이용한 이미지 리사이징 (0) | 2019.12.26 |
AWS Lambda 활용 EIP 변경 (0) | 2017.04.12 |
AWS Lambda를 이용하여 Security Group 자동 제어 (0) | 2016.10.21 |
AWS Lambda를 이용하여 S3 업로드된 파일 meta-data 변경 (0) | 2015.11.18 |