GitHub Actions 自动化
大约 7 分钟约 2056 字
GitHub Actions 自动化
简介
GitHub Actions 是 GitHub 提供的内置 CI/CD 平台,通过 YAML 工作流文件定义自动化流程。它深度集成 GitHub 仓库,支持丰富的 Actions 市场场、矩阵构建、密钥管理以及多种部署目标。开发者无需维护额外的 CI 服务器,即可实现从代码检查、测试、构建到部署的全自动化。
特点
Workflow YAML 基础
基本工作流
# .github/workflows/ci.yml
name: CI Pipeline
on:
push:
branches: [main, develop]
pull_request:
branches: [main]
env:
DOTNET_VERSION: '8.0.x'
APP_NAME: 'myapp'
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup .NET
uses: actions/setup-dotnet@v4
with:
dotnet-version: ${{ env.DOTNET_VERSION }}
- name: Restore dependencies
run: dotnet restore
- name: Build
run: dotnet build -c Release --no-restore
- name: Test
run: dotnet test -c Release --no-build --logger "trx;LogFileName=test-results.trx"
- name: Publish Test Results
uses: dorny/test-reporter@v1
if: always()
with:
name: Test Results
path: '**/test-results.trx'
reporter: dotnet-trx
- name: Publish
run: dotnet publish src/Api/Api.csproj -c Release -o publish/
- name: Upload artifact
uses: actions/upload-artifact@v4
with:
name: publish-${{ github.sha }}
path: publish/
retention-days: 7Node.js 项目工作流
# .github/workflows/node-ci.yml
name: Node CI/CD
on:
push:
branches: [main]
pull_request:
jobs:
build:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [18, 20, 22]
steps:
- uses: actions/checkout@v4
- name: Setup Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node-version }}
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Lint
run: npm run lint
- name: Test
run: npm test -- --coverage
- name: Build
run: npm run build
- name: Upload coverage
uses: codecov/codecov-action@v4
with:
token: ${{ secrets.CODECOV_TOKEN }}Actions 市场使用
常用 Actions 组合
# .github/workflows/release.yml
name: Release Pipeline
on:
push:
tags:
- 'v*'
jobs:
release:
runs-on: ubuntu-latest
steps:
# 检出代码(含完整历史,用于版本号生成)
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
# 设置 .NET 环境
- name: Setup .NET
uses: actions/setup-dotnet@v4
with:
dotnet-version: '8.0.x'
# 登录 Docker 镜像仓库
- name: Login to Registry
uses: docker/login-action@v3
with:
registry: registry.example.com
username: ${{ secrets.REGISTRY_USER }}
password: ${{ secrets.REGISTRY_PASS }}
# 设置 Docker Buildx(支持多平台构建)
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
# 构建并推送 Docker 镜像
- name: Build and Push
uses: docker/build-push-action@v5
with:
context: .
push: true
tags: |
registry.example.com/myapp:${{ github.ref_name }}
registry.example.com/myapp:latest
cache-from: type=gha
cache-to: type=gha,mode=max
# 创建 GitHub Release
- name: Create Release
uses: softprops/action-gh-release@v2
with:
generate_release_notes: true
draft: false
prerelease: ${{ contains(github.ref_name, 'rc') || contains(github.ref_name, 'beta') }}缓存优化
# .github/workflows/cached-build.yml
name: Cached Build
on: [push]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
# 缓存 NuGet 包
- name: Cache NuGet packages
uses: actions/cache@v4
with:
path: ~/.nuget/packages
key: ${{ runner.os }}-nuget-${{ hashFiles('**/*.csproj') }}
restore-keys: |
${{ runner.os }}-nuget-
# 缓存 npm 包
- name: Cache npm
uses: actions/cache@v4
with:
path: |
~/.npm
node_modules
key: ${{ runner.os }}-npm-${{ hashFiles('package-lock.json') }}
restore-keys: |
${{ runner.os }}-npm-
- name: Restore and Build
run: |
dotnet restore
dotnet build -c Release矩阵构建
跨平台与多版本测试
# .github/workflows/matrix.yml
name: Matrix Build
on: [push, pull_request]
jobs:
test:
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, windows-latest, macos-latest]
dotnet-version: ['7.0.x', '8.0.x']
exclude:
- os: macos-latest
dotnet-version: '7.0.x'
steps:
- uses: actions/checkout@v4
- name: Setup .NET ${{ matrix.dotnet-version }}
uses: actions/setup-dotnet@v4
with:
dotnet-version: ${{ matrix.dotnet-version }}
- name: Restore
run: dotnet restore
- name: Build
run: dotnet build --no-restore
- name: Test
run: dotnet test --no-build --logger "GitHubActions"动态矩阵(构建多个服务)
# .github/workflows/multi-service.yml
name: Multi-Service Build
on: [push]
jobs:
detect-changes:
runs-on: ubuntu-latest
outputs:
services: ${{ steps.filter.outputs.changes }}
steps:
- uses: actions/checkout@v4
- name: Detect changed services
uses: dorny/paths-filter@v3
id: filter
with:
filters: |
api:
- 'src/Api/**'
worker:
- 'src/Worker/**'
frontend:
- 'src/Frontend/**'
build:
needs: detect-changes
if: ${{ needs.detect-changes.outputs.services != '[]' }}
runs-on: ubuntu-latest
strategy:
matrix:
service: ${{ fromJson(needs.detect-changes.outputs.services) }}
steps:
- uses: actions/checkout@v4
- name: Build ${{ matrix.service }}
run: |
echo "Building ${{ matrix.service }}..."
docker build -t myapp-${{ matrix.service }}:latest src/${{ matrix.service }}/Secrets 管理
使用 GitHub Secrets
# .github/workflows/deploy.yml
name: Deploy
on:
push:
branches: [main]
jobs:
deploy:
runs-on: ubuntu-latest
environment: production
steps:
- uses: actions/checkout@v4
- name: Configure kubectl
run: |
mkdir -p $HOME/.kube
echo "${{ secrets.KUBE_CONFIG }}" | base64 -d > $HOME/.kube/config
- name: Deploy to Kubernetes
run: |
kubectl set image deployment/myapp \
myapp=registry.example.com/myapp:${{ github.sha }} \
-n production
- name: Verify deployment
run: |
kubectl rollout status deployment/myapp -n production --timeout=120s
- name: Rollback on failure
if: failure()
run: |
kubectl rollout undo deployment/myapp -n production使用 Environment 和 Protection Rules
# .github/workflows/staged-deploy.yml
name: Staged Deploy
on:
push:
branches: [main]
jobs:
deploy-staging:
runs-on: ubuntu-latest
environment: staging
steps:
- uses: actions/checkout@v4
- name: Deploy to Staging
run: echo "Deploying to staging..."
env:
DEPLOY_URL: ${{ secrets.DEPLOY_URL }}
API_KEY: ${{ secrets.API_KEY }}
deploy-production:
needs: deploy-staging
runs-on: ubuntu-latest
environment:
name: production
# 生产环境需要审批
# 在 GitHub 仓库 Settings > Environments 中配置
# Required reviewers: admin, lead
steps:
- uses: actions/checkout@v4
- name: Deploy to Production
run: echo "Deploying to production..."部署工作流
Docker 镜像构建与部署
# .github/workflows/docker-deploy.yml
name: Docker Build & Deploy
on:
push:
branches: [main]
tags: ['v*']
env:
REGISTRY: ghcr.io
IMAGE_NAME: ${{ github.repository }}
jobs:
build-and-push:
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Login to GHCR
uses: docker/login-action@v3
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Extract metadata
id: meta
uses: docker/metadata-action@v5
with:
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
tags: |
type=ref,event=branch
type=ref,event=pr
type=semver,pattern={{version}}
type=semver,pattern={{major}}.{{minor}}
type=sha
- name: Build and push
uses: docker/build-push-action@v5
with:
context: .
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
cache-from: type=gha
cache-to: type=gha,mode=max
platforms: linux/amd64,linux/arm64
deploy:
needs: build-and-push
runs-on: ubuntu-latest
if: startsWith(github.ref, 'refs/tags/v')
environment: production
steps:
- name: Deploy
run: |
echo "Deploying image with tag ${{ github.ref_name }}"
# 部署到 Kubernetes / AWS / Azure 等优点
缺点
总结
GitHub Actions 为开发者提供了开箱即用的 CI/CD 能力,通过 YAML 工作流文件即可定义完整的自动化流程。利用 Actions 市场的丰富组件、矩阵构建的并行能力、Environment 的审批保护机制以及与 GitHub 生态的深度集成,可以快速构建从代码检查到生产部署的完整交付流水线。建议充分利用缓存机制加速构建、使用矩阵构建确保兼容性,并通过 Environment Protection Rules 为生产部署增加安全门禁。
关键知识点
- DevOps 主题的核心是让交付更快、更稳、更可审计。
- 自动化不是把命令脚本化,而是把失败、回滚、权限和观测一起设计进去。
- 生产链路必须明确制品、环境、凭据、配置和责任边界。
项目落地视角
- 把流水线拆成构建、测试、制品、部署、验证和回滚几个阶段。
- 为关键步骤补齐日志、指标、通知和人工兜底点。
- 定期演练扩容、回滚、故障注入和灾备切换。
常见误区
- 只关注部署成功,不关注失败恢复和审计追踪。
- 把环境差异藏在临时脚本或人工操作里。
- 上线频率高了以后,没有标准化制品和配置管理。
进阶路线
- 继续补齐 GitOps、可观测性、平台工程和成本治理。
- 把主题和应用架构、安全、权限、备份恢复联动起来理解。
- 形成团队级平台能力,而不是每个项目重复造轮子。
适用场景
- 当你准备把《GitHub Actions 自动化》真正落到项目里时,最适合先在一个独立模块或最小样例里验证关键路径。
- 适合构建自动化交付、基础设施治理、监控告警和生产发布体系。
- 当团队规模扩大、发布频率提升或环境变多时,这类主题会显著影响交付效率。
落地建议
- 所有自动化流程尽量做到幂等、可审计、可回滚。
- 把制品、变量、凭据和执行权限分层管理。
- 定期演练扩容、回滚、密钥轮换和灾备恢复。
排错清单
- 先定位失败发生在代码、构建、制品、环境还是权限层。
- 检查流水线变量、凭据、镜像标签和目标环境配置是否一致。
- 如果问题偶发,重点看并发发布、资源争抢和外部依赖抖动。
复盘问题
- 如果把《GitHub Actions 自动化》放进你的当前项目,最先要验证的输入、输出和失败路径分别是什么?
- 《GitHub Actions 自动化》最容易在什么规模、什么边界条件下暴露问题?你会用什么指标或日志去确认?
- 相比默认实现或替代方案,采用《GitHub Actions 自动化》最大的收益和代价分别是什么?
