Created
February 17, 2016 04:36
-
-
Save konstantinvlasenko/7757d7c7ed109f925ea7 to your computer and use it in GitHub Desktop.
AWS CloudFormation Custom Resource - Spot (Part 2 - lambda response on instance created)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var AWS = require('aws-sdk'); | |
var https = require('https'); | |
var url = require('url'); | |
AWS.config.apiVersions = { | |
ec2: '2015-10-01' | |
}; | |
var ec2 = new AWS.EC2(); | |
exports.handler = function(event, context) { | |
var _instanceId = event.detail['instance-id']; | |
var _ec2 = { InstanceIds: [ _instanceId ] }; | |
ec2.describeInstances(_ec2, function(err, data) { | |
if (err) context.fail(err); | |
else { | |
var _instance = data.Reservations[0].Instances[0]; | |
var _params = { Filters: [ | |
{ Name: 'resource-id', Values: [ _instance.SpotInstanceRequestId ] }, | |
{ Name: 'key', Values: [ 'cf_hostname', 'cf_access', 'cf_stack', 'cf_request', 'cf_resource' ] } | |
] }; | |
ec2.describeTags(_params, function(err, data) { | |
if (err) context.fail(err); | |
else { | |
if(data.Tags.length === 5) { // our instance | |
var _cf = getCfEvent(data.Tags); | |
sendResponse(_cf, _instance, function(err){ | |
if (err) context.fail(err); | |
else context.done(); | |
}); | |
} else { // do nothing | |
context.done(); | |
} | |
} | |
}); | |
} | |
}); | |
}; | |
// Sends a response to the pre-signed S3 URL | |
var getCfEvent = function(tags) { | |
var _result = {}; | |
tags.forEach(function(tag){ | |
_result[tag.Key] = tag.Value; | |
}); | |
return _result; | |
}; | |
// Sends a response to the pre-signed S3 URL | |
var sendResponse = function(cf, instance, callback) { | |
var _body = JSON.stringify({ | |
Status: 'SUCCESS', | |
Reason: 'Instance started', | |
PhysicalResourceId: instance.InstanceId, | |
StackId: cf.cf_stack, | |
RequestId: cf.cf_request, | |
LogicalResourceId: cf.cf_resource, | |
Data: instance | |
}); | |
var _options = { | |
hostname: cf.cf_hostname, | |
port: 443, | |
path: '/' + cf.cf_stack.replace(/:/g, '%3A') + '%7C' + cf.cf_resource + '%7C' + cf.cf_request + '?' + cf.cf_access, | |
method: 'PUT', | |
headers: { | |
'Content-Type': '', | |
'Content-Length': _body.length | |
} | |
}; | |
var req = https.request(_options, function(res) { | |
console.log('STATUS:', res.statusCode); | |
callback(null); | |
}); | |
req.on('error', function(err) { | |
callback(err); | |
}); | |
req.write(_body); | |
req.end(); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment