Using Github Actions Build Docker Image Push to AWS ECR
Table of Contents
AWS provides Github Actions to allow integrating Continuous Integration and Continuous Delivery to AWS solutions.
Before you starting, let’s assume that you have already configured the aws client, you’ve a github account.
Creating an AWS ECR
Creating a image repository and named shenlelu-test
:
aws ecr create-repository \
--repository-name shenlelu-test
Creating a Github Repository
Setup Github repo:
- Login to Github
- Create a repo named
testrepo
- Ref: Create a repo
In local workspace, create a new repository on the command line:
mkdir ~/workspace/myrepo
cd ~/workspace/myrepo
git init
git remote add origin git@github.com:lushenle/testrepo.git
Using An existence of Dockerfile
from the repo CSE546-FallA2021, so, add it as a submodule and pust it:
git submodule add git@github.com:EugeneKuz/CSE546-FallA2021.git
git add .
git commit -m 'add submodule'
git push --set-upstream origin main
Configuring the Github Actions
Add credentials in Github secrets, you can do this by going to settings of your repository and then secrets tab, where you add them:
AWS_ACCESS_KEY_ID
: AWS access key IDAWS_SECRET_ACCESS_KEY
: AWS secret access key
After setting up the repository, Create two folders in the root .github/workflow and inside the workflow, folder create a TASK_NAME.yml
file:
mkdir -p .github/workflow
This TASK_NAME.yml
contains the set of instructions that the Workflow will execute. Here build.yml
is the file that we need to write:
name: Build Docker Image
on:
push:
branches: [ main ]
jobs:
docker:
runs-on: ubuntu-latest
steps:
- name: Check out code
uses: actions/checkout@v2
with:
submodules: recursive
# Using the short head as the image tag
- name: Get hash
run: echo "::set-output name=sha_short::$(git rev-parse --short HEAD)"
id: sha
- name: Configure AWS credentials
uses: aws-actions/configure-aws-credentials@v1
with:
aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
aws-region: ap-northeast-2
- name: Login to Amazon ECR
id: login-ecr
uses: aws-actions/amazon-ecr-login@v1
- name: Build, tag, and push image to Amazon ECR
env:
ECR_REGISTRY: ${{ steps.login-ecr.outputs.registry }}
# ECR_REPOSITORY is the previously created aws ECR repo name
ECR_REPOSITORY: shenlelu-test
IMAGE_TAG: ${{ steps.sha.outputs.sha_short }}
# Build and Push image
run: |
docker build -t $ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG CSE546-FallA2021/.
docker push $ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG
Commit the workflow code to work and push cahnges:
git add .github/.
git commit -m 'add github action: build image and push to AWS ECR'
git push
Monitoring, Building, and Pushing
- Make a commitment to your Repository by adding the
IMAGE_TAG
value inbuild.yml
File. - Once the changes are pushed to the repository checkout the
Actions
Tab.