Skip to content

Instantly share code, notes, and snippets.

@miguelmota
Created April 16, 2018 17:43
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 miguelmota/1e2dab56709268addb77f4f657b34c8a to your computer and use it in GitHub Desktop.
Save miguelmota/1e2dab56709268addb77f4f657b34c8a to your computer and use it in GitHub Desktop.
AWS node.js deregister all unhealthy elastic load balancer targets
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