Overview:
Most of the organizations use amazon cloud AWS. So naturally we might want to use Elastic Container Registry (ECR) to store the docker images.In order to push the docker images into ECR, we need some credentials. Some of us create an IAM user and store that in the CI server like Jenkins. It is not really a good practice to create an IAM user. We should be always using some sort of Role to provide the short term token to authenticate the user. In this article, Lets see how we can create a docker repository for our docker image and push it into ECR using docker-credential-helper.
Prerequisites:
I assume you already have the following!
- Docker knowledge
- AWS knowledge
- AWS account with enough permission
- Laptop/Desktop with Docker installed
Sample Docker Image:
Lets first create a simple docker image. I am planning to use my existing project here in GitHub. Feel free to fork/clone to play with this.
Creating Repository In AWS:
- Go to AWS Console to create a repo under ECR
- I created my repo as shown here.
- Once created, make a note of your docker repo name – URI.
- Make a note of the ‘view push commands’ section in the AWS console.
- Now your Jenkinsfile should be updated with the URI as shown here.
pipeline {
agent none
stages {
stage('Build Jar') {
agent {
docker {
image 'maven:3-alpine'
args '-v $HOME/.m2:/root/.m2'
}
}
steps {
sh 'mvn clean package -DskipTests'
}
}
stage('Build Image') {
steps {
script {
app = docker.build("12345678.dkr.ecr.ca-central-1.amazonaws.com/selenium-docker")
}
}
}
stage('Push Image') {
steps {
script {
app.push("latest")
}
}
}
}
}
- Now lets go to IAM to create a Role for your EC2 instance to push the docker images into ECR.
- Select the below policy (we need both read and write access – so select the power user. We do NOT need full access)
- Once the role is created with a name, attach the role to your EC2 instance.
- Even though the machine has the role attached, it still will NOT be able to push it to our ECR repository.
- We need credential store. Run the below commands one by one in the EC2 instance.
git clone https://github.com/awslabs/amazon-ecr-credential-helper
cd amazon-ecr-credential-helper
make docker
The above make docker command might take some time. Be patient. Once it is complete, below binary file would have been created. Run the below command to move it to the PATH.
sudo cp ./bin/local/docker-credential-ecr-login /usr/bin/docker-credential-ecr-login
- Run the below command. If it is not present, create it. Note: ~ is user home.
vi ~/.docker/config.json
- We need to include the below section in the config.json
"credsStore": "ecr-login"
- If it was an empty config.json, it should like this.
{
"credsStore": "ecr-login"
}
- Now try to push the docker image into the ECR from the EC2 instance. It should be successful!!