As it took me a few attempts to get it to work, I thought it would be useful to capture how to use environment variables in the buildspec.yml file for anyone else using AWS CodeBuild to hopefully save you a few minutes of hacking around.

To reference an environment variable, simply prefix the variable name with $ in your list of commands. So for example:

And that is it. Pretty simple when you know how.

It would also appear that you cannot use environment variables with dots in the name. For example I was trying to use ‘rba.build.version’ as a environment property, but it continuously failed with bad substitution errors.¬†Reading around I don’t think this is CodeBuild specific, more me not using Ubuntu properly (I am using the default CodeBuild JDK 8 Docker container for my builds which is Ubuntu-based).

As an added bonus if you want to see what environment variables are available to you to play around with, you can add a ‘printenv‘ command into the install phase of the build which will print the entire environment to your CloudWatch logs. Something like this:

You can then use any of the environment variables to influence the outcome of your builds.

Founder and principal consultant of Rob Blake Associates. Over 5 years hands-on experience building and deploying production web applications on AWS. 10 years professional experience as a Java developer. Previously technical co-founder of The Law Wizard which was sold in June 2014.

10 thoughts on “Using environment variables in AWS CodeBuild buildspec.yml”

  1. Do you know if there is an escape character needed when the variable is in the middle of a string?

    For example I’d like to do something like this in the parameter store section.

    parameter-store
    KEY1: “some_value_$STAGE”
    KEY2: “some_other_$STAGE”

  2. THANK YOU CHRIS!

    I have been googling for an hour trying to figure out why my environment variables didn’t resolve on our Windows build.

Leave a Reply

Your email address will not be published. Required fields are marked *