2

I'm trying to use the event bridge to reboot my degraded ec2 instance whenever the beanstalk changes to warn status, at the destination there is the option to call a lambda function or use the api reboot instance, my doubt is how to get the id of the instance only degraded (Taking into account that my environment has 2 instances).

GustavoNogueira
  • 389
  • 1
  • 3
  • 16

1 Answers1

1

when Elastic Beanstalk dispatches an event for a health status change, it looks like:

{ 
   "version":"0",
   "id":"1234a678-1b23-c123-12fd3f456e78",
   "detail-type":"Health status change",
   "source":"aws.elasticbeanstalk",
   "account":"111122223333",
   "time":"2020-11-03T00:34:48Z",
   "region":"us-east-1",
   "resources":[
      "arn:was:elasticbeanstalk:us-east-1:111122223333:environment/myApplication/myEnvironment"
   ],
   "detail":{
      "Status":"Environment health changed",
      "EventDate":1604363687870,
      "ApplicationName":"myApplication",
      "Message":"Environment health has transitioned from Pending to Ok. Initialization completed 1 second ago and took 2 minutes.",
      "EnvironmentName":"myEnvironment",
      "Severity":"INFO"
   }
}

in your AWS Lambda, you can use any AWS Elastic Beanstalk command, using the AWS SDK for your language of choice,

using the AWS JavaScript SDK for Elastic Beanstalk, you can restart your environment with restartAppServer:

 var params = {
  EnvironmentName: event.detail.EnvironmentName // based on the sample above
 };
 elasticbeanstalk.restartAppServer(params, function(err, data) {
   if (err) console.log(err, err.stack); // an error occurred
   else     console.log(data);           // successful response
 });

in the example above we would trigger a restart for all instances in the environment.

to target a specific instance, you can use describe-instances-health, renamed to describeInstancesHealth in the AWS JavaScript SDK:

var params = {
  AttributeNames: ["HealthStatus"],
  EnvironmentName: event.detail.EnvironmentName,
};
elasticbeanstalk.describeInstancesHealth(params, function(err, data) {
  if (err) console.log(err, err.stack); // an error occurred
  else     console.log(data);           // successful response
});

based on its response, you can filter the instance that isn't OK and trigger a restart using the instance id by calling the EC2 API rebootInstances:

 var params = {
  InstanceIds: [
     "i-1234567890abcdef5"
  ]
 };
 ec2.rebootInstances(params, function(err, data) {
   if (err) console.log(err, err.stack); // an error occurred
   else     console.log(data);           // successful response
 });
oieduardorabelo
  • 2,687
  • 18
  • 21
  • Thanks a lot for the answer, you gave me several points in the documentation that I had not yet found, I will try to implement and give feedback – GustavoNogueira Mar 30 '21 at 11:56