Search code examples
amazon-web-servicesdeploymentbitbucketaws-cloudformation

Passing Bitbucket Pipelines Variables to Cloudformation


I'm unable to pass Bitbucket repository variables to my AWS Cloudformation template. I need to pass $BITBUCKET_BUILD_NUMBER. I can echo it to the Bitbucket pipeline, but the variable is never substituted in Cloudformation Parameters.

bitbucket-pipelines.yml:

pipelines:
  branches:
    master: 
      - step:
          name: Deploy (Dev)
          deployment: dev
          script:
            - export PARAMETERS=$(cat ./parameters.json)
            - echo "BITBUCKET_BUILD_NUMBER is $BITBUCKET_BUILD_NUMBER"
            - pipe: atlassian/aws-cloudformation-deploy:0.18.0
              variables:
                STACK_NAME: 'dev-be-uservice'
                TEMPLATE: 'cloudformation.yml'
                STACK_PARAMETERS: $PARAMETERS

parameters.json:

[
  {
    "ParameterKey": "BuildTag",
    "ParameterValue": "$BITBUCKET_BUILD_NUMBER"
  }
]

cloudformation.yml:

Parameters:
  BuildTag:
    Description: The Docker Tag
    Type: String

In parameters.json I've tried "$BITBUCKET_BUILD_NUMBER", "${BITBUCKET_BUILD_NUMBER}", etc.

Cloudformation always shows BuildTag as the unsubstituted string ($BITBUCKET_BUILD_NUMBER) rather than the build number (2).


Solution

  • You need to evaluate the environment variable in the file before the deployment. To do this, you can use envsubst:

    pipelines:
      branches:
        master: 
          - step:
              name: Deploy (Dev)
              deployment: dev
              script:
                - apt-get -y update && apt-get -y install gettext-base
                - export PARAMETERS=$(envsubst < ./parameters.json)
                - echo "BITBUCKET_BUILD_NUMBER is $BITBUCKET_BUILD_NUMBER"
                - pipe: atlassian/aws-cloudformation-deploy:0.18.0
                  variables:
                    STACK_NAME: 'dev-be-uservice'
                    TEMPLATE: 'cloudformation.yml'
                    STACK_PARAMETERS: $PARAMETERS
    

    e.g.:

    $ cat file
    [
      {
        "ParameterKey": "BuildTag",
        "ParameterValue": "$BITBUCKET_BUILD_NUMBER"
      }
    ]
    $ export BITBUCKET_BUILD_NUMBER=1.0.0
    $ export PARAMETERS=$(envsubst < file)
    $ echo "$PARAMETERS"
    [
      {
        "ParameterKey": "BuildTag",
        "ParameterValue": "1.0.0"
      }
    ]