概览
OpenID Connect (OIDC) 允许您的 GitHub Actions 工作流程访问 Amazon Web Services (AWS) 中的资源,而无需将任何 AWS 凭据存储为长期 GitHub 机密。
本指南介绍如何配置 AWS 信任 GitHub 的 OIDC 作为联合标识,并包括使用令牌向 AWS 验证并访问资源的 aws-actions/configure-aws-credentials
工作流程示例。
基本要求
-
要了解 GitHub 如何使用 OpenID Connect (OIDC) 的基本概念及其体系结构和优势,请参阅“关于使用 OpenID Connect 进行安全强化”。
-
在继续之前,必须规划安全策略,以确保仅以可预测的方式分配访问令牌。 要控制云提供商颁发访问令牌的方式,必须至少定义一个条件,使不受信任的存储库无法为云资源请求访问令牌。 更多信息请参阅“使用云配置 OIDC 信任”。
将身份提供商添加到 AWS
要将 GitHub OIDC 提供商添加到 IAM,请参阅 AWS 文档。
- 对于提供程序 URL:使用
https://token.actions.githubusercontent.com
- 对于“受众”:如果您使用的是官方操作,请使用
sts.amazonaws.com
。
配置角色和信任策略
要在 IAM 中配置角色和信任,请参阅 AWS 文档中的“假定角色”和“为 Web 身份或 OpenID Connect Federation 创建角色”。
编辑信任关系以将 sub
字段添加到验证条件。 例如:
"Condition": {
"ForAllValues:StringEquals": {
"token.actions.githubusercontent.com:aud": "sts.amazonaws.com",
"token.actions.githubusercontent.com:sub": "repo:octo-org/octo-repo:ref:refs/heads/octo-branch"
}
}
更新 GitHub Actions 工作流程
要更新 OIDC 的工作流程,您需要对 YAML 进行两项更改:
- 为令牌添加权限设置。
- 使用
aws-actions/configure-aws-credentials
操作将 OIDC 令牌 (JWT) 交换为云访问令牌。
添加权限设置
The job or workflow run requires a permissions
setting with id-token: write
. You won't be able to request the OIDC JWT ID token if the permissions
setting for id-token
is set to read
or none
.
The id-token: write
setting allows the JWT to be requested from GitHub's OIDC provider using one of these approaches:
- Using environment variables on the runner (
ACTIONS_ID_TOKEN_REQUEST_URL
andACTIONS_ID_TOKEN_REQUEST_TOKEN
). - Using
getIDToken()
from the Actions toolkit.
如果您只需要为单个作业获取 OIDC 令牌,则可以在该作业中设置此权限。 例如:
permissions:
id-token: write
You may need to specify additional permissions here, depending on your workflow's requirements.
请求访问令牌
aws-actions/configure-aws-credentials
操作从 GitHub OIDC 提供商接收 JWT,然后从 AWS 请求访问令牌。 更多信息请参阅 AWS 文档。
<example-bucket-name>
:在此处添加 S3 存储桶的名称。<role-to-assume>
:将示例替换为您的 AWS 角色。<example-aws-region>
:在此处添加您的 AWS 区域的名称。
# Sample workflow to access AWS resources when workflow is tied to branch
# The workflow Creates static website using aws s3
name: AWS example workflow
on:
push
env:
BUCKET_NAME : "<example-bucket-name>"
AWS_REGION : "<example-aws-region>"
# permission can be added at job level or workflow level
permissions:
id-token: write
contents: read # This is required for actions/checkout
jobs:
S3PackageUpload:
runs-on: ubuntu-latest
steps:
- name: Git clone the repository
uses: actions/checkout@v3
- name: configure aws credentials
uses: aws-actions/configure-aws-credentials@v1
with:
role-to-assume: arn:aws:iam::1234567890:role/example-role
role-session-name: samplerolesession
aws-region: ${{ env.AWS_REGION }}
# Upload a file to AWS s3
- name: Copy index.html to s3
run: |
aws s3 cp ./index.html s3://${{ env.BUCKET_NAME }}/