AWS 使用 GitHub Action workflows 实现自动构建镜像及推送到 ECR

AWS GitHub DevOps About 2,041 words

IAM

在IAM中创建角色role。假设名称为:github-actions-ecr(后面ecr.yaml中要用)

Step 0: Add provider

在IAM页面,选择Identity providers,选择Add provider。

选择OpenID Connect:
- 填写Provider为token.actions.githubusercontent.com
- 填写Audience为sts.amazonaws.com

Step 1: Select trusted entity

选择Web identity,在Identity provider中选择上一步创建的token.actions.githubusercontent.com,在Audience里选择sts.amazonaws.com。

其他如下:organization就填写github.com/<owner>中的<owner>即可(账号名)。

Identity provider:token.actions.githubusercontent.com
Audience:sts.amazonaws.com
GitHub organization:my_org
GitHub repository:*
GitHub branch:*

Step 2: Add permissions

搜索AmazonEC2ContainerRegistryPowerUser,勾选它,然后下一步。

Step 3:

填Role名字,比如github-actions-ecr,点Create role。

ecr.yaml

新建.github文件夹,在.github文件下新建workflows文件夹(注意单词拼写,否则无法触发GitHub Action)

完整路径:.github/workflows/ecr.yaml

完整代码如下:(<ACCOUNT_ID>替换为AWS的账号ID)

name: Build and Push to ECR

on:
  push:
    branches: [main]
  workflow_dispatch:        # 允许在 Actions 页面手动触发

permissions:
  id-token: write           # 必须有,OIDC 要用
  contents: read

env:
  AWS_REGION: us-east-1                                            # 改成你的 region
  AWS_ROLE_ARN: arn:aws:iam::<ACCOUNT_ID>:role/github-actions-ecr  # 改成你的 Role ARN
  ECR_REPO: ${{ github.event.repository.name }}                    # 自动取 GitHub 仓库名

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - uses: aws-actions/configure-aws-credentials@v4
        with:
          role-to-assume: ${{ env.AWS_ROLE_ARN }}
          aws-region: ${{ env.AWS_REGION }}

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

      - name: Build & Push
        env:
          REGISTRY: ${{ steps.ecr.outputs.registry }}
        run: |
          docker build -t $REGISTRY/$ECR_REPO:${{ github.sha }} -t $REGISTRY/$ECR_REPO:latest .
          docker push --all-tags $REGISTRY/$ECR_REPO

可能的错误

公司的GitHub Enterprise管理员禁用了GitHub提供的运行机器。

需要联系管理员开通。

GitHub Actions hosted runners are disabled for this repository. For more information please contact your GitHub Enterprise Administrator.

Views: 6 · Posted: 2026-10-09

———         Thanks for Reading         ———

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓
Prev Post
Today In History
Browsing Refresh