Chuyển tới nội dung chính

GitHub Actions Cheatsheet

Tra cứu nhanh cấu trúc workflow, trigger, reusable workflow (workflow_call), caching và bảo mật secrets cho CI/CD trên GitHub.

Khung CI Workflow cơ bản (.github/workflows/ci.yml)​

name: CI

on:
pull_request:
branches: [main]
workflow_call:

permissions:
contents: read

jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 22
cache: npm
- run: npm ci
- run: npm run build

Các Trigger phổ biến (on:)​

on:
push:
branches: [main]
paths: ["docs/**", "src/**"] # Chỉ chạy khi các đường dẫn này thay đổi
pull_request:
types: [opened, edited, synchronize, reopened]
workflow_dispatch: # Cho phép chạy thủ công trên GitHub UI
inputs:
version:
description: "Version to deploy"
required: false
schedule:
- cron: "0 2 * * 1" # Chạy định kỳ (UTC)
workflow_call: # Gọi từ workflow khác (reusable)

Pattern CI → Release → Deploy với Reusable Workflow​

Dùng workflow_call để chuỗi hóa pipeline mà không cần tạo Personal Access Token (PAT) khi semantic-release đẩy tag bằng GITHUB_TOKEN:

jobs:
ci:
uses: ./.github/workflows/ci.yml

release:
needs: ci
runs-on: ubuntu-latest
outputs:
released: ${{ steps.rel.outputs.released }}
steps:
- id: rel
run: echo "released=true" >> "$GITHUB_OUTPUT"

deploy:
needs: release
if: needs.release.outputs.released == 'true'
uses: ./.github/workflows/deploy.yml
secrets: inherit

Bảo mật & Best Practices​

  • Luôn khai báo permissions ở mức tối thiểu (Least Privilege) ở đầu workflow hoặc từng job.
  • Dùng GitHub Environments (ví dụ production, release) để cô lập secrets deploy và cấu hình approval/branch rule.
  • Chặn chạy trùng khi push liên tiếp bằng concurrency:
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true

Lệnh gh theo dõi Actions​

gh run list -L 10 # Xem 10 lần chạy gần nhất
gh run watch <run-id> # Theo dõi trực tiếp trên terminal
gh run view <run-id> --log-failed # Xem log các bước bị lỗi
gh workflow run deploy.yml # Kích hoạt workflow_dispatch thủ công

Tham khảo​