Last active
February 17, 2016 04:35
-
-
Save konstantinvlasenko/01e10a01f208bfc8ef64 to your computer and use it in GitHub Desktop.
AWS CloudFormation Custom Resource - Spot (Part 1 - lambda creator)
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' | |
}; | |
exports.handler = function(event, context) { | |
var ec2 = new AWS.EC2({ region: event.ResourceProperties.Region }); | |
if (event.RequestType === 'Delete') { | |
ec2.terminateInstances({ InstanceIds: [ event.PhysicalResourceId ] }, function(err, data) { | |
if (err) context.fail(err); | |
else { | |
sendResponse(event, function(err){ | |
if (err) context.fail(err); | |
else context.done(); | |
}); | |
} | |
}); | |
} else if(event.RequestType === 'Create') { | |
// create spot request | |
ec2.requestSpotInstances(event.ResourceProperties.params, function(err, data) { | |
if (err) context.fail(err); | |
else { | |
var parsedUrl = url.parse(event.ResponseURL); | |
// store ResponseURL as tag for spot request | |
var _params = { | |
Resources: [ data.SpotInstanceRequests[0].SpotInstanceRequestId ], | |
Tags: [ | |
{ Key: 'cf_hostname', Value: parsedUrl.hostname }, | |
{ Key: 'cf_access', Value: parsedUrl.query }, | |
{ Key: 'cf_stack', Value: event.StackId }, | |
{ Key: 'cf_request', Value: event.RequestId }, | |
{ Key: 'cf_resource', Value: event.LogicalResourceId } | |
] | |
}; | |
ec2.createTags(_params, function(err, data) { | |
if (err) context.fail(err); | |
else context.done(); | |
}); | |
} | |
}); | |
} else { // assume Update | |
context.done(); | |
} | |
}; | |
// Sends a response to the pre-signed S3 URL | |
var sendResponse = function(event, callback) { | |
var _body = JSON.stringify({ | |
Status: 'SUCCESS', | |
StackId: event.StackId, | |
RequestId: event.RequestId, | |
LogicalResourceId: event.LogicalResourceId, | |
PhysicalResourceId: event.PhysicalResourceId | |
}); | |
var parsedUrl = url.parse(event.ResponseURL); | |
var options = { | |
hostname: parsedUrl.hostname, | |
port: 443, | |
path: parsedUrl.path, | |
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