GitHub Actions
workflow-triggers、secrets、runners、marketplace-actions。
35 分钟
GitHub Actions
GitHub Actions 在仓库内用 YAML 定义 CI/CD:push/PR 时自动测试、构建、部署。本课对应 git-github 路线图 的 workflow-triggers、secrets、runners、marketplace-actions。
系统学习见 github-actions-essentials;本地 Git 触发 push 见 git-essentials 与 ghg-pr。
学习目标
- 编写最小 workflow:触发器 + job + steps
- 配置 secrets 与 PR 安全边界
- 了解 hosted runner 与 Marketplace actions
第一个 Workflow
文件路径:.github/workflows/ci.yml
name: CI
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: "20"
cache: "npm"
- run: npm ci
- run: npm test
push 到 main 或针对 main 的 PR 都会跑 test job。
触发器要点
on:
push:
paths:
- "src/**"
- ".github/workflows/**"
pull_request:
types: [opened, synchronize, reopened]
workflow_dispatch: # 手动触发
paths 过滤无关改动,节省分钟数(与 Actions track PR 课一致)。
Secrets 与权限
Settings → Secrets and variables → Actions 添加 NPM_TOKEN 等。
- run: npm publish
env:
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
Fork PR 默认拿不到仓库 secrets,防止恶意 PR 外泄密钥。需要 CI 对 fork 友好时,查阅官方 pull_request_target 文档并评估安全风险。
Runners
| 类型 | 说明 |
|---|---|
| GitHub-hosted | ubuntu-latest / windows-latest / macos-latest |
| Self-hosted | 自建机器,适合内网或特殊硬件 |
runs-on: self-hosted
Marketplace Actions
uses: actions/checkout@v4 来自官方;第三方如 。 pin 到 (),定期关注安全公告。