介绍
从 GitHub Actions 部署到 AWS 资源时,传统方法是将 IAM 用户访问密钥存储在 GitHub Secrets 中。然而,这种方法存在几个挑战:
- 访问密钥泄露的风险
- 定期轮换工作的需要
- 需要管理的密码数量增加
OIDC(OpenID Connect)认证解决了这些挑战。本文详细说明了如何在 GitHub Actions 和 AWS 之间设置 OIDC 集成。
什么是 OIDC?
OIDC 是基于 OAuth 2.0 的认证协议。GitHub Actions 颁发一个令牌,可以向 AWS 证明"我是来自此仓库的工作流",AWS 验证它并提供临时凭证。
OIDC 的优势
- 无需密码:无需在 GitHub 中存储访问密钥
- 增强安全性:仅使用临时凭证
- 细粒度权限控制:可以按仓库或分支限制权限
- 降低管理成本:无需密钥轮换
AWS 配置
1. 创建 IAM 身份提供商
首先,在 AWS 管理控制台中创建 IAM 身份提供商。
- 打开 IAM 控制台
- 点击"身份提供商"→"添加提供商"
- 输入以下信息:
提供商类型:OpenID Connect
提供商 URL:https://token.actions.githubusercontent.com
受众:sts.amazonaws.com
Terraform 示例
resource "aws_iam_openid_connect_provider" "github_actions" {
url = "https://token.actions.githubusercontent.com"
client_id_list = [
"sts.amazonaws.com",
]
thumbprint_list = [
"6938fd4d98bab03faadb97b34396831e3780aea1"
]
}
AWS SAM 示例
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: GitHub Actions OIDC Provider
Resources:
GitHubOIDCProvider:
Type: AWS::IAM::OIDCProvider
Properties:
Url: https://token.actions.githubusercontent.com
ClientIdList:
- sts.amazonaws.com
ThumbprintList:
- 6938fd4d98bab03faadb97b34396831e3780aea1
2. 创建 IAM 角色
接下来,创建 GitHub Actions 将要担任的 IAM 角色。
配置信任策略
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Federated": "arn:aws:iam::123456789012:oidc-provider/token.actions.githubusercontent.com"
},
"Action": "sts:AssumeRoleWithWebIdentity",
"Condition": {
"StringEquals": {
"token.actions.githubusercontent.com:aud": "sts.amazonaws.com"
},
"StringLike": {
"token.actions.githubusercontent.com:sub": "repo:your-org/your-repo:*"
}
}
}
]
}
条件详情
可以使用 token.actions.githubusercontent.com:sub 值限制访问。
# 特定仓库的全部访问
repo:your-org/your-repo:*
# 仅特定分支
repo:your-org/your-repo:ref:refs/heads/main
# 仅特定环境
repo:your-org/your-repo:environment:production
# 仅 Pull Request
repo:your-org/your-repo:pull_request
Terraform 示例
data "aws_iam_policy_document" "github_actions_assume_role" {
statement {
actions = ["sts:AssumeRoleWithWebIdentity"]
principals {
type = "Federated"
identifiers = [aws_iam_openid_connect_provider.github_actions.arn]
}
condition {
test = "StringEquals"
variable = "token.actions.githubusercontent.com:aud"
values = ["sts.amazonaws.com"]
}
condition {
test = "StringLike"
variable = "token.actions.githubusercontent.com:sub"
values = ["repo:your-org/your-repo:*"]
}
}
}
resource "aws_iam_role" "github_actions" {
name = "github-actions-deploy-role"
assume_role_policy = data.aws_iam_policy_document.github_actions_assume_role.json
}
# 附加所需的权限策略
resource "aws_iam_role_policy_attachment" "deploy_policy" {
role = aws_iam_role.github_actions.name
policy_arn = "arn:aws:iam::aws:policy/AmazonECS_FullAccess"
}
AWS SAM 示例
Resources:
GitHubActionsRole:
Type: AWS::IAM::Role
Properties:
RoleName: github-actions-deploy-role
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Federated: !GetAtt GitHubOIDCProvider.Arn
Action: sts:AssumeRoleWithWebIdentity
Condition:
StringEquals:
token.actions.githubusercontent.com:aud: sts.amazonaws.com
StringLike:
token.actions.githubusercontent.com:sub: repo:your-org/your-repo:*
ManagedPolicyArns:
- arn:aws:iam::aws:policy/AmazonECS_FullAccess
Outputs:
GitHubActionsRoleArn:
Description: ARN of the GitHub Actions IAM Role
Value: !GetAtt GitHubActionsRole.Arn
Export:
Name: GitHubActionsRoleArn
使用 SAM 部署:
sam build
sam deploy --guided
初始部署后,将输出的角色 ARN 作为 AWS_ROLE_ARN 注册到 GitHub Secrets 中。
3. 附加权限策略
向角色附加部署所需的权限。例如:
- S3 部署:
AmazonS3FullAccess - ECS 部署:
AmazonECS_FullAccess - Lambda:
AWSLambda_FullAccess
对于生产环境,建议根据最小权限原则创建自定义策略。
GitHub Actions 配置
创建工作流文件
创建 .github/workflows/deploy.yml。
name: Deploy to AWS
on:
push:
branches:
- main
# 获取 OIDC 令牌的权限设置(重要!)
permissions:
id-token: write
contents: read
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Configure AWS credentials
uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: arn:aws:iam::123456789012:role/github-actions-deploy-role
aws-region: ap-northeast-1
- name: Deploy to S3
run: |
aws s3 sync ./dist s3://your-bucket-name --delete
- name: Verify deployment
run: |
aws s3 ls s3://your-bucket-name
重要注意事项
1. permissions 配置
permissions:
id-token: write # 获取 OIDC 令牌所必需
contents: read # 检出仓库所必需
没有此设置,将无法获取 OIDC 令牌并会出现错误。
2. configure-aws-credentials 操作版本
使用 v4 或更高版本。旧版本可能不支持 OIDC。
uses: aws-actions/configure-aws-credentials@v4
实际示例:部署 SAM 应用程序
以下是使用 AWS SAM 部署无服务器应用程序的示例。
name: Deploy SAM Application
on:
push:
branches:
- main
permissions:
id-token: write
contents: read
env:
AWS_REGION: ap-northeast-1
SAM_STACK_NAME: my-sam-app
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Python
uses: actions/setup-python@v5
with:
python-version: '3.11'
- name: Setup SAM CLI
uses: aws-actions/setup-sam@v2
with:
use-installer: true
- name: Configure AWS credentials
uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: ${{ secrets.AWS_ROLE_ARN }}
aws-region: ${{ env.AWS_REGION }}
- name: SAM Build
run: sam build --use-container
- name: SAM Deploy
run: |
sam deploy \
--stack-name ${{ env.SAM_STACK_NAME }} \
--capabilities CAPABILITY_IAM \
--resolve-s3 \
--no-fail-on-empty-changeset \
--no-confirm-changeset
- name: Get Stack Outputs
run: |
aws cloudformation describe-stacks \
--stack-name ${{ env.SAM_STACK_NAME }} \
--query 'Stacks[0].Outputs' \
--output table
实际示例:部署到 ECS
作为更实际的示例,以下是 ECS 部署工作流。
name: Deploy to ECS
on:
push:
branches:
- main
permissions:
id-token: write
contents: read
env:
AWS_REGION: ap-northeast-1
ECR_REPOSITORY: my-app
ECS_SERVICE: my-service
ECS_CLUSTER: my-cluster
CONTAINER_NAME: my-container
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Configure AWS credentials
uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: ${{ secrets.AWS_ROLE_ARN }}
aws-region: ${{ env.AWS_REGION }}
- name: Login to Amazon ECR
id: login-ecr
uses: aws-actions/amazon-ecr-login@v2
- name: Build and push image to ECR
id: build-image
env:
ECR_REGISTRY: ${{ steps.login-ecr.outputs.registry }}
IMAGE_TAG: ${{ github.sha }}
run: |
docker build -t $ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG .
docker push $ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG
echo "image=$ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG" >> $GITHUB_OUTPUT
- name: Download task definition
run: |
aws ecs describe-task-definition \
--task-definition my-task \
--query taskDefinition > task-definition.json
- name: Update task definition
id: task-def
uses: aws-actions/amazon-ecs-render-task-definition@v1
with:
task-definition: task-definition.json
container-name: ${{ env.CONTAINER_NAME }}
image: ${{ steps.build-image.outputs.image }}
- name: Deploy to ECS
uses: aws-actions/amazon-ecs-deploy-task-definition@v1
with:
task-definition: ${{ steps.task-def.outputs.task-definition }}
service: ${{ env.ECS_SERVICE }}
cluster: ${{ env.ECS_CLUSTER }}
wait-for-service-stability: true
故障排除
错误:"Not authorized to perform sts:AssumeRoleWithWebIdentity"
原因:信任策略条件不匹配
解决方案:
- 验证 IAM 角色信任策略中的
token.actions.githubusercontent.com:sub值 - 检查仓库名称和分支名称是否正确
- 在 GitHub Actions 日志中检查实际的
sub声明值
- name: Debug OIDC token
run: |
curl -H "Authorization: bearer $ACTIONS_ID_TOKEN_REQUEST_TOKEN" \
"$ACTIONS_ID_TOKEN_REQUEST_URL&audience=sts.amazonaws.com" | \
jq -R 'split(".") | .[1] | @base64d | fromjson'
错误:"Error: Credentials could not be loaded"
原因:缺少 permissions 配置
解决方案:在工作流文件中添加以下内容
permissions:
id-token: write
contents: read
认证成功但出现权限错误
原因:所需的权限策略未附加到 IAM 角色
解决方案:向 IAM 角色附加适当的策略
aws iam attach-role-policy \
--role-name github-actions-deploy-role \
--policy-arn arn:aws:iam::aws:policy/AmazonS3FullAccess
安全最佳实践
1. 最小权限原则
只授予最低必要权限。
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"s3:PutObject",
"s3:GetObject",
"s3:ListBucket"
],
"Resource": [
"arn:aws:s3:::your-specific-bucket",
"arn:aws:s3:::your-specific-bucket/*"
]
}
]
}
2. 按分支或标签限制
将生产部署限制到特定分支。
{
"Condition": {
"StringEquals": {
"token.actions.githubusercontent.com:sub": "repo:your-org/your-repo:ref:refs/heads/main"
}
}
}
3. 按环境分离角色
为开发、预演和生产使用不同的角色。
- name: Configure AWS credentials (Production)
if: github.ref == 'refs/heads/main'
uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: ${{ secrets.AWS_ROLE_ARN_PROD }}
aws-region: ap-northeast-1
- name: Configure AWS credentials (Development)
if: github.ref == 'refs/heads/develop'
uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: ${{ secrets.AWS_ROLE_ARN_DEV }}
aws-region: ap-northeast-1
4. 使用 CloudTrail 进行审计
记录所有 API 调用并定期审查。
# CloudTrail 的 S3 存储桶
resource "aws_s3_bucket" "cloudtrail" {
bucket = "my-cloudtrail-logs-bucket"
}
resource "aws_s3_bucket_policy" "cloudtrail" {
bucket = aws_s3_bucket.cloudtrail.id
policy = jsonencode({
Version = "2012-10-17"
Statement = [
{
Sid = "AWSCloudTrailAclCheck"
Effect = "Allow"
Principal = {
Service = "cloudtrail.amazonaws.com"
}
Action = "s3:GetBucketAcl"
Resource = aws_s3_bucket.cloudtrail.arn
},
{
Sid = "AWSCloudTrailWrite"
Effect = "Allow"
Principal = {
Service = "cloudtrail.amazonaws.com"
}
Action = "s3:PutObject"
Resource = "${aws_s3_bucket.cloudtrail.arn}/*"
Condition = {
StringEquals = {
"s3:x-amz-acl" = "bucket-owner-full-control"
}
}
}
]
})
}
# CloudTrail
resource "aws_cloudtrail" "github_actions_audit" {
name = "github-actions-audit"
s3_bucket_name = aws_s3_bucket.cloudtrail.id
include_global_service_events = true
is_multi_region_trail = true
enable_logging = true
depends_on = [aws_s3_bucket_policy.cloudtrail]
}
结论
GitHub Actions 与 AWS 之间的 OIDC 集成提供了以下优势:
- 无访问密钥的安全部署
- 仅使用临时凭证
- 按仓库或分支进行细粒度权限控制
- 降低管理成本
虽然初始设置稍微复杂,但一旦配置完成,将带来长期的安全性和可操作性改善。我强烈建议考虑采用这种方式。
