Reading an Environment Variable set at CodePipeline from a CodeBuild buildspec.yml

30 Views Asked by At

I've setup an AWS CodePipeline named test-pipeline-flow.

The Source step has being set to use an AWS CodeCommit named test-repo.

The Build step has being set to use an AWS CodeBuild named test-build-repo. This CodeBuild has the following buildspec.yml:

version: 0.2
phases:
  build:
    commands:
       - echo $FOO
       - echo $BAR

At the CodeBuild test-build-repo I've also set the Environment Variables through the Environment > Additional configuration sub-section:

Additional configuration

So the issue here is that when I trigger the AWS CodePipeline test-pipeline-flow

The CloudWatch logs show that $FOO holds whatever (as expected) and the $BAR actually holds #{codepipeline.PipelineExecutionId} instead of the actual Execution ID

What else am I missing that not allowing $BAR to resolve to the correct value provided by AWS CodePipeline?

1

There are 1 best solutions below

0
deric4 On

Based off your screen shot, it looks like you're tryings to use the CodePipeline variable syntax on the CodeBuild configuration page. If so, you need to set the environment variables within CodePipeline page/console.

This page has a detailed description of how the variables are scoped within a pipeline and its actions: https://docs.aws.amazon.com/codepipeline/latest/userguide/reference-variables.html

when you run the following command from cloud-shell or from your local machine you should see something like this:

notice we are looking at the pipeline, not the codebuild project

# ref https://docs.aws.amazon.com/codepipeline/latest/userguide/actions-variables.html

aws codepipeline get-pipeline --name <pipeline-name>

{
    "name": "Build",
    "actions": [
        {
            "outputArtifacts": [
                {
                    "name": "BuildArtifact"
                }
            ],
            "name": "Build",
            "configuration": {
                "EnvironmentVariables": "[{\"name\":\"Execution_ID\",\"value\":\"#{codepipeline.PipelineExecutionId}\",\"type\":\"PLAINTEXT\"},{\"name\":\"Commit_ID\",\"value\":\"#{SourceVariables.CommitId}\",\"type\":\"PLAINTEXT\"}]",
                "ProjectName": "env-var-test"
            },
            "inputArtifacts": [
                {
                    "name": "SourceArtifact"
                }
            ],
            "region": "us-west-2",
            "actionTypeId": {
                "provider": "CodeBuild",
                "category": "Build",
                "version": "1",
                "owner": "AWS"
            },
            "runOrder": 1
        }
    ]
},