Matthew Allen
Matthew Allen

Reputation: 585

AWS CodeBuild buildspec - are changes to variables in phases section available in artifacts section?

I define some variables in the env/variables, then make changes to the value in phases/pre_build. I want to use the variable down in artifacts, but it looks like the changes are not persisted.

This is a legacy Windows .NET Framework 4.7.2 application getting deployed to IIS.

My buildspec.yml file:

version: 0.2

env:
  variables:
    APPNAME: DummyApp
    BRANCH: manual
  
phases:
  pre_build:
    commands:
      - echo "start BRANCH = ${BRANCH}"
      - echo "CODEBUILD_WEBHOOK_HEAD_REF = ${env:CODEBUILD_WEBHOOK_HEAD_REF}"
      # CODEBUILD_WEBHOOK_HEAD_REF is null when build is triggered from console as opposed to a webhook
      - if (${CODEBUILD_WEBHOOK_HEAD_REF}) { ${BRANCH} = ($CODEBUILD_WEBHOOK_HEAD_REF.replace('refs/heads/', '')) }
      - echo "after BRANCH = ${env:BRANCH}"

  build:
    commands:
      - echo "build commands happen here"

artifacts:
  files:
    - .\Dummy\bin\Debug\*
  # not sure why this doesnt work down here, are changes in the phases section above not propagated?
  name: ${env:APPNAME}/${env:APPNAME}-${env:BRANCH}.zip
  discard-paths: yes

The value of $CODEBUILD_WEBHOOK_HEAD_REF = "refs/head/develop".
The value of $BRANCH after the replace statement = "develop".
The value of my artifact in S3 is "DummyApp/DummyApp-manual.zip".

I want the artifact named "DummyApp/DummyApp-develop.zip".

Some sort of scoping issue?

Upvotes: 0

Views: 2042

Answers (1)

Matthew Allen
Matthew Allen

Reputation: 585

Saw various indications that this is not possible.

https://blog.shikisoft.com/define-environment-vars-aws-codebuild-buildspec/

The crucial thing you should note here is that you can only assign literal values to the environment variables declared this way. You cannot assign dynamic values at runtime. If you would like to change the value of the <...> variable above, you have to change your buildspec file and push your changes to your repository again. So it is like hardcoding parameter values. But it is better than typing the in all commands needed in the phases section.

In addition to trying to simply set the local var in pre_build, I tried a number of approaches, including

  • running a custom powershell script to parse the Branch name as the first step in the pre_build
  • running the command in the variable declaration itself
  • calling the prsh SetEnvironmentVariable method

The thing that seems to work is using the replace command down in the artifact/name itself:

artifacts:
  files:
    - .\Dummy\bin\Debug\*
  name: ${env:APPNAME}/${env:APPNAME}-$($CODEBUILD_WEBHOOK_HEAD_REF.replace('refs/heads/', '')).zip
  discard-paths: yes

created this artifact: DummyApp\DummyApp-develop.zip

Upvotes: 0

Related Questions