Jenkinsfile: Publish Docker Image to Amazon ECR

Reading Time: 1 minute

Problem

You pushed a docker image to AWS ECR and get denied: requested access to the resource is denied error.

stage('Publish Docker Image to AWS'){
steps {
  script {

   //build image
   commit_id = readFile('commit_id').trim()
   def image = docker.build("$ECR_REPO_NAME:$commit_id")
    
   //push image
   docker.withRegistry( "https://$ECR_REGISTRY", ECR_CRED) {
       echo ' Pushing Latest docker image'
       image.push()
   } 
  }
}
}

Solution

Cleanup current user docker credentials using

sh 'rm ~/.dockercfg || true'
sh 'rm ~/.docker/config.json || true'

Jenkins stage should look like that

stage('Publish Docker Image to AWS'){
steps {
  script {
   //cleanup current user docker credentials
   sh 'rm ~/.dockercfg || true'
   sh 'rm ~/.docker/config.json || true'

   //build image
   commit_id = readFile('commit_id').trim()
   def image = docker.build("$ECR_REPO_NAME:$commit_id")
    
   //push image
   docker.withRegistry( "https://$ECR_REGISTRY", ECR_CRED) {
       echo ' Pushing Latest docker image'
       image.push()
   } 
  }
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *