Skip to content

Use ECR image built in the previous stage?

0

I'm using CodePipeline, and I have the following stages:

  1. Source - fetch source from GitHub
  2. Build - builds a Docker image and publishes it to ECR.
  3. Test - runs tests

Is it possible to use the image from step (2) in step (3) as the environment in which the commands run?

In other words, I am not talking about doing docker run $image_name.

I'm talking about setting is as the env.image value of the BuildSpec, so that the entire environment of the running tasks is the image from step 2.

I am pretty sure I got a PoC working using matrix build earlier this week. I swear it worked! I am trying today, and cannot get it to work anymore. :(

Also, what I cannot do is use "latest" or any other stable image tag, as there can be parallel builds in rapid succession, then we don't know for sure which build the code will run in.

I'm tagging the images with the value of CODEBUILD_RESOLVED_SOURCE_VERSION which is a git commit sha.

2 Answers
0

From a test I could perform, it was possible to use the Docker image built in the Build stage (step 2) as the environment for the Test stage (step 3) in AWS CodePipeline.

I had to dynamically setting the env.image value in my BuildSpec file.

I suggest you try the following to achieve the same:

  • Tag the Docker Image with a unique identifier, such as the CODEBUILD_RESOLVED_SOURCE_VERSION (the Git commit SHA).
  • Pass the Image URI via CodePipeline environment variables or parameter store
  • In the Test stage, set the env.image value in the BuildSpec file to the Docker image URI passed from the Build stage.

This can help you achieve the cascading variable pass.

EXPERT

answered 2 years ago

EXPERT

reviewed 2 years ago

  • Thanks, @Giovanni Lauria, It sounds encouraging! I find only one part confusing:

    Pass the Image URI via CodePipeline environment variables

    Could you please clarify that?

    Thank you!

  • Got the same result when using env.image in the matrix build (which is supported): "BATCH_START_BUILD_ERROR: Failed calling StartBuild for a batch.. Failed while calling StartBuild with exception message: Invalid characters found in the image name."

            "env": {
              "image": "#{BuildAction.DOCKER_IMAGE_TAG_NODE}"
            },
    

    Where the value of DOCKER_IMAGE_TAG_NODE is the full ECR:tag combo.

  • Also, were you testing with the batch builds or non-batch?

    Because with non batch, I tried to add env.image and CodeBuild logs that it's an invalid prop.

    Found possible syntax errors in buildspec: 
    In the section env
        The following keys cannot be identified:
            image
    

    But if I set it at the project level to #{BuildAction.DOCKER_IMAGE_TAG_NODE} then deployment fails, because it's an invalid image name ("Only alphanumeric characters, hyphens, underscores, colons, periods, forward slashes, the at symbols and number signs are supported").

0

The existing answer misses an important distinction: passing an image URI as a CodeBuild environment variable does not change the image used to create that build environment.

For a normal (non-batch) buildspec, top-level env supports variables, Parameter Store, Secrets Manager, shell, exported variables, and the Git credential helper; it does not support env.image. An image property exists only inside individual tasks in the batch build syntax. That explains the validation error in your comment.

Also, #{BuildAction.DOCKER_IMAGE_TAG_NODE} is CodePipeline variable syntax. CodePipeline resolves such references in a downstream action configuration before starting that action. It does not rewrite a buildspec.yml file from the source artifact, so a token placed in batch.*.env.image is passed as a literal image name and fails image-name validation.

The standard CodePipeline CodeBuild action exposes ProjectName, EnvironmentVariables, batch settings, and buildspec override, but it has no per-execution image override. The supported per-build mechanism is the CodeBuild StartBuild API's imageOverride field (CLI: --image-override).

A race-safe design is therefore:

  1. Build and push the image with an immutable tag, or preferably record its digest-qualified URI.
  2. Export that exact URI from the Build action, for example as IMAGE_URI.
  3. Have a downstream orchestration action call StartBuild for the Test project with that URI as ImageOverride.
  4. Wait for that specific build to finish and propagate its result back to the pipeline.

For example, the Build action can export the value:

version: 0.2
env:
  exported-variables:
    - IMAGE_URI
phases:
  post_build:
    commands:
      # Set IMAGE_DIGEST after pushing and verifying the image in ECR.
      - 'IMAGE_URI="$REPOSITORY_URI@$IMAGE_DIGEST"'

Give the Build action a namespace such as BuildVariables. A low-code way to run the Test build is a Standard Step Functions state machine invoked from CodePipeline. The Step Functions action input is an action configuration field, so CodePipeline resolves the variable there:

Configuration:
  StateMachineArn: arn:aws:states:REGION:ACCOUNT:stateMachine:test-built-image
  InputType: Literal
  Input: '{"ImageUri":"#{BuildVariables.IMAGE_URI}"}'

The state machine can use CodeBuild's synchronous integration:

{
  "StartAt": "TestInBuiltImage",
  "States": {
    "TestInBuiltImage": {
      "Type": "Task",
      "Resource": "arn:aws:states:::codebuild:startBuild.sync",
      "Arguments": {
        "ProjectName": "test-project",
        "ImageOverride.$": "$.ImageUri"
      },
      "End": true
    }
  }
}

A Standard Step Functions action waits for the state machine to reach a terminal status, and codebuild:startBuild.sync waits for the Test build, so a failed test fails the pipeline action.

If the built image already contains the code and tests, make test-project a NO_SOURCE CodeBuild project and store an inline buildspec in the project definition. If the tests still come from source, configure a source that can be used by a direct StartBuild call and pass the same commit/version; a project whose source is only the CodePipeline artifact cannot receive that artifact through this separate API call automatically.

Do not solve this by calling UpdateProject to replace the Test project's image immediately before its normal pipeline action. That mutates shared project state, so concurrent pipeline executions can select each other's images—the race you are trying to avoid. imageOverride belongs to one build request and leaves the project unchanged.

Finally, scope the Step Functions execution role to starting and observing the Test project, and configure the Test project's image-pull credentials and ECR permissions for that repository. A digest URI, or a commit tag in an ECR repository with tag immutability enabled, ensures that each pipeline execution tests exactly the image it built.

AWS references:

answered 3 months ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.