Build & Push Docker Containers within a Pipeline: Amazon ECR

Build and push Docker containers to a Amazon Elastic Container Registry using Kaniko

To build and push containers with Sail CI you can use Kaniko as a task within your pipeline.

What is Kaniko?

Kaniko is a tool to build and push container images from a Dockerfile. It does not depend on the Docker daemon and executes each command within a Dockerfile entirely in userspace.

Find more information at:
https://github.com/GoogleContainerTools/kaniko

Amazon Elastic Container Registry

tasks:
  build-push:
    image: gcr.io/kaniko-project/executor
    args:
      - --context
      - $(GIT_CLONE_DIR)
      - --destination
      - AWS_ACCOUNT_ID.dkr.ecr.eu-west-2.amazonaws.com/demo:$(GIT_SHORT_SHA)
    mounts:
      - /workspace/docker/config.json: AWS_CREDENTIALS_HELPER
      - /workspace/aws/credentials: AWS_CREDENTIALS
    env:
      - DOCKER_CONFIG: /workspace/docker
      - AWS_SHARED_CREDENTIALS_FILE: /workspace/aws/credentials


We first mount the AWS_CREDENTIALS_HELPER environment variable to the filesystem so that Kaniko knows what registry to apply authentication to when pushing images.

You can create the AWS_CREDENTIALS_HELPER environment variable using https://app.sail.ci.

A typical config.json credentials helper file for ECR looks like:

{
  "credHelpers": {
    "AWS_ACCOUNT_ID.dkr.ecr.AWS_REGION.amazonaws.com": "ecr-login"
  }
}

Note: Ensure you update AWS_ACCOUNT_ID and AWS_REGION based on your ECR repository

The second environment variable we mount to the filesystem is AWS_CREDENTIALS. This is the credentials for an account with permissions to access the ECR registry you wish to push to.

See https://sail.ci/docs/environment-variables for more information using environment variables.

See https://sail.ci/docs/mounts for more information on mounts.

See for more information using environment variables.

A typical AWS credentials file:

[default]
aws_access_key_id     = ABCDEFGHIJKLMNOPQRST
aws_secret_access_key = abc123defg456hijk789abc123def345
region                = eu-west-2

You can typically base64 encode a file using:

cat "./credentials" | base64

The "build-push" task uses the official Kaniko image from Google to then specify a context to build the Docker image (in this example the Dockerfile is at the root of the project). A --destination argument provides Kaniko with the registry to push the image once built.

DOCKER_CONFIG and AWS_SHARED_CREDENTIALS_FILE are set using env environment variables to point at the mounted files to tell Kaniko where the credentials and configurations are in order to authenticate and push images to ECR.