How do I manually run scripts that require access to environment variables on my Elastic Beanstalk instance on Amazon Linux 2?

Last updated: 2020-08-20

I want to manually run scripts that require access to environment variables on my AWS Elastic Beanstalk instance on Amazon Linux 2.

Short description

You can use platform hooks to manually run scripts, which require access to environment variables on your Elastic Beanstalk instance, on Amazon Linux 2 platforms. To configure and run custom code on your environment instances during instance provisioning, it's a best practice to use platform hooks instead of providing files and commands in .ebextension configuration files.

Note: The following resolution includes a script that you can use across several platforms, including PHP, Python, Ruby, Amazon Corretto, Tomcat, and Node.js. The script allows users to source the environment variables defined in the /opt/elasticbeanstalk/deployment/env file.


1.    In your application source bundle, create a file called 01_set_env.conf in the .platform/hooks/postdeploy directory. For example:

├── .platform
│   ├── hooks
│   │   ├── postdeploy
│   │   │   ├──
|-- helloworld

2.    Create a Bash script that copies the /opt/elasticbeanstalk/deployment/env file and sets 644 permissions so that any user on the instance can access the file. For example:


#Create a copy of the environment variable file
cp /opt/elasticbeanstalk/deployment/env /opt/elasticbeanstalk/deployment/custom_env_var

#Set permissions to the custom_env_var file so this file can be accessed by any user on the instance. You can restrict permissions as per your requirements.
chmod 644 /opt/elasticbeanstalk/deployment/custom_env_var

#Remove duplicate files upon deployment
rm -f /opt/elasticbeanstalk/deployment/*.bak

Important: Set the permissions chmod +x for the .platform/hooks/postdeploy/ file.

3.    Deploy the .platform hook file.

4.    To avoid manually sourcing the file, add the following code to your user's ~/.bash_profile:

source <(sed -E -n 's/[^#]+/export &/ p' /opt/elasticbeanstalk/deployment/custom_env_var)

Note: On Amazon Linux 2, all environment variables are centralized into a single file called /opt/elasticbeanstalk/deployment/env. You must use this file during Elastic Beanstalk's application deployment process only. The variables defined in /opt/elasticbeanstalk/deployment/env aren't available at the operating system level, which causes "permission denied" issues if you access these variables through manual scripts run on the instance. The /opt/elasticbeanstalk/deployment/env file has restricted permissions, and can be difficult for non-root users (for example, ec2-user) to source. For example:

[root@ip-X-X-X-X deployment]# ls -latr /opt/elasticbeanstalk/deployment/env

-r-------- 1 root root 147 Jun 17 06:23 /opt/elasticbeanstalk/deployment/env

Did this article help?

Do you need billing or technical support?