Search code examples
amazon-web-servicesamazon-ecsaws-codepipelineaws-codebuildamazon-ecr

AWS CodePipeline Docker push command returns 'no basic auth credentials'


I am using CodePipeline to push my image to ECR, it gets the repository from the GitHub, and tries to build it before pushing it to ECR. I figured out how to login to AWS ECR by the aws ecr get-login-password command. But the main problem is, in the post_build stage when I am trying to run command docker push. It returns me the error that says: no basic auth credentials

My buildspec.yml file:

phases:
  install:
    runtime-versions:
      nodejs: 16
  pre_build:
    commands:
      - echo Installing Dependencies
      - npm install
      - docker logout
      - aws ecr get-login-password || docker login --username AWS --password-stdin $AWS_ACCOUNT_ID.dkr.ecr.$AWS_DEFAULT_REGION.amazonaws.com
  build:
    commands:
      - docker build -t $IMAGE_REPO_NAME:$IMAGE_TAG .
      - docker tag $IMAGE_REPO_NAME:$IMAGE_TAG $AWS_ACCOUNT_ID.dkr.ecr.$AWS_DEFAULT_REGION.amazonaws.com/$IMAGE_REPO_NAME:$IMAGE_TAG
  post_build:
    commands:
      - echo Pushing the docker image
      - docker -v
      - aws --version
      - docker push $AWS_ACCOUNT_ID.dkr.ecr.$AWS_DEFAULT_REGION.amazonaws.com/$IMAGE_REPO_NAME:$IMAGE_TAG
      - printf '[{"name":"%s","imageUrl":"%s"}]' $CONTAINER_NAME $AWS_ACCOUNT_ID.dkr.ecr.$AWS_DEFAULT_REGION.amazonaws.com/$IMAGE_REPO_NAME:$IMAGE_TAG > imagedefinitions.json
artifacts:
  files: imagedefinitions.json

Screenshot from AWS Codebuild:

AWS Codebuild Error Image


Solution

  • In buildspec version 0.1, "CodeBuild runs each command in a separate instance of the default shell in the build environment. This means that each command runs in isolation from all other commands". That is the reason why ecr login in pre-build phase does not effect the post-build phase

    You should try to use version 0.2 which mentioned in reference link

    You might also try to run ecr login in the post-build phase, it may work, I guess