第二章:CI/CD 流水线——GitHub Actions 自动化
第二章:CI/CD 流水线——GitHub Actions 自动化
“代码合并后自动测试、构建镜像、部署上线。GitHub Actions 让 CI/CD 成为每个项目的标配。”
2.1 CI/CD 流程
flowchart LR
A[Push/PR] --> B[Run Tests]
B --> C{通过?}
C -->|是| D[Build Image]
C -->|否| E[通知失败]
D --> F[Push to Registry]
F --> G[Deploy]
2.2 GitHub Actions 基础
核心概念:
| 概念 | 说明 |
|---|---|
| Workflow | 自动化流程 |
| Job | 工作步骤组 |
| Step | 具体操作 |
| Action | 可复用步骤 |
2.3 测试 Job
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with: python-version: "3.12"
- run: pip install -r requirements.txt
- run: pytest tests/ -v
2.4 构建和推送
flowchart
A[Build] --> B[Login to Registry]
B --> C[Build Image]
C --> D[Push Image]
D --> E[Tag with commit SHA]
2.5 Secrets 管理
flowchart
A[GitHub Secrets] --> B[Environment Variables]
B --> C[CI/CD Pipeline]
C --> D[Deployment]
本章小结
- Workflow:Push/PR 触发
- Test Job:lint + pytest
- Build Job:构建 + 推送镜像
- Secrets:环境变量安全注入
本章提示词模板
生成 CI/CD 配置
为 FastAPI 项目生成 GitHub Actions CI/CD:
需求:
1. Push main → 测试 + 构建 + 部署
2. PR → 预览环境
3. 环境变量使用 Secrets
请生成完整的 workflow 文件。
继续阅读:第三章:生产部署