2026年2月28日

GitHub Actions 入门 - 自动化 CI/CD 工作流

GitHub Actions 是 GitHub 提供的持续集成和持续部署(CI/CD)服务,可以自动化你的软件开发工作流程。

GitHub Actions 简介

什么是 GitHub Actions

GitHub Actions 是一个自动化平台,可以:

  • 自动构建和测试代码
  • 自动部署应用
  • 执行定时任务
  • 响应 GitHub 事件

核心概念

概念 说明
Workflow 工作流,自动化流程
Event 触发事件
Job 任务,工作流中的步骤集合
Step 步骤,任务中的具体操作
Action 可复用的操作单元
Runner 执行任务的虚拟机

免费额度

类型 免费额度
公开仓库 无限制
私有仓库 2000 分钟/月

工作流配置

创建工作流

在仓库中创建 .github/workflows/ 目录,添加 YAML 文件:

# .github/workflows/main.yml
name: CI

on:
  push:
    branches: [ main ]
  pull_request:
    branches: [ main ]

jobs:
  build:
    runs-on: ubuntu-latest
    
    steps:
    - uses: actions/checkout@v4
    
    - name: Setup Node.js
      uses: actions/setup-node@v4
      with:
        node-version: '20'
    
    - name: Install dependencies
      run: npm ci
    
    - name: Run tests
      run: npm test

触发事件

推送触发

on:
  push:
    branches: [ main, dev ]
    paths:
      - 'src/**'
      - 'package.json'

定时触发

on:
  schedule:
    - cron: '0 0 * * *'  # 每天 UTC 0点

手动触发

on:
  workflow_dispatch:
    inputs:
      environment:
        description: '部署环境'
        required: true
        default: 'staging'

其他事件

on:
  issues:
    types: [opened]
  pull_request:
    types: [opened, closed]
  release:
    types: [published]

Jobs 配置

基础配置

jobs:
  build:
    runs-on: ubuntu-latest
    timeout-minutes: 30
    continue-on-error: false

运行环境

环境 说明
ubuntu-latest Ubuntu 最新版
ubuntu-22.04 Ubuntu 22.04
windows-latest Windows 最新版
macos-latest macOS 最新版

矩阵构建

jobs:
  build:
    runs-on: ${{ matrix.os }}
    strategy:
      matrix:
        os: [ubuntu-latest, windows-latest, macos-latest]
        node: [18, 20, 22]

依赖关系

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - run: echo "Building..."
  
  test:
    needs: build
    runs-on: ubuntu-latest
    steps:
      - run: echo "Testing..."
  
  deploy:
    needs: [build, test]
    runs-on: ubuntu-latest
    steps:
      - run: echo "Deploying..."

Steps 配置

使用 Action

steps:
  - name: Checkout
    uses: actions/checkout@v4
  
  - name: Setup Node.js
    uses: actions/setup-node@v4
    with:
      node-version: '20'
      cache: 'npm'

执行命令

steps:
  - name: Install
    run: npm install
  
  - name: Build
    run: |
      npm run build
      echo "Build completed"
  
  - name: Test
    run: npm test
    shell: bash

条件执行

steps:
  - name: Deploy to production
    if: github.ref == 'refs/heads/main'
    run: npm run deploy:prod
  
  - name: Deploy to staging
    if: github.ref == 'refs/heads/dev'
    run: npm run deploy:staging

环境变量与密钥

环境变量

env:
  NODE_ENV: production
  API_URL: https://api.example.com

jobs:
  build:
    runs-on: ubuntu-latest
    env:
      DATABASE_URL: ${{ secrets.DATABASE_URL }}
    steps:
      - name: Print env
        run: echo $NODE_ENV

Secrets 配置

  1. 仓库 -> Settings -> Secrets and variables -> Actions
  2. 添加 Repository secrets
steps:
  - name: Deploy
    env:
      API_KEY: ${{ secrets.API_KEY }}
    run: |
      curl -H "Authorization: Bearer $API_KEY" https://api.example.com

变量配置

jobs:
  deploy:
    runs-on: ubuntu-latest
    env:
      ENVIRONMENT: ${{ vars.ENVIRONMENT }}

常用 Actions

actions/checkout

- uses: actions/checkout@v4
  with:
    repository: owner/repo
    ref: main
    token: ${{ secrets.GITHUB_TOKEN }}
    path: ./repo

actions/setup-node

- uses: actions/setup-node@v4
  with:
    node-version: '20'
    cache: 'npm'
    registry-url: 'https://registry.npmjs.org'

actions/cache

- uses: actions/cache@v4
  with:
    path: ~/.npm
    key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
    restore-keys: |
      ${{ runner.os }}-node-

actions/upload-artifact

- uses: actions/upload-artifact@v4
  with:
    name: build-output
    path: dist/
    retention-days: 5

actions/download-artifact

- uses: actions/download-artifact@v4
  with:
    name: build-output
    path: dist/

自动部署示例

部署到 GitHub Pages

name: Deploy to GitHub Pages

on:
  push:
    branches: [ main ]

jobs:
  build-and-deploy:
    runs-on: ubuntu-latest
    
    steps:
    - uses: actions/checkout@v4
    
    - name: Setup Node.js
      uses: actions/setup-node@v4
      with:
        node-version: '20'
        cache: 'npm'
    
    - name: Install and Build
      run: |
        npm ci
        npm run build
    
    - name: Deploy
      uses: peaceiris/actions-gh-pages@v3
      with:
        github_token: ${{ secrets.GITHUB_TOKEN }}
        publish_dir: ./dist

部署到服务器

name: Deploy to Server

on:
  push:
    branches: [ main ]

jobs:
  deploy:
    runs-on: ubuntu-latest
    
    steps:
    - uses: actions/checkout@v4
    
    - name: Deploy via SSH
      uses: appleboy/ssh-action@v1.0.0
      with:
        host: ${{ secrets.HOST }}
        username: ${{ secrets.USERNAME }}
        key: ${{ secrets.SSH_KEY }}
        script: |
          cd /var/www/html
          git pull origin main
          npm install
          npm run build
          pm2 restart app

Docker 构建推送

name: Docker Build and Push

on:
  push:
    branches: [ main ]

jobs:
  docker:
    runs-on: ubuntu-latest
    
    steps:
    - uses: actions/checkout@v4
    
    - name: Login to Docker Hub
      uses: docker/login-action@v3
      with:
        username: ${{ secrets.DOCKER_USERNAME }}
        password: ${{ secrets.DOCKER_PASSWORD }}
    
    - name: Build and Push
      uses: docker/build-push-action@v5
      with:
        context: .
        push: true
        tags: user/app:latest

上下文与表达式

上下文变量

上下文 说明
github GitHub 事件信息
env 环境变量
job 任务信息
steps 步骤输出
runner 运行环境信息
secrets 密钥

常用表达式

# 分支判断
if: github.ref == 'refs/heads/main'

# 事件类型
if: github.event_name == 'push'

# 提交信息
if: contains(github.event.head_commit.message, '[deploy]')

# 文件变更
if: contains(github.event.commits[*].modified, 'src/')

# 步骤输出
if: steps.build.outcome == 'success'

输出变量

jobs:
  build:
    runs-on: ubuntu-latest
    outputs:
      version: ${{ steps.get_version.outputs.version }}
    
    steps:
    - id: get_version
      run: echo "version=1.0.0" >> $GITHUB_OUTPUT
  
  deploy:
    needs: build
    runs-on: ubuntu-latest
    steps:
    - run: echo ${{ needs.build.outputs.version }}

工作流模板

Node.js CI

name: Node.js CI

on:
  push:
    branches: [ main ]
  pull_request:
    branches: [ main ]

jobs:
  build:
    runs-on: ubuntu-latest
    
    strategy:
      matrix:
        node-version: [18.x, 20.x]
    
    steps:
    - uses: actions/checkout@v4
    
    - name: Use Node.js ${{ matrix.node-version }}
      uses: actions/setup-node@v4
      with:
        node-version: ${{ matrix.node-version }}
        cache: 'npm'
    
    - run: npm ci
    - run: npm run build --if-present
    - run: npm test

Python CI

name: Python CI

on: [push, pull_request]

jobs:
  build:
    runs-on: ubuntu-latest
    
    steps:
    - uses: actions/checkout@v4
    
    - name: Set up Python
      uses: actions/setup-python@v5
      with:
        python-version: '3.11'
        cache: 'pip'
    
    - name: Install dependencies
      run: |
        pip install -r requirements.txt
    
    - name: Run tests
      run: |
        python -m pytest

调试技巧

查看日志

在 Actions 页面查看详细日志

启用调试

env:
  ACTIONS_STEP_DEBUG: true
  ACTIONS_RUNNER_DEBUG: true

SSH 调试

- name: SSH Debug
  uses: mxschmitt/action-tmate@v3

最佳实践

安全建议

  1. 使用 Secrets 存储敏感信息
  2. 限制 GITHUB_TOKEN 权限
  3. 使用特定版本的 Action
  4. 审查第三方 Action

性能优化

  1. 使用缓存
  2. 并行执行任务
  3. 减少不必要的步骤
  4. 使用矩阵构建

配置建议

# 使用特定版本
- uses: actions/checkout@v4

# 使用缓存
- uses: actions/setup-node@v4
  with:
    cache: 'npm'

# 设置超时
jobs:
  build:
    timeout-minutes: 10

总结

GitHub Actions 是强大的 CI/CD 工具:

  • 与 GitHub 深度集成
  • 免费额度充足
  • 丰富的 Action 生态
  • 配置简单灵活

适合:

  • 自动化测试
  • 自动部署
  • 定时任务
  • 代码质量检查

掌握 GitHub Actions 可以大幅提升开发效率。