Search code examples
github-actionsaws-ecrgithub-ci

GitHub CI script for build and push to different ECR based on differenct branch push


I have a project on GitHub, I want to setup CI job to build docker images and push to AWS ECR. My requirements are -

  1. One single ci file (I have created.github/workflows/aws.yml)
  2. CI job must trigger on the push to master and sandbox branches only
  3. If pushed to sandbox branch, then docker images should be pushed ECR1
  4. If pushed to master branch, then docker image should be pushed to ECR2

So far I have made the following CI file

.github/workflows/aws.yml -

  name: CI

  on:
    pull_request:
      branches:
      - master
      - sandbox
    push:
      branches:
      - master
      - sandbox

  env:
    AWS_REPOSITORY_URL_MASTER: ${{ secrets.AWS_REPOSITORY_URL_MASTER }}
    AWS_REPOSITORY_URL_SANDBOX: ${{ secrets.AWS_REPOSITORY_URL_SANDBOX }}
    AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
    AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}

  jobs:
    build-and-push:
      name: Build and push image to AWS ECR master
      runs-on: ubuntu-latest
      steps:

      - name: Checkout
        uses: actions/checkout@v2

      - name: Setup ECR
        run: $( aws ecr get-login --no-include-email --region ap-south-1)

      - name: Build and tag the image
        run: docker build -t $AWS_REPOSITORY_URL_MASTER .

      - name: Push
        run: docker push $AWS_REPOSITORY_URL_MASTER
    build-and-push-sandbox:
      name: Build and push image to AWS ECR master
      runs-on: ubuntu-latest
      steps:

      - name: Checkout
        uses: actions/checkout@v2

      - name: Setup ECR
        run: $( aws ecr get-login --no-include-email --region ap-south-1)

      - name: Build and tag the image
        run: docker build -t $AWS_REPOSITORY_URL_SANDBOX .

      - name: Push
        run: docker push $AWS_REPOSITORY_URL_SANDBOX

How will the script distinguish when to run build-and-push-master(triggered on master branch push) and build-and-push-sandbox(triggered on sandbox branch push)?


Solution

  • Add an if clauses at the job level:

    jobs:
        build-and-push:
          name: Build and push image to AWS ECR master
          runs-on: ubuntu-latest
          if: github.ref == 'refs/heads/master'
          steps:
    

    and

        build-and-push-sandbox:
          name: Build and push image to AWS ECR sandbox
          runs-on: ubuntu-latest
          if: github.ref == 'refs/heads/sandbox'
          steps:
    
    

    Alternatively, since the jobs are so similar, you can try to unify them and set an env variable $AWS_REPOSITORY to either ${{ secrets.AWS_REPOSITORY_URL_MASTER }} or ${{ secrets.AWS_REPOSITORY_URL_SANDBOX }}, depending on the value of github.ref.