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.