SHARE
TWEET

Untitled

a guest Jul 21st, 2019 60 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const logger = require('./logger'),
  2. AWS = require('aws-sdk'),
  3. CronJob = require('cron').CronJob;
  4.  
  5. AWS.config.update({region: 'us-east-1'}); // change to your region
  6. var opts = {  
  7.   credentials: new AWS.EC2MetadataCredentials()// default to use the credentials for the ec2 instance
  8. };
  9.  
  10. var elasticbeanstalk = new AWS.ElasticBeanstalk(opts);
  11. var ec2 = new AWS.EC2(opts);
  12. var metadata = new AWS.MetadataService(opts);
  13.  
  14. function runTaskOnMaster(name, taskToRun) {
  15.   logger.info('Beginning task: ' + name);
  16.  
  17.   return new Promise( (resolve, reject) => {
  18.     metadata.request('/latest/meta-data/instance-id', (err, InstanceId) => {
  19.       if (err) {return reject(err);}
  20.       return resolve(InstanceId)
  21.     });
  22.   })
  23.   .then((currentInstanceId) => {
  24.     console.log('InstanceId', currentInstanceId);
  25.     return new Promise( (resolve, reject) => {    
  26.       var params = {
  27.         Filters: [
  28.           {
  29.             Name: 'resource-id',
  30.             Values: [currentInstanceId]
  31.           }
  32.         ]
  33.       };
  34.  
  35.       ec2.describeTags(params, (err, data) => {
  36.         if (err) {return reject('dt' + err);}
  37.  
  38.         var envIdTag = data.Tags.find(t => t.Key === 'elasticbeanstalk:environment-id');
  39.         if (envIdTag === null) {
  40.           return reject('Failed to find the value of "elasticbeanstalk:environment-id" tag.');
  41.         }
  42.  
  43.         elasticbeanstalk.describeEnvironmentResources({EnvironmentId: envIdTag.Value}, function (err, data) {
  44.           if (err) { return reject('de' + err); }
  45.           if (currentInstanceId !== data.EnvironmentResources.Instances[0].Id) { return resolve(false); }
  46.           return resolve(true);
  47.         });
  48.       });
  49.     });
  50.   })
  51.   .then( (isMaster) => {
  52.     if (!isMaster) {
  53.       logger.warn('Not running task as not master EB instance.');
  54.     } else {
  55.       logger.info('Identified as master EB instance. Running task.');
  56.       taskToRun();
  57.     }
  58.   })
  59.   .catch( (err) => logger.error(err));
  60. }
  61.  
  62. logger.info('*** Starting Cron Jobs! ***');
  63.  
  64.  
  65. new CronJob('0 */5 * * * *', function() { //every 5 min
  66.   runTaskOnMaster( 'Task 1', () => {
  67.     //do cron work here.
  68.   });
  69. }, null, true);
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top