I want to terminate and rebuild my test or non-critical AWS Elastic Beanstalk environment on a daily schedule. How can I do this?

You can stop and restart your Elastic Beanstalk environment with the API calls terminate-environment and rebuild-environment.

To perform these calls on a schedule, configure Amazon CloudWatch Events events to trigger AWS Lambda functions at a specific time each day, and configure those Lambda functions to make the Elastic Beanstalk API calls.

Important: Any out-of-band changes you make to an Elastic Beanstalk environment or its instances won't persist after the environment is terminated. Be sure to consider this factor when changing your environment. Also make sure to note the termination time and complete any work using the instance before that time. The instance terminates at the scheduled time regardless of whether someone is connected to it.

Before proceeding, make sure to note your Elastic Beanstalk environment's ID (EnvironmentId).

Create an IAM role for your Lambda function

1.    Create the following inline policy (for example, Lambda.json) for an AWS Identity and Access Management (IAM) role for your Lambda function:

$ cat Lambda.json 
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Service": [
          "lambda.amazonaws.com"
        ]
      },
      "Action": [
        "sts:AssumeRole"
      ]
    }
  ]
}

2.    Note the IAM role's Amazon Resource Name (ARN).

3.    Create the IAM role using the policy you created in the previous step as follows:

aws iam create-role --role-name elasticbeanstalk-lambda-role --assume-role-policy-document file://Lambda.json

4.    Attach the following managed policy to the IAM role:

aws iam attach-role-policy --policy-arn arn:aws:iam::aws:policy/AWSElasticBeanstalkFullAccess --role-name elasticbeanstalk-lambda-role

Create a Lambda function deployment package

1.    Open your preferred text editor and copy in the following code that restarts the Elastic Beanstalk environment.

Important: Make sure to replace e-iffbvbnzia with your Elastic Beanstalk environment's ID.

import boto3
envid=['e-iffbvbnzia']
client = boto3.client('elasticbeanstalk')
def handler(event, context):
    try:
         for appid in range(len(envid)):
             response = client.rebuild_environment(EnvironmentId=str(envid[appid].strip()))
             if response:
                 print('Restore environment %s' %str(envid[appid]))
             else:
                 print('Failed to Restore environment %s' %str(envid[appid]))

    except Exception as e:
        print('EnvironmentID is not valid')

Note: This code example is compliant with Python 3.6 runtimes.

2.    Save the code as a Python file (for example, StartElasticBeanstalk.py).

3.    Compress the Python file as a ZIP file (for example, StartElasticBeanstalk.zip).

4.    Open your preferred text editor and copy in the following code that terminates the Elastic Beanstalk environment.

Important: Make sure to replace e-iffbvbnzia with your Elastic Beanstalk environment's ID.

import boto3
envid=['e-iffbvbnzia']
client = boto3.client('elasticbeanstalk')
def handler(event, context):
    try:
         for appid in range(len(envid)):
             response = client.terminate_environment(EnvironmentId=str(envid[appid].strip()))
             if response:
                 print('Terminating environment %s' %str(envid[appid]))
             else:
                 print('Failed to Terminate environment %s' %str(envid[appid]))
             
    except Exception as e:
        print('EnvironmentID is not valid')

5.    Save the code as a Python file (for example, StopElasticBeanstalk.py).

6.    Compress the Python file as a ZIP file (for example, StopElasticBeanstalk.zip).

Create your Lambda function

In the AWS CLI, run the following commands to create Lambda functions that stop and restart your Elastic Beanstalk environment.

Important: Make sure to provide the deployment package (StartElasticBeanstalk.zip or StopElasticBeanstalk.zip) and IAM role's ARN as parameters in each command.

aws lambda create-function \
--function-name StartElasticBeanstalk \
--zip-file fileb://file-path/StartElasticBeanstalk.zip \
--role arn:aws:iam::012345678912:role/elasticbeanstalk-lambda-role \
--handler StartElasticBeanstalk.handler \
--runtime python3.6
aws lambda create-function \
--function-name StopElasticBeanstalk \
--zip-file fileb://file-path/StopElasticBeanstalk.zip \
--role arn:aws:iam::012345678912:role/elasticbeanstalk-lambda-role \
--handler StopElasticBeanstalk.handler \
--runtime python3.6

Create a CloudWatch Events rule to trigger the Lambda function

1.    Create rules to start and stop the Lambda function as follows:

aws events put-rule --name "StartLambdaFunction" --schedule-expression "cron(0 8 * * ? *)"
aws events put-rule --name "StopLambdaFunction" --schedule-expression "cron(0 18 * * ? *)"

2.    Run the following add-permission commands to trust the CloudWatch Events service principal (events.amazonaws.com) and scope permissions to the rules you just created.

Important: Make sure to replace the ARN in each command with the IAM role's ARN.

aws lambda add-permission \
--function-name StartElasticBeanstalk \
--statement-id StartLambdaFunction \
--action 'lambda:InvokeFunction' \
--principal events.amazonaws.com \
--source-arn arn:aws:events:us-west-2:012345678912:rule/StartLambdaFunction
aws lambda add-permission \
--function-name StopElasticBeanstalk \
--statement-id StopLambdaFunction \
--action 'lambda:InvokeFunction' \
--principal events.amazonaws.com \
--source-arn arn:aws:events:us-west-2:012345678912:rule/StopLambdaFunction

Using CloudFormation templates

You can also create a CloudFormation template to perform all these actions. You can configure the template to create the Lambda IAM Execution role, start the Lambda function, stop the Lambda function, and then trigger the CloudWatch event. For more information about creating a template that uses a Lambda function, see AWS Lambda Template. For more information about using Elastic Beanstalk resources in your template, see Elastic Beanstalk Template Snippets.


Did this page help you? Yes | No

Back to the AWS Support Knowledge Center

Need help? Visit the AWS Support Center

Published: 2018-09-28