9

I have a buildspec.yml file in my CodeBuild that I want to read values out of EC2 Systems Manager Parameter Store. CodeBuild supports doing this via the parameter-store attribute in your spec file.

Problem is, I can't figure out how to use enviornment Variables that are set BEFORE the buidlspec executes.

Here is an example:

version: 0.2
env:
  variables:    
    RUNTIME: "nodejs8.10"
  #parameter-store vars are in the format /[stage]/[repo]/[branch]/[eyecatcher]/key
  parameter-store: #see https://docs.aws.amazon.com/codebuild/latest/userguide/build-spec-ref.html#build-spec-ref-syntax
    LAMBDA_EXECUTION_ROLE_ARN: "/${STAGE}/deep-link/${BRANCH}/GetUri/lambdaExecutionRoleArn"
    ENV_SAMPLE_KEY: "/${STAGE}/deep-link/${BRANCH}/GetUri/key1"

phases:
  install:
    commands:  
      ...

As you can see I'm doing the AWS best practice for name-spacing the EC2 Systems Manager Parameter Store keys. I want to re-use this build spec for all my stages, so hard coding is not an option. The vars I use in the Value string are populated as EnvironmentVariables in my CodeBuild project - so they are available before the spec runs.

How do I dynamically populate the Value of the parameter-store Keys with something that is not hard coded?

rynop
  • 50,086
  • 26
  • 101
  • 112

3 Answers3

13

This variable expansion is now supported in CodeBuild for parameter-store use case. You can define any environment variable in your buildspec and have that referenced in the path to fetch the parameter store. For example, if you have an environment variable called $stage you could use it like this:

version: 0.2
env:
  variables:
    stage: PRE_PROD
  parameter-store:
    encryptedVar: CodeBuild-$stage
phases:
  build:
    commands:
      - echo $encryptedVar
d512
  • 32,267
  • 28
  • 81
  • 107
Subin Mathew
  • 2,335
  • 1
  • 16
  • 24
  • Thanks. Link or better yet example? – rynop Feb 17 '20 at 01:19
  • 1
    The accepted answer (https://stackoverflow.com/a/50452118/3925926) isn't valid anymore. I can confirm that the variable expansion works for parameter store variables. One can use even the environment variables passed to CodeBuild (e.g. via CloudFormation templates for instance) – Roba Sep 12 '20 at 18:05
6

I found this StackOverflow post - unfortunately the feature you describe does not seem to exist.
It would have been nice to be able to use parameters and functions akin to the features in CloudFormation templates.

Jonatan
  • 720
  • 7
  • 12
0

https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/dynamic-references.html

It doesnt say it explicitly but I'm guessing you can use a !Sub in whatever cloudformation template you are using to build that resolve string, and use it in a ParameterOverride to pass into your buildspec in the regular parameter block instead of a parameter-store block

user356900
  • 13
  • 1
  • 4