Last active
October 11, 2023 02:59
-
-
Save tony-gutierrez/de5b304fd042f6140eb61a31d0ff92d5 to your computer and use it in GitHub Desktop.
AWS Elastic Beanstalk master instance nodejs cron.
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 logger = require('./logger'), | |
AWS = require('aws-sdk'), | |
CronJob = require('cron').CronJob; | |
AWS.config.update({region: 'us-east-1'}); // change to your region | |
var opts = { | |
credentials: new AWS.EC2MetadataCredentials()// default to use the credentials for the ec2 instance | |
}; | |
var elasticbeanstalk = new AWS.ElasticBeanstalk(opts); | |
var ec2 = new AWS.EC2(opts); | |
var metadata = new AWS.MetadataService(opts); | |
function runTaskOnMaster(name, taskToRun) { | |
logger.info('Beginning task: ' + name); | |
return new Promise( (resolve, reject) => { | |
metadata.request('/latest/meta-data/instance-id', (err, InstanceId) => { | |
if (err) {return reject(err);} | |
return resolve(InstanceId) | |
}); | |
}) | |
.then((currentInstanceId) => { | |
console.log('InstanceId', currentInstanceId); | |
return new Promise( (resolve, reject) => { | |
var params = { | |
Filters: [ | |
{ | |
Name: 'resource-id', | |
Values: [currentInstanceId] | |
} | |
] | |
}; | |
ec2.describeTags(params, (err, data) => { | |
if (err) {return reject('dt' + err);} | |
var envIdTag = data.Tags.find(t => t.Key === 'elasticbeanstalk:environment-id'); | |
if (envIdTag === null) { | |
return reject('Failed to find the value of "elasticbeanstalk:environment-id" tag.'); | |
} | |
elasticbeanstalk.describeEnvironmentResources({EnvironmentId: envIdTag.Value}, function (err, data) { | |
if (err) { return reject('de' + err); } | |
if (currentInstanceId !== data.EnvironmentResources.Instances[0].Id) { return resolve(false); } | |
return resolve(true); | |
}); | |
}); | |
}); | |
}) | |
.then( (isMaster) => { | |
if (!isMaster) { | |
logger.warn('Not running task as not master EB instance.'); | |
} else { | |
logger.info('Identified as master EB instance. Running task.'); | |
taskToRun(); | |
} | |
}) | |
.catch( (err) => logger.error(err)); | |
} | |
logger.info('*** Starting Cron Jobs! ***'); | |
new CronJob('0 */5 * * * *', function() { //every 5 min | |
runTaskOnMaster( 'Task 1', () => { | |
//do cron work here. | |
}); | |
}, null, true); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
an async/await version based on this snippet
https://gist.github.com/ayavilevich/9cea31154a71d079cb5328006a72bd53