Search code examples
dockerdockerfileaws-cloudformationaws-codepipelineaws-codebuild

How to build Image from Dockerfile in AWS CodePipeline using buildspec.yml, and then push to ECR?


I have a Dockerfile in a CodeCommit Repository. I'm building a pipeline with two Stages which should:

  1. Connect to CodeCommit Source (successful)
  2. Build the image from Dockerfile in the Repository and push it to ECR (not successful)

I tried the following but, it exits with exit status 127 because of the command IMAGE_URI= $REPO_URI:$IMAGE_TAG.

CodeBuildProject:
Type: AWS::CodeBuild::Project
DependsOn: CodeBuildServiceRole
Properties:
  Name: pipeline
  Artifacts:
    Type: CODEPIPELINE
  Environment:
    Type: LINUX_CONTAINER
    ComputeType: !FindInMap [BuildPowerMap, !Ref   BuildPower, ComputeType]
    Image: aws/codebuild/standard:2.0
    EnvironmentVariables:
      - Name: AWS_DEFAULT_REGION
        Value: !Ref AWS::Region
      - Name: REPO_URI
        Value: !Sub ${AWS::AccountId}.dkr.ecr.${AWS::Region}.amazonaws.com/${ContainerRepo}
      - Name: AWS_ACCOUNT_ID
        Value: !Ref AWS::Region
    PrivilegedMode: true
  ServiceRole: !Ref CodeBuildServiceRole
  Source:
    Type: CODEPIPELINE
    BuildSpec:  |
      version: 0.2
      phases:
        pre_build:
          commands:
            - echo Logging in to Amazon ECR...
            - $(aws ecr get-login --no-include-email --region $AWS_DEFAULT_REGION)
            - CODEBUILD_RESOLVED_SOURCE_VERSION="${CODEBUILD_RESOLVED_SOURCE_VERSION:-$IMAGE_TAG}"
            - IMAGE_TAG=$(echo $CODEBUILD_RESOLVED_SOURCE_VERSION | cut -c 1-7)
            - IMAGE_URI= $REPO_URI:$IMAGE_TAG
        build:
          commands:
            - echo Build started on `date`
            - echo Building the Docker image...    
            - docker build --tag "$IMAGE_URI" .
        post_build:
          commands:
            - bash -c "if [ /"$CODEBUILD_BUILD_SUCCEEDING/" == /"0/" ]; then exit 1; fi"
            - echo Build completed on `date`
            - echo Pushing the Docker image...
            - docker push "$IMAGE_URI"
            - printf '[{"name":"nginx","imageUri":"%s"}]' "$IMAGE_URI" > images.json
      artifacts:
        files: images.json

Error Message from AWS CodeBuild, after I ran the pipeline:

enter image description here


Solution

  • Based on the comments.

    The issue was caused by space in:

    IMAGE_URI= $REPO_URI:$IMAGE_TAG
    

    It should be:

    IMAGE_URI=$REPO_URI:$IMAGE_TAG