GitHub Actions自动化
2025/7/17...大约 6 分钟
GitHub Actions自动化
GitHub Actions是GitHub提供的持续集成/持续部署(CI/CD)服务,它允许你自动化软件开发工作流程,如构建、测试和部署。
GitHub Actions基础
核心概念
- 工作流(Workflow):由一个或多个作业组成的自动化过程,由事件触发
- 事件(Event):触发工作流的特定活动,如push、pull request或定时任务
- 作业(Job):工作流中的一组步骤,在同一运行器上执行
- 步骤(Step):可以运行命令或动作的单个任务
- 动作(Action):可重用的工作单元,可以是自定义的或来自GitHub Marketplace
- 运行器(Runner):执行工作流的服务器,可以是GitHub提供的或自托管的
工作流文件结构
工作流定义在仓库的.github/workflows
目录下的YAML文件中:
name: CI/CD Pipeline
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
schedule:
- cron: '0 0 * * *' # 每天午夜运行
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Set up Node.js
uses: actions/setup-node@v3
with:
node-version: '16'
- name: Install dependencies
run: npm ci
- name: Run tests
run: npm test
常用触发器
on:
# 推送到指定分支时触发
push:
branches: [ main, develop ]
paths-ignore: [ 'docs/**', '**.md' ]
# 创建或更新PR时触发
pull_request:
types: [ opened, synchronize ]
# 手动触发
workflow_dispatch:
inputs:
environment:
description: 'Environment to deploy to'
required: true
default: 'staging'
# 定时触发
schedule:
- cron: '0 0 * * *' # 每天午夜运行
# 其他工作流完成时触发
workflow_run:
workflows: [ "Build" ]
types: [ completed ]
CI/CD配置与使用
持续集成(CI)配置
以下是一个典型的CI工作流,用于构建和测试代码:
name: Continuous Integration
on:
push:
branches: [ main, develop ]
pull_request:
branches: [ main ]
jobs:
test:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [14.x, 16.x, 18.x]
steps:
- uses: actions/checkout@v3
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v3
with:
node-version: ${{ matrix.node-version }}
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Lint code
run: npm run lint
- name: Run unit tests
run: npm test
- name: Run integration tests
run: npm run test:integration
- name: Upload coverage reports
uses: codecov/codecov-action@v3
with:
token: ${{ secrets.CODECOV_TOKEN }}
持续部署(CD)配置
以下是一个部署到不同环境的CD工作流示例:
name: Continuous Deployment
on:
push:
branches: [ main ]
workflow_dispatch:
inputs:
environment:
description: 'Environment to deploy to'
required: true
default: 'staging'
type: choice
options:
- staging
- production
jobs:
deploy:
runs-on: ubuntu-latest
environment: ${{ github.event.inputs.environment || 'staging' }}
steps:
- uses: actions/checkout@v3
- name: Set up Node.js
uses: actions/setup-node@v3
with:
node-version: '16'
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Build application
run: npm run build
- name: Deploy to staging
if: ${{ github.event.inputs.environment == 'staging' || github.event.inputs.environment == null }}
uses: some-deployment-action@v1
with:
target: 'staging'
token: ${{ secrets.DEPLOY_TOKEN }}
- name: Deploy to production
if: ${{ github.event.inputs.environment == 'production' }}
uses: some-deployment-action@v1
with:
target: 'production'
token: ${{ secrets.DEPLOY_TOKEN }}
环境和密钥管理
GitHub Actions提供了安全存储和使用敏感信息的方法:
仓库密钥:
- 在仓库设置中的"Secrets and variables" > "Actions"中添加
- 在工作流中使用:
${{ secrets.SECRET_NAME }}
环境密钥:
- 创建环境并添加特定于环境的密钥
- 在工作流中指定环境:
environment: production
变量:
- 存储非敏感配置信息
- 可在仓库或环境级别设置
- 在工作流中使用:
${{ vars.VARIABLE_NAME }}
自动化测试与部署
自动化测试策略
- 矩阵测试:在多个环境或配置上运行测试
jobs:
test:
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ubuntu-latest, windows-latest, macos-latest]
node-version: [14.x, 16.x, 18.x]
- 并行测试:将测试分割为多个作业以加速执行
jobs:
unit-tests:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- run: npm test:unit
integration-tests:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- run: npm test:integration
- 测试报告:生成和发布测试报告
- name: Run tests
run: npm test -- --coverage
- name: Upload test results
uses: actions/upload-artifact@v3
with:
name: test-results
path: coverage/
自动化部署方案
- 部署到GitHub Pages:
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Build
run: npm run build
- name: Deploy to GitHub Pages
uses: JamesIves/github-pages-deploy-action@v4
with:
folder: build
- 部署到云服务提供商:
# AWS部署示例
- name: Configure AWS credentials
uses: aws-actions/configure-aws-credentials@v1
with:
aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
aws-region: us-east-1
- name: Deploy to S3
run: aws s3 sync ./build s3://my-bucket/
- name: Invalidate CloudFront
run: aws cloudfront create-invalidation --distribution-id ${{ secrets.CF_DISTRIBUTION_ID }} --paths "/*"
- 使用SSH部署到服务器:
- name: Set up SSH
uses: webfactory/ssh-agent@v0.7.0
with:
ssh-private-key: ${{ secrets.SSH_PRIVATE_KEY }}
- name: Deploy to server
run: |
scp -r ./build/* user@server:/path/to/deployment
ssh user@server 'cd /path/to/deployment && ./restart.sh'
常用Actions模板
JavaScript/Node.js项目
name: Node.js CI/CD
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
jobs:
build-and-test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Use Node.js
uses: actions/setup-node@v3
with:
node-version: '16'
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Lint
run: npm run lint
- name: Test
run: npm test
- name: Build
run: npm run build
- name: Upload build artifacts
uses: actions/upload-artifact@v3
with:
name: build
path: build/
Python项目
name: Python CI
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
jobs:
test:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: [3.8, 3.9, 3.10]
steps:
- uses: actions/checkout@v3
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v4
with:
python-version: ${{ matrix.python-version }}
cache: 'pip'
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install flake8 pytest
if [ -f requirements.txt ]; then pip install -r requirements.txt; fi
- name: Lint with flake8
run: flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics
- name: Test with pytest
run: pytest
Docker项目
name: Docker CI/CD
on:
push:
branches: [ main ]
tags: [ 'v*.*.*' ]
pull_request:
branches: [ main ]
jobs:
build-and-push:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v2
- name: Login to DockerHub
if: github.event_name != 'pull_request'
uses: docker/login-action@v2
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Extract metadata
id: meta
uses: docker/metadata-action@v4
with:
images: username/app
tags: |
type=semver,pattern={{version}}
type=ref,event=branch
type=sha
- name: Build and push
uses: docker/build-push-action@v4
with:
context: .
push: ${{ github.event_name != 'pull_request' }}
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
cache-from: type=gha
cache-to: type=gha,mode=max
多语言项目
name: Multi-language CI
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
jobs:
frontend:
runs-on: ubuntu-latest
defaults:
run:
working-directory: ./frontend
steps:
- uses: actions/checkout@v3
- name: Set up Node.js
uses: actions/setup-node@v3
with:
node-version: '16'
cache: 'npm'
cache-dependency-path: './frontend/package-lock.json'
- name: Install dependencies
run: npm ci
- name: Test frontend
run: npm test
backend:
runs-on: ubuntu-latest
defaults:
run:
working-directory: ./backend
steps:
- uses: actions/checkout@v3
- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: '3.10'
cache: 'pip'
cache-dependency-path: './backend/requirements.txt'
- name: Install dependencies
run: pip install -r requirements.txt
- name: Test backend
run: pytest
高级功能与优化
工作流优化技巧
- 缓存依赖:
- name: Cache Node.js modules
uses: actions/cache@v3
with:
path: ~/.npm
key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
restore-keys: |
${{ runner.os }}-node-
- 作业之间共享数据:
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Build
run: npm run build
- name: Upload build
uses: actions/upload-artifact@v3
with:
name: build-files
path: build/
deploy:
needs: build
runs-on: ubuntu-latest
steps:
- name: Download build
uses: actions/download-artifact@v3
with:
name: build-files
path: build
- name: Deploy
run: ./deploy.sh
- 条件执行:
steps:
- name: Deploy to production
if: github.ref == 'refs/heads/main' && github.event_name == 'push'
run: ./deploy-prod.sh
自托管运行器
如果需要特定环境或更多资源,可以设置自托管运行器:
添加自托管运行器:
- 在仓库或组织设置中,点击"Actions" > "Runners" > "New self-hosted runner"
- 按照指示设置运行器
在工作流中使用:
jobs:
build:
runs-on: self-hosted
steps:
- uses: actions/checkout@v3
# 其他步骤...
复用工作流
- 可重用工作流:创建可在多个仓库中使用的工作流
# .github/workflows/reusable.yml
name: Reusable workflow
on:
workflow_call:
inputs:
environment:
required: true
type: string
secrets:
deploy-token:
required: true
jobs:
deploy:
runs-on: ubuntu-latest
environment: ${{ inputs.environment }}
steps:
- uses: actions/checkout@v3
- name: Deploy
run: ./deploy.sh
env:
TOKEN: ${{ secrets.deploy-token }}
- 调用可重用工作流:
jobs:
call-workflow:
uses: ./.github/workflows/reusable.yml
with:
environment: production
secrets:
deploy-token: ${{ secrets.DEPLOY_TOKEN }}
工作流可视化与监控
GitHub Actions仪表板:
- 在仓库的"Actions"选项卡查看所有工作流运行
- 检查详细日志和步骤输出
状态徽章:在README中添加工作流状态徽章

- 通知配置:
- 设置工作流失败时的邮件通知
- 使用Slack或Teams集成发送通知
- name: Slack notification
uses: 8398a7/action-slack@v3
with:
status: ${{ job.status }}
fields: repo,message,commit,author,action,eventName,ref,workflow
env:
SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}
if: always()