简易的 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 免费额度足够

相关推荐
AI大模型..15 分钟前
Dify 本地部署安装教程(Windows + Docker),大模型入门到精通,收藏这篇就足够了!
人工智能·程序员·开源·llm·github·deepseek·本地化部署
CoderJia程序员甲3 小时前
GitHub 热榜项目 - 日榜(2026-02-24)
人工智能·ai·大模型·github·ai教程
无名的小白5 小时前
宝塔计划任务实现定时备份Openclaw/Workspace到Github
github
TG_yunshuguoji6 小时前
亚马逊云代理商:AWS 国际站缺卡新用户创建邮箱怎么选择?
安全·云计算·aws
散峰而望6 小时前
C++ 启程:从历史到实战,揭开命名空间的神秘面纱
c语言·开发语言·数据结构·c++·算法·github·visual studio
峰顶听歌的鲸鱼9 小时前
Zabbix监控系统
linux·运维·笔记·安全·云计算·zabbix·学习方法
Wcowin9 小时前
为Zensical添加 GitHub 热力图卡片
github·zensical
Wcowin12 小时前
为Zensical添加 GitHub 仓库卡片
javascript·github·zensical
TG_yunshuguoji12 小时前
亚马逊云代理商:如何监控AWS RDS使用率并设置报警?
运维·云计算·aws
菜鸟别浪14 小时前
内存管理-第1章-Linux 内核内存管理概述
linux·运维·云计算·虚拟化·内存管理