AWS CodePipeline: How to make ECR Image build by CodeBuild as an artifact for the remaining stages?

2.1k Views Asked by At

My CodePipeline currently has a Github Source and a CodeBuild that builds an image and pushes it to ECR:

+---------------+      +-----------+     +-----+
| GitHub Source +----->+ CodeBuild +---->+ ECR |
+---------------+      +-----------+     +-----+

I want to add a CodeDeploy step to the pipeline which will take the image pushed to ECR and deploy it on ECS. But my CodeBuild step does not produce any artifacts (It uploads to ECS, and I don't know how to define a ECR image as an artifact). So I am not able to connect the CodeDeploy to the pipeline. Any idea how to do this?

+---------------+      +-----------+     +-----+      +------------+     +-----+
| GitHub Source +----->+ CodeBuild +---->+ ECR +----->+ CodeDeploy +---->+ ECS |
+---------------+      +-----------+     +-----+      +------------+     +-----+

The only solution I can think of is to make a second pipeline that will take ECR as a source, and do the deployment.

     Pipeline 1
+---------------+      +-----------+     +-----+
| GitHub Source +----->+ CodeBuild +---->+ ECR |
+---------------+      +-----------+     +-----+

 Pipeline 2
+-----+      +------------+     +-----+
| ECR +----->+ CodeDeploy +---->+ ECS |
+-----+      +------------+     +-----+
2

There are 2 best solutions below

0
On BEST ANSWER

You should define an artefact which will be a json file named imagedefinitions.json for ECS Standard deployment actions or imageDetail.json for Amazon ECS Blue/Green deployment actions. It is explained in the reference here.

In my case, since I was doing a standard deployment, I added to the buildspec.yml at the end of the build, two extra commands:

  phases: 
    build: 
      commands: 

        ...Build and push to ECR...

        echo Generating imagedefinitions.json
        echo '[{"name":"<CONTAINER-NAME>","imageUri":"'<IMAGE-URI>"}]' > imagedefinitions.json
  artifacts:
    files:
      - imagedefinitions.json

and then added the file as a artifact.

0
On

Not sure how you are versioning your ECR images, but you could version them with the git hash which is obtainable within code build as environment variable $CODEBUILD_RESOLVED_SOURCE_VERSION (note: the input artifact needs to be Source for this env variable to be available).

Then in your CodeDeploy step, also use the input artifact as source, then specify the $CODEBUILD_RESOLVED_SOURCE_VERSION as the image tag you want CodeDeploy to deploy.

An added bonus, using the git hash as the container version allows you to reference the git pull request from the image tag which is nice for visibility.