How to get Git SHA in an Elastic Beanstalk App (and set other dynamic env vars at deployment)

Posted by Matt Bryson on 18-May-2015 08:57:28
Find me on:

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 .ebextensions

To cut to the chase, add this to a config file in .ebextensions, eg projectRoot/.ebextensions/env_vars.config (change myApp_env_vars.conf to something more appropriate for your application).

command: echo Defaults:root \!requiretty >> /etc/sudoers</code>

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

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...

  1. 01_enable_rootaccess - allows .ebextension commands to run as sudo
  2. 01_export_build_number_to_apache - exports the build number to Apache / php.
  3. 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
# 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 .ebextensions file.


Topics: PHP, EC2, AWS, Deployment, EB (Elastic Beanstalk), Apache

About the author

Matt Bryson is an experienced systems engineer with over 15 years Development and Systems Operations experience.

Product Briefing

In this short product briefing, see how iDetailAid customers are simplifying the creation, update, localisation and upload of CLM content.

New Call-to-action

Subscribe to Email Updates

Recent Posts