diff --git a/.github/workflows/reusable-ecr-build-push.yml b/.github/workflows/reusable-ecr-build-push.yml new file mode 100644 index 0000000..09a2fbd --- /dev/null +++ b/.github/workflows/reusable-ecr-build-push.yml @@ -0,0 +1,66 @@ +name: Reusable workflow to build and push Docker image to Amazon ECR + +on: + workflow_call: + inputs: + aws-region: + description: 'AWS Region for ECR' + required: true + type: string + + +# Permission can be added at job level or workflow level +permissions: + id-token: write # This is required for requesting the JWT + contents: read # This is required for actions/checkout + +jobs: + build-and-push: + runs-on: ubuntu-latest + steps: + - name: Checkout code + uses: actions/checkout@9bb56186c3b09b4f86b1c65136769dd318469633 # v4.1.2 + + - name: configure aws credentials + uses: aws-actions/configure-aws-credentials@e3dd6a429d7300a6a4c196c26e071d42e0343502 # v4.0.2 + with: + role-to-assume: arn:aws:iam::478656756051:role/GitHubAction-AssumeRoleWithAction + role-session-name: GitHub_to_AWS_via_FederatedOIDC + aws-region: ${{ inputs.aws-region }} + + - name: Sts GetCallerIdentity + run: | + aws sts get-caller-identity + + - name: Get AWS ECR login using oidc token + run: | + aws ecr get-login-password --region ${{ inputs.aws-region }} | docker login --username AWS --password-stdin 478656756051.dkr.ecr.${{ inputs.aws-region }}.amazonaws.com + + - name: Docker build + run: | + docker build -f ./dockerfile/api/Dockerfile \ + -t 478656756051.dkr.ecr.${{ inputs.aws-region }}.amazonaws.com/github-action-demo:${{ github.sha }} \ + -t 478656756051.dkr.ecr.${{ inputs.aws-region }}.amazonaws.com/github-action-demo:latest . + + - name: Run Trivy vulnerability scanner + uses: aquasecurity/trivy-action@d710430a6722f083d3b36b8339ff66b32f22ee55 # v0.19.0 + with: + image-ref: 478656756051.dkr.ecr.${{ inputs.aws-region }}.amazonaws.com/github-action-demo:${{ github.sha }} + format: 'sarif' + output: 'trivy-report.sarif' + ignore-unfixed: true + + - name: Upload Trivy report to GitHub + uses: github/codeql-action/upload-sarif@v1 + with: + sarif_file: 'trivy-report.sarif' + + - name: Docker push to AWS ECR + run: | + docker push 478656756051.dkr.ecr.${{ inputs.aws-region }}.amazonaws.com/github-action-demo:${{ github.sha }} + docker push 478656756051.dkr.ecr.${{ inputs.aws-region }}.amazonaws.com/github-action-demo:latest + + # [Extremely Important] + - name: Remove the cached AWS credentials from the runner + run: | + rm -rf /home/runner/.docker/config.json