Created
February 19, 2019 18:28
-
-
Save ayavilevich/9cea31154a71d079cb5328006a72bd53 to your computer and use it in GitHub Desktop.
AWS Elastic Beanstalk "is leader instance" check for use with cron, etc (nodejs, async/await).
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
// based on https://gist.github.com/tony-gutierrez/de5b304fd042f6140eb61a31d0ff92d5 | |
async function isLeader() { | |
try { | |
// get APIs | |
var elasticbeanstalk = new AWS.ElasticBeanstalk(); | |
var ec2 = new AWS.EC2(); | |
var metadata = new AWS.MetadataService(); | |
// get ec2 instance id | |
const request = new Promise( (resolve, reject) => { // MetadataService.request has no support for promise, make one ourselves | |
metadata.request('/latest/meta-data/instance-id', (err, InstanceId) => { | |
if (err) {return reject(err);} | |
return resolve(InstanceId) | |
}); | |
}); | |
const currentInstanceId = await request; | |
console.log('currentInstanceId', currentInstanceId); | |
// get env id | |
var params = { | |
Filters: [ | |
{ | |
Name: 'resource-id', | |
Values: [currentInstanceId] | |
} | |
] | |
}; | |
const tagData = await ec2.describeTags(params).promise(); // needs ec2:DescribeTags permission | |
console.log('tagData', tagData); | |
const envIdTag = tagData.Tags.find(t => t.Key === 'elasticbeanstalk:environment-id'); | |
if (envIdTag === null) { | |
throw Error('Failed to find the value of "elasticbeanstalk:environment-id" tag.'); | |
} | |
// get ebs instances for env | |
// needs elasticbeanstalk:DescribeEnvironmentResources, autoscaling:DescribeAutoScalingGroups | |
const envData = await elasticbeanstalk.describeEnvironmentResources({ EnvironmentId: envIdTag.Value }).promise(); | |
console.log('envData', envData); | |
console.log('instances', envData.EnvironmentResources.Instances); | |
// see if we are first | |
return currentInstanceId === envData.EnvironmentResources.Instances[0].Id; | |
} catch(e) { | |
console.error(e); | |
return false; | |
} | |
} | |
// https://stackoverflow.com/questions/20904787/get-current-environment-name | |
function isCloud() { | |
try { | |
var contents = fs.readFileSync('/sys/hypervisor/uuid', 'utf8'); | |
return contents.substr(0,3) === 'ec2'; | |
} catch(e) { | |
// console.error(e); // expected to get: Error: ENOENT: no such file or directory, open '/sys/hypervisor/uuid' | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment