简易的 AWS SAM + GitHub Actions 项目

下面是一个 最简易的 AWS SAM + GitHub Actions 项目,目标是:

✅ 用 Python 写一个 Hello World Lambda

✅ 通过 API Gateway 暴露为 HTTP 接口

✅ 使用 GitHub Actions 自动部署到 AWS(无 CI/CD 测试,仅部署)

✅ 全程使用 OIDC 安全认证(无需 Access Key)


🧰 第一步:本地创建项目

1. 创建项目目录

复制代码
mkdir simple-sam-github && cd simple-sam-github

2. 初始化 Git

复制代码
git init

3. 使用 SAM 快速生成模板

复制代码
sam init \
  --name simple-sam-github \
  --runtime python3.12 \
  --dependency-manager pip \
  --app-template hello-world

这会生成:

复制代码
simple-sam-github/
├── hello_world/
│   ├── app.py
│   └── requirements.txt
├── tests/
├── template.yaml
└── README.md

4. 简化代码(可选)

编辑 hello_world/app.py,保留最简逻辑:

复制代码
# hello_world/app.py
import json

def lambda_handler(event, context):
    return {
        "statusCode": 200,
        "body": json.dumps({"message": "Hello from SAM + GitHub Actions!"})
    }

5. 清空依赖(本例不需要第三方库)

复制代码
echo "" > hello_world/requirements.txt

☁️ 第二步:配置 AWS(关键!)

目标:让 GitHub Actions 能安全部署到你的 AWS 账户

1. 登录 AWS 控制台 → IAM

2. 创建 OIDC 身份提供商

  • 路径:IAM → Identity providers → Add provider
  • Provider type: OpenID Connect
  • Provider URL: https://token.actions.githubusercontent.com
  • Audience: sts.amazonaws.com
  • 点击 Get thumbprintAdd provider

✅ 成功后你会看到:token.actions.githubusercontent.com

3. 创建权限策略

点击策略(新窗口),粘贴以下 JSON:

复制代码
{
  "Version": "2012-10-17",
  "Statement": [
    { "Effect": "Allow", "Action": "cloudformation:*", "Resource": "*" },
    { "Effect": "Allow", "Action": "lambda:*", "Resource": "*" },
    { "Effect": "Allow", "Action": "apigateway:*", "Resource": "*" },
    { "Effect": "Allow", "Action": "iam:CreateRole", "Resource": "arn:aws:iam::ACCOUNT_ID:role/*" },
    { "Effect": "Allow", "Action": "iam:PutRolePolicy", "Resource": "arn:aws:iam::ACCOUNT_ID:role/*" },
    { "Effect": "Allow", "Action": "iam:PassRole", "Resource": "arn:aws:iam::ACCOUNT_ID:role/*" },
    { "Effect": "Allow", "Action": "s3:*", "Resource": "arn:aws:s3:::aws-sam-cli-managed-*" }
  ]
}

🔁 将 ACCOUNT_ID 替换为你的 AWS 账户 ID(12 位数字)

保存策略(如 SimpleSAMDeployPolicy),返回角色创建页面,选择该策略。

4. 创建角色 IAM Role(供 GitHub 使用)

  • 路径:IAM → Roles → Create role
  • Trusted entity type: Web identity
  • Identity provider: token.actions.githubusercontent.com
  • Audience: sts.amazonaws.com
  • 添加刚加的权限策略

点击 Next

5. 命名角色

  • Role name: github-simple-sam-role
  • 创建角色

✅ 记下角色 ARN:arn:aws:iam::123456789012:role/github-simple-sam-role


🌐 第三步:配置 GitHub

1. 在 GitHub 上创建仓库

  • 名称:simple-sam-github
  • 不要初始化 README

2. 推送本地代码

复制代码
git remote add origin https://github.com/YOUR_GITHUB_USERNAME/simple-sam-github.git
git branch -M main
git add .
git commit -m "feat: initial SAM hello world"
git push -u origin main

📂 第四步:添加 GitHub Actions 部署文件

创建 .github/workflows/deploy.yml

复制代码
name: Deploy SAM App

on:
  push:
    branches: [ main ]

jobs:
  deploy:
    runs-on: ubuntu-latest
    permissions:
      id-token: write   # 必须启用 OIDC
      contents: read

    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Setup Python
        uses: actions/setup-python@v5
        with:
          python-version: '3.12'

      - name: Install AWS SAM CLI
        run: pip install aws-sam-cli

      - name: Configure AWS Credentials (via OIDC)
        uses: aws-actions/configure-aws-credentials@v4
        with:
          role-to-assume: arn:aws:iam::123456789012:role/github-simple-sam-role  # ← 替换为你的角色 ARN
          aws-region: us-east-1  # 可改为 ap-southeast-1 等

      - name: Build SAM Application
        run: sam build

      - name: Deploy to AWS
        run: |
          sam deploy \
            --stack-name simple-sam-github-stack \
            --capabilities CAPABILITY_IAM \
            --no-confirm-changeset \
            --region us-east-1

⚠️ 修改两处:

  1. role-to-assume: 替换为你的角色 ARN
  2. --region: 改为你常用的区域(如 ap-southeast-1

▶️ 第五步:触发部署

复制代码
git add .github/workflows/deploy.yml
git commit -m "feat: add GitHub Actions deployment"
git push

GitHub Actions 会自动运行:

  • 安装 SAM CLI
  • 通过 OIDC 获取 AWS 临时凭证
  • 构建并部署 SAM 应用

🔍 第六步:验证结果

1. 查看部署日志

  • GitHub → Actions → Deploy SAM App → 查看日志

成功时会输出:

复制代码
Successfully created/updated stack - simple-sam-github-stack

2. 获取 API URL

  • AWS 控制台 → CloudFormation → 找到堆栈 simple-sam-github-stack
  • 查看 OutputsHelloWorldApi

示例 URL:

复制代码
https://abc123.execute-api.us-east-1.amazonaws.com/hello

3. 测试 API

复制代码
curl https://abc123.execute-api.us-east-1.amazonaws.com/hello

响应:

复制代码
{"message": "Hello from SAM + GitHub Actions!"}

✅ 成功!


🗑 第七步:清理资源(避免费用)

删除 CloudFormation 堆栈

复制代码
aws cloudformation delete-stack --stack-name simple-sam-github-stack --region us-east-1

或在控制台手动删除。


✅ 项目结构总结

复制代码
simple-sam-github/
├── hello_world/
│   ├── app.py                 # Lambda 函数
│   └── requirements.txt       # 无依赖
├── template.yaml              # SAM 模板(自动生成)
└── .github/workflows/deploy.yml  # GitHub Actions 部署脚本

💡 优势

  • 零密钥:使用 OIDC,不存储 AWS Access Key
  • 全自动:推代码即部署
  • 极简:无测试、无多环境、无复杂逻辑
  • 低成本:Lambda 免费额度足够

相关推荐
深圳市恒讯科技2 小时前
2026新加坡服务器硬件防火墙配置推荐
运维·服务器·云计算
潘晓可3 小时前
从自建Github实例迁移仓库到SaaS版Github
github
极客小云3 小时前
【基于AI的自动商品试用系统:不仅仅是虚拟试衣!】
javascript·python·django·flask·github·pyqt·fastapi
China_Yanhy3 小时前
入职 Web3 运维日记 · 第 6 日:触碰红线 —— 私钥托管与 AWS KMS 的博弈
运维·web3·aws
主机哥哥11 小时前
阿里云OpenClaw(原Clawdbot/Moltbot)一键秒级部署教程
阿里云·云计算
打码人的日常分享13 小时前
智能制造数字化工厂解决方案
数据库·安全·web安全·云计算·制造
70asunflower15 小时前
阿里云无影云电脑 Docker 使用完全指南
阿里云·docker·云计算
主机哥哥15 小时前
零基础入门:阿里云OpenClaw部署全流程详解(图文版)
阿里云·云计算
念丶小宇16 小时前
Github上传大文件
github