CodePipeline with CodeBuild error for cross-account ECR login & push for built Docker image

Question:

Hey cloud gurus 🙂 I need your help!

I’m trying since quite a while to set up an AWS CodePipeline from source to
build to ECR to ECS for a Docker container where the pipeline is in another
account from where it is deployed. Actually, I have multiple deployment
accounts: Dev, Test and Prod, however, now I just aim to get it deployed into
Dev.

(Also, in my setup I also have ECR repos in all three deployment accounts –
is this the recommended approach compared to maybe one ECR repo in probably the
same account as the pipeline?)

All is using CloudFormation templates, both the AWS infra as well as the pipeline.

Problem

I’m currently stuck with a permission issue for CodeBuild pushing to an ECR repo
in another account as CodeBuild and its service role.

Overview

The Pipeline account has a pipeline with two stages: source and build taking the
code from CodeCommit and then CodeBuild to build the container. The first stage
works but not the second where the buildspec.yml fails logging into the ECR
repo that I have like so:

This fails with the clear and expected error:

The CodeBuild project service role does not have permissions to cross-account
access ECR. I know that but not yet how to approach solving it.

AFAIK, CodePipeline requires a service role in the same account. The build project
service role must also be in the same account and provides permissions
to e.g. CodeBuild, artifacts store and KMS.

I tried to give the CodeBuild project a role in the Dev account but got an error:

In summary, the pipeline needs the role in the pipeline account, same for the
CodeBuild project. That all makes sense as those run there and also need access to
artifacts S3 bucket and related KMS.

So, how and where to provide the role/permissions to log in to ECR as well as later
to push into a specific repo so that the docker commands can be in the buildspec.yml
file?

I’m planning to use CodeDeploy ECS to deploy once I have the build stage working.

Is the overall approach recommended for cross-account deployments and/or are
there other approaches you use?

Most examples online are much simpler with a single account
with this related issue
or just general cross-account without ECR (which I have working).

Thanks in advance for your help on this one!

Answer:

You can create a user in the other account which holds ECR repo and give its Access Key and Secret Key as Environment Variables to your CodeBuild Project.

Leave a Reply