Created
April 16, 2018 17:43
-
-
Save miguelmota/1e2dab56709268addb77f4f657b34c8a to your computer and use it in GitHub Desktop.
AWS node.js deregister all unhealthy elastic load balancer targets
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
const AWS = require('aws-sdk') | |
const elb = new AWS.ELBv2({apiVersion: '2015-12-01', region: 'us-east-1'}) | |
async function getTGs(loadBalancerArn) { | |
return new Promise((resolve, reject) => { | |
elb.describeTargetGroups({}, (err, data) => { | |
if (err) return reject(err) | |
resolve(data.TargetGroups.map(x => x.TargetGroupArn)) | |
}) | |
}) | |
} | |
async function getHealth(tg) { | |
return new Promise((resolve, reject) => { | |
elb.describeTargetHealth({ | |
TargetGroupArn: tg | |
}, (err, data) => { | |
if (err) return reject(err) | |
resolve(data.TargetHealthDescriptions.map(x => { | |
return { | |
target: x.Target, | |
state: x.TargetHealth.State, | |
} | |
})) | |
}) | |
}) | |
} | |
async function deregisterTargets(tgGroupArn, tgs) { | |
return new Promise((resolve, reject) => { | |
if (!tgs.length) { | |
return resolve({targetGroupArn: tgGroupArn, message: 'nothing to deregister'}) | |
} | |
elb.deregisterTargets({ | |
TargetGroupArn: tgGroupArn, | |
Targets: tgs | |
}, (err, data) => { | |
if (err) return reject(err) | |
resolve(data) | |
}) | |
}) | |
} | |
exports.handler = async (event, context, callback) => { | |
const tgs = await getTGs() | |
const data = await Promise.all(tgs.map(async tg => { | |
const healths = await getHealth(tg) | |
const unhealthy = healths.reduce((acc, x) => { | |
if (x.state === 'unhealthy') { | |
acc.push(x.target) | |
} | |
return acc | |
}, []) | |
return await deregisterTargets(tg, unhealthy) | |
})) | |
if (typeof callback == 'function') { | |
callback(null, data) | |
} | |
console.log(data) | |
return data | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment