Creating a repository for the custom CodeBuild container

Now, that you have built a custom CodeBuild image, you need to publish the image to a location that CodeBuild can pull the image from. If you are using the ECR, you will typically publish this image to a repository within ECR, and that is the approach we will take.

First, you need to add a new repository to the ecr.yml file, in the root of the todobackend-aws folder, which you created earlier in the chapter::

AWSTemplateFormatVersion: "2010-09-09"

Description: ECR Resources

Resources:
CodebuildRepository:
Type: AWS::ECR::Repository
Properties:
RepositoryName: docker-in-aws/codebuild
RepositoryPolicyText:
Version: '2008-10-17'
Statement:
- Sid: CodeBuildAccess
Effect: Allow
Principal:
Service: codebuild.amazonaws.com
Action:
- ecr:GetDownloadUrlForLayer
- ecr:BatchGetImage
- ecr:BatchCheckLayerAvailability
TodobackendRepository:
Type: AWS::ECR::Repository
...
...

In the preceding example, you create a new repository with the name docker-in-aws/codebuild, which will result in a fully qualified repository by the name of <account-id>.dkr.ecr.<region>.amazonaws.com/docker-in-aws/codebuild (for example, 385605022855.dkr.ecr.us-east-1.amazonaws.com/docker-in-aws/codebuild). Note that you must grant pull access to the CodeBuild service, as CodeBuild needs to pull the image to run as its build container.

You can now deploy the changes to the ECR stack by using the aws cloudformation deploy command, which you may recall from the chapter, Publishing Docker Images Using ECR is deployed to a stack called ecr-repositories:

> export AWS_PROFILE=docker-in-aws
> aws cloudformation deploy --template-file ecr.yml --stack-name ecr-repositories
Enter MFA code for arn:aws:iam::385605022855:mfa/justin.menga:

Waiting for changeset to be created..
Waiting for stack create/update to complete
Successfully created/updated stack - ecr-repositories

Once the deployment is complete, you need to retag the image that you created earlier, with the fully qualified name of your new ECR repository, after which you can log in to ECR and publish the image:

> docker tag codebuild 385605022855.dkr.ecr.us-east-1.amazonaws.com/docker-in-aws/codebuild
> eval $(aws ecr get-login --no-include-email)
WARNING! Using --password via the CLI is insecure. Use --password-stdin.
Login Succeeded
> docker push 385605022855.dkr.ecr.us-east-1.amazonaws.com/docker-in-aws/codebuild
The push refers to repository [385605022855.dkr.ecr.us-east-1.amazonaws.com/docker-in-aws/codebuild]
770fb042ae3b: Pushed
0cdc6e0d843b: Pushed
395fced17f47: Pushed
3abf4e550e49: Pushed
0a6dfdbcc220: Pushed
27760475e1ac: Pushed
5270ef39cae0: Pushed
2c88066e123c: Pushed
b09386d6aa0f: Pushed
1ed7a5e2d1b3: Pushed
cd7100a72410: Pushed
latest: digest:
sha256:858becbf8c64b24e778e6997868f587b9056c1d1617e8d7aa495a3170761cf8b size: 2618