← 返回首页
🚀

GitHub Actions:Workflow矩阵构建与自动化

📂 architecture ⏱ 2 min 207 words

GitHub Actions:Workflow矩阵构建与自动化

GitHub Actions核心概念

GitHub Actions是GitHub内置的CI/CD平台,通过YAML配置文件定义工作流,支持事件驱动的自动化流程。

GitHub Event(Push/PR/Schedule)
    → 触发Workflow
        → 执行Job(并行/串行)
            → 运行Step(Action/Script)
                → 产出Artifact/部署

矩阵构建策略

矩阵构建允许在多种环境组合下并行测试:

name: Matrix Build

on: [push, pull_request]

jobs:
  test:
    runs-on: ubuntu-latest
    strategy:
      fail-fast: false
      matrix:
        node-version: [14, 16, 18]
        os: [ubuntu-latest, windows-latest, macos-latest]
        include:
          - node-version: 20
            os: ubuntu-latest
            experimental: true
        exclude:
          - node-version: 14
            os: windows-latest
    
    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'
      
      - run: npm ci
      - run: npm test

复合Action开发

将可复用步骤封装为复合Action,实现跨项目共享:

# .github/actions/setup-project/action.yml
name: 'Setup Project'
description: '安装依赖并配置环境'
inputs:
  node-version:
    description: 'Node.js版本'
    required: false
    default: '18'

runs:
  using: 'composite'
  steps:
    - name: Setup Node.js
      uses: actions/setup-node@v4
      with:
        node-version: ${{ inputs.node-version }}
        cache: 'npm'
    
    - name: Install dependencies
      shell: bash
      run: npm ci --prefer-offline
    
    - name: Build project
      shell: bash
      run: npm run build

自托管Runner配置

# .github/workflows/self-hosted.yml
jobs:
  build:
    runs-on: self-hosted
    steps:
      - uses: actions/checkout@v4
      
      - name: Build on self-hosted runner
        run: |
          docker compose up -d
          npm run build
          docker compose push
        env:
          DOCKER_REGISTRY: ${{ secrets.REGISTRY_URL }}

缓存优化策略

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

安全实践

permissions:
  contents: read
  packages: write
  id-token: write  # OIDC用于云服务认证

jobs:
  deploy:
    environment: production  # 需要审批
    steps:
      - name: OIDC Token
        uses: aws-actions/configure-aws-credentials@v4
        with:
          role-to-assume: arn:aws:iam::123456789012:role/deploy
          aws-region: us-east-1