Skip to content

Setting up to push container images to ECR using GitHub Actions

4 minute read
Content level: Intermediate
0

I created a sample configuration to push container images to ECR using GitHub Actions.

GitHub Repository Create

Please create a repository following the steps in the document below.
https://docs.github.com/en/repositories/creating-and-managing-repositories/creating-a-new-repository

Creating an identity provider and IAM role for GitHub Actions

GitHub Actions and AWS integration uses OIDC for authentication.
Identity provider configuration can be set up following the steps in the document below.
https://docs.github.com/en/actions/security-for-github-actions/security-hardening-your-deployments/configuring-openid-connect-in-amazon-web-services

This time, i configured the settings based on the CloudFormation template in the GitHub repository below.
I have commented out "ThumbprintList" because, as mentioned in the GitHub issue comments, it is no longer required to specify this after July 6, 2023.
https://github.com/aws-actions/configure-aws-credentials#configure-aws-credentials-for-github-actions

AWSTemplateFormatVersion: '2010-09-09'
Description: OIDC settings for Github Actions. 

Parameters:
  EnvName:
    Type: String
    Default: prd
    AllowedValues:
      - prd
    Description: Environment name
  OrgID:
    Type: String
    Description: Github Organazation ID
  RepoName:
    Type: String
    Default: RepositoryName
    Description: Repository name

Resources:
  OIDCProvider:
    Type: AWS::IAM::OIDCProvider
    Properties:
      ClientIdList:
        - 'sts.amazonaws.com'
      Url: https://token.actions.githubusercontent.com
#      ThumbprintList:
#        - 6938fd4d98bab03faadb97b34396831e3780aea1
#        - 1c58a3a8518e8759bf075b76b750d4f2df264fcd

  GithubActionsPolicy:
    Type: AWS::IAM::ManagedPolicy
    Properties:
      PolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: Allow
            Action:
              - 'ecr:UploadLayerPart'
              - 'ecr:PutImage'
              - 'ecr:InitiateLayerUpload'
              - 'ecr:CompleteLayerUpload'
              - 'ecr:BatchCheckLayerAvailability'
              - 'ecr:GetAuthorizationToken'
            Resource: '*'
      ManagedPolicyName: !Sub policy-${EnvName}-github-oidc-${RepoName}-001

  OIDCProviderRole:
    Type: AWS::IAM::Role
    Properties:
      RoleName: !Sub 'role-${EnvName}-github-oidc-${RepoName}-001'
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Principal:
              Federated: !Sub 'arn:aws:iam::${AWS::AccountId}:oidc-provider/token.actions.githubusercontent.com'
            Action: 'sts:AssumeRoleWithWebIdentity'
            Condition:
              StringLike:
                'token.actions.githubusercontent.com:sub':
                  - !Sub 'repo:${OrgID}/${RepoName}:*'
      ManagedPolicyArns:
        - !Ref GithubActionsPolicy

Creating an ECR repository

ECR repository creation can be done following the steps in the document below.
https://docs.aws.amazon.com/AmazonECR/latest/userguide/repository-create.html
a

Create a GitHub Actions workflow file

I created the workflow file as follows.
For ECR authentication, i am using "amazon-ecr-login" which is available as shown in the repository below.
Additionally, i set up GitHub Actions to run when changes occur to files in the "ecs/function" directory and to the Dockerfile.
https://github.com/aws-actions/amazon-ecr-login

name: ECR push

on:
  pull_request:
    branches:
      - main
    paths:
      - "ecs/function/**"
      - "ecs/Dockerfile"
    types: [closed]

permissions:
  id-token: write
  actions: write
  contents: read
  pull-requests: read

jobs:
  push_ecr:
    runs-on: ubuntu-latest
    permissions:
      id-token: write
      contents: read
    defaults:
      run:
        working-directory: ./ecs/
    steps:
      - uses: actions/checkout@v4

      - uses: aws-actions/configure-aws-credentials@v4
        with:
          aws-region: "ap-northeast-1"
          role-to-assume: "arn:aws:iam::<your-aws-account-id>:role/role-prd-github-oidc-ecr-test-001"

      - uses: aws-actions/amazon-ecr-login@v2
        id: login-ecr

      - name: create container image
        env:
          REGISTRY: ${{ steps.login-ecr.outputs.registry }}
          REPOSITORY: "ecr-test"
          IMAGE_TAG: ${{ github.sha }}
        run: |
          docker build . --tag ${{ env.REGISTRY }}/${{ env.REPOSITORY }}:${{ env.IMAGE_TAG }}
          docker push ${{ env.REGISTRY }}/${{ env.REPOSITORY }}:${{ env.IMAGE_TAG }}

A sample Dockerfile is created as follows:

FROM python:3.12.4

WORKDIR /app
ADD ./function/ /app

CMD ["python3", "index.py"]

A sample index.py is created as follows:

import json

def main():
    print("test1")

if __name__ == '__main__':
    main()

Place each file in the following configuration:

.
├── .github
│   └── workflows
│       └── ecr-push.yaml
└── ecs
    ├── Dockerfile
    └── function
        └── index.py

After creating the files, please push them to the GitHub repository.
Please create the main branch in advance.

git checkout -b dev
git add .
git commit -m "actions test"
git push origin dev

Verify that GitHub Actions is working

After pushing the code, GitHub Actions will start running when you merge from the dev branch to the main branch.
Create a pull request to the main branch with changes as shown in the image below.
After creating the pull request, GitHub Actions will start running when you merge it.
a

You can check the history of executed workflows by opening the "Actions" tab.
If the status is green as shown in the image below, the execution was successful.
a

After GitHub Actions execution is complete, you can check the container image created from the ECR repository.
a

EXPERT
published a month ago117 views