Skip to content

Instantly share code, notes, and snippets.

@sb-davidegironi
Created December 22, 2020 08:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sb-davidegironi/36ad718da81c7ae89618c55e3f941c8d to your computer and use it in GitHub Desktop.
Save sb-davidegironi/36ad718da81c7ae89618c55e3f941c8d to your computer and use it in GitHub Desktop.
AWS Lambda to wait healthy target on Blue/Green deployment for Fargate
const host='myappapi.domain.com';
const port='5000';
const path='/health';
const startupTimeout=10000;
const requestTimeout=10000;
const maxTimeout=300000;
const aws = require('aws-sdk');
const lambda = new aws.Lambda({ region: 'us-east-1' });
const codedeploy = new aws.CodeDeploy();
exports.handler = (event, context, callback) => {
let deploymentId = event.DeploymentId;
let lifecycleEventHookExecutionId = event.LifecycleEventHookExecutionId;
let params = {
deploymentId: deploymentId,
lifecycleEventHookExecutionId: lifecycleEventHookExecutionId,
status: 'Succeeded'
};
lambda.invoke({
FunctionName: 'CodeDeployAATT',
InvocationType: "RequestResponse",
Payload: JSON.stringify({ "host": host, "port": port, "path": path, "startupTimeout": startupTimeout, "requestTimeout": requestTimeout, "maxTimeout": maxTimeout })
}, function(err, data) {
if (err || data.Payload === 'false')
params.status = 'Failed';
codedeploy.putLifecycleEventHookExecutionStatus(params, function(err, data) {
if (err) {
callback('Validation test failed');
} else {
callback(null, 'Validation test succeeded');
}
});
});
};
const http = require('http');
exports.handler = async (event) => {
let host = event.host || '_.domain.com';
let port = event.port || '5000';
let path = event.path || '/health';
let startupTimeout = event.startupTimeout || 10000;
let requestTimeout = event.requestTimeout || 10000;
let maxTimeout = event.maxTimeout || 300000;
let ret = false;
const sleep = m => new Promise(r => setTimeout(r, m));
console.log('waiting ' + startupTimeout + ' milliseconds before start');
await sleep(startupTimeout);
for(let i=0; i<(maxTimeout/requestTimeout); i++) {
try {
if(i != 0) {
console.log('calling ' + host + ':' + port + '' + path + ' for the ' + i + ' time');
let req = http.request({
host: host,
port: port,
path: path,
timeout: 1000,
}, (res) => {
console.log('Result status is: ' + res.statusCode);
if(res.statusCode == 200)
ret = true;
});
req.on('error', (err) => {
console.error(err);
});
req.end();
}
} catch (err) {
console.error(err);
}
if(ret)
break;
await sleep(requestTimeout);
}
console.log('waiting ' + 5000 + ' milliseconds after return');
await sleep(5000);
console.log('returning ' + ret);
return ret;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment