As part of our deployment process, we include the short git SHA as a build number against our SemVer version number.
We wanted this available in our application UI to help identify running versions. Easy I thought, Beanstalk sets this as the
Version Label when deploying, so we should be able to access that from the environment vars in PHP.
Unfortunately not, this is one of the many EB values you cant easily get to. After a lot of failed attempts, here is how we managed it as a one-liner in the
To cut to the chase, add this to a config file in
myApp_env_vars.conf to something more appropriate for your application).
commands: 01_enable_rootaccess: command: echo Defaults:root \!requiretty >> /etc/sudoers</code> container_commands: 01_export_build_number_to_apache: command: echo "SetEnv BUILD_NUMBER \"$(unzip -z /opt/elasticbeanstalk/deploy/appsource/source_bundle | tail -n 1 | cut -c1-7)\"" | sudo tee /etc/httpd/conf.d/myApp_env_vars.conf > /dev/null 02_export_build_number_to_ec2: command: echo "export BUILD_NUMBER=\"$(unzip -z /opt/elasticbeanstalk/deploy/appsource/source_bundle | tail -n 1 | cut -c1-7)\"" | sudo tee -a /opt/elasticbeanstalk/support/envvars > /dev/null
What this does is...
- 01_enable_rootaccess - allows .ebextension commands to run as sudo
- 01_export_build_number_to_apache - exports the build number to Apache / php.
- 02_export_build_number_to_ec2 - exports the build number to the EC2 box (optional). This isn't exposed to Apache / php, but useful if you use other post deploy scripts.
We get the git SHA by looking at the comments in the
source_bundle zip that EB creates and copies to the Ec2 box. One of the comments in the ZIP has the SHA, so the command breaks down as follows...
#Get the comment with the -z param unzip -z /opt/elasticbeanstalk/deploy/appsource/ # Pipe it into the tail app taking the last line (the comment value) | tail -n 1 # Pipe that and cut the first 7 chars from it | cut -c1-7 # Using that value, construct the string to set the Env var in apache SetEnv BUILD_NUMBER=\"$( ABOVE COMMANDS )\"" # Pipe that string into an apache config file so its loaded when apache starts.. sudo tee /etc/httpd/conf.d/myApp_env_vars.conf > /dev/null
You could uses similar approaches for setting other env vars at deploy time. However, if you have static values, then just use the
option_settings entry in the