Hướng dẫn AWS CodeBuild, build image tự động cho ECR

  • October 1, 2022
  • 1042

Chúng ta đã biết cách Create docker image to AWS ECR bằng command line thủ công. Vậy làm thế nào để build và push docker image tự động lên ECR? Để giải quyết cho câu hỏi trên chúng ta cùng tìm hiểu về AWS CodeBuild nhé.

Aws CodeBuild là gì?

AWS CodeBuild là dịch vụ giúp biên dịch code, unit test, tạo ra các gói phần mềm sẵn sàng triển khai tự động. CodeBuild hỗ trợ nhiều source control: github, bitbucket..., hỗ chợ hầu hết các ngôn ngữ lập trình: golang, java, node, php, python, ruby, docker..., chi phí tính theo phút, có thể thiết lập nhiều cấu hình build khác nhau, máy chủ sẽ chỉ chạy khi có trigger build.

Create CodeBuild

Giờ chúng ta sẽ tạo thử một CodeBuild giúp build và push docker image tự động lên ECR.
Create codebuild
Chọn source control là github, sau đó connect đến tài khoản github của bạn, chọn project mà bạn muốn build.
codebuild with github
Thiết lập trigger build, ở ví dụ này mình sẽ build docker image khi có code được push lên branch master. Chọn trigger push và head ref là refs/heads/master
CodeBuild trigger build
Thiết lập môi trường dùng để build chọn: Managed image, Operating system linux, tạo iam role build....
codebuild env
Codebuild env
Thêm quyền cho iam role vừa tạo sau khi tạo codebuild thành công, có quyền truy cập để ecr, ecs, s3
Aws codebuild role
Thiết lập các biến env cho file buildspec.yml


// File env cho môi trường dev
ENV_FILE_NAME: .env.dev

// Uri của image trên ecr
API_REPOSITORY_URI: 056663857946.dkr.ecr.us-east-1.amazonaws.com/laravel-fpm

Buildspec env
Thiết lập nội dung build và push docker image lên ECR, trong file buildspec.yml


version: 0.2
phases:
  pre_build:
    commands:
      - echo Logging in to Amazone ECR...
      - aws --version
      - echo $AWS_DEFAULT_REGION
      #- docker login --username huunv --password password
      - COMMIT_HASH=$(echo $CODEBUILD_RESOLVED_SOURCE_VERSION | cut -c 1-7)
      - IMAGE_TAG=${COMMIT_HASH:=latest}
  build:
    commands:
      - echo Build started on `date`
      - echo $IMAGE_TAG
      - echo Building the Docker image...
      #- aws s3 cp s3://lear-ec2/${ENV_FILE_NAME} ${ENV_FILE_NAME}
      - cp ${ENV_FILE_NAME} .env
      - docker build -t ${API_REPOSITORY_URI} -f docker/app/Dockerfile .
      # - docker build -t ${ARTISAN_REPOSITORY_URI} -f docker/app/Dockerfile.migration .
      # - docker build -t ${BATCH_REPOSITORY_URI} -f docker/app/Dockerfile.phpbatch .
      - docker tag ${API_REPOSITORY_URI}:latest ${API_REPOSITORY_URI}:${IMAGE_TAG}
      # - docker tag ${ARTISAN_REPOSITORY_URI}:latest ${ARTISAN_REPOSITORY_URI}:${IMAGE_TAG}
      # - docker tag ${BATCH_REPOSITORY_URI}:latest ${BATCH_REPOSITORY_URI}:${IMAGE_TAG}
  post_build:
    commands:
      - aws ecr get-login --no-include-email --region $AWS_DEFAULT_REGION
      - $(aws ecr get-login --no-include-email --region $AWS_DEFAULT_REGION)
      - echo Build completed on `date`
      - docker push ${API_REPOSITORY_URI}:latest
      - docker push ${API_REPOSITORY_URI}:${IMAGE_TAG}
      # - docker push ${ARTISAN_REPOSITORY_URI}:latest
      # - docker push ${ARTISAN_REPOSITORY_URI}:${IMAGE_TAG}
      # - docker push ${BATCH_REPOSITORY_URI}:latest
      # - docker push ${BATCH_REPOSITORY_URI}:${IMAGE_TAG}
      # - echo Run migration
      # - aws ecs run-task --cluster ${API_CLUSTER_NAME} --count 1 --launch-type FARGATE --network-configuration awsvpcConfiguration="{subnets=[${PROTECTED_SUBNET_ID}],securityGroups=[${ARTISAN_SG_ID}],assignPublicIp=ENABLED}" --task-definition ${ARTISAN_TASK_NAME}
      - printf '[{"name":"laravel-fpm","imageUri":"%s"}]' ${API_REPOSITORY_URI}:${IMAGE_TAG} > imagedefinitions.json
      # - printf '[{"name":"batch","imageUri":"%s"}]' ${BATCH_REPOSITORY_URI}:${IMAGE_TAG} > imagebatchdefinitions.json
artifacts:
  files:
    - imagedefinitions.json
    # - imagebatchdefinitions.json

file buildspec.yml có thể để ở thư mục root của code, or khai báo trực tiếp trên aws console codebuild, trong ví dụ này mình sẽ khai báo trực tiếp
Config file buildspec.yml
Các thiết lập khác để như mặc định của aws. Click button create build project để tạo codebuild vậy là xong.

Build and check log

Tiếp theo chúng ta sẽ build thử project. Bạn có thể build image trực tiếp khi click vào button start build, hoặc push code lên nhánh master trigger đã được thiết lập ở phần trước.
Check log trong detail của 1 lần build
Check log build
Các lỗi sẽ được log màu đỏ trong build log, khi gặp lỗi ưu tiên fix lỗi từ trên xuống.
Build success

Build success
Kiểm tra image trên AWS ECR.
Aws ecr image
Xem trigger build trong tài khoản github
Trigger in github
Như vậy là chúng ta đã build được docker image push lên AWS ECR tự động mỗi lần code master thay đổi. Giờ đến lượt bạn. Thanks for readding...