Customize Elastic Beanstalk Environment

Occasionally, you will need to customize environment for applications running in Elastic Beanstalk. Some of the use cases can be:
  • Download properties/configuration files, used by application, from S3
  • Run customized scripts which make use of environment variables
  • Create or modify files/directories
One of the approach, to customize environment, is to use Elastic Beanstalk configuration files. These configuration files are part of source code and are usually placed at root of source code in folder .ebextensions.  Lets consider a use case where web application reads properties from a file. And file needs to be downloaded from S3.
Create folder .ebextensions at root of source code.  Create file 'downloadPropertiesFile.config' in folder .ebextensions with following content in yaml format:
        command: sudo /usr/bin/aws s3 --region eu-west-1 cp s3://${Bucket_Path_To_File_In_S3} /destination_file_path
If using gradle, add following content in build.gralde to make this .ebextensions part of war file.
war {
    from('.ebextensions') {
Add Environment Variable Bucket_Path_To_File_In_S3 to Elastic Beanstalk environment.
Deploy war file to elastic beanstalk environment and file from S3 should be downloaded. Make sure that ec2-instace has associated Role (Instance Profile) which has access to S3 bucket.
It is recommended to use Roles/Instance Profiles to access AWS resources from ec2-instance. However, if you cannot assign role to ec2-instance then you can download files using environment variables. Change content of 'downloadPropertiesFile.config' to:
        command: export AWS_ACCESS_KEY_ID=${AWS_ACCESS_KEY_ID}
        command: sudo /usr/bin/aws s3 --region eu-west-1 cp s3://${Bucket_Path_To_File_In_S3} /destination_file_path
And add following environment variables to Elastic Beanstalk application. These environment variables are not available in shell and this is why we have to export them first in order to download file from S3.

This example also demonstrates on how to access environment variables in .ebextensions files. Elastic beanstalk executes container commands after extracting source code, but before deploying it. It is important to note that Environment Variables are available for container commands but they are not available for other .ebextensions keys such as Files and Commands.
For Further Reading: Container Commands


Popular posts from this blog

Practice Questions - AWS Solutions Architect - Associate Certification

AWS: Increase Connection Timeout

AWS Parameter Store