Skip to Content

GitHub Actions

GitHub Actions là gì?

GitHub Actions là công cụ CI/CD (Continuous Integration/Continuous Deployment) tích hợp sẵn trong GitHub. Cho phép tự động hóa:

  • Build và test code
  • Deploy ứng dụng
  • Tự động review, format code
  • Và nhiều hơn nữa!

Các khái niệm cơ bản

Workflow

File YAML định nghĩa các công việc tự động chạy.

Event

Sự kiện trigger workflow (push, pull_request, schedule…).

Job

Nhóm các steps chạy trên cùng một runner.

Step

Một lệnh hoặc action đơn lẻ.

Runner

Môi trường chạy workflow (Ubuntu, Windows, macOS).

Tạo Workflow đầu tiên

Bước 1: Tạo file workflow

Tạo file .github/workflows/ci.yml:

name: CI on: push: branches: [main] pull_request: branches: [main] jobs: build: runs-on: ubuntu-latest steps: - name: Checkout code uses: actions/checkout@v4 - name: Setup Node.js uses: actions/setup-node@v4 with: node-version: '20' - name: Install dependencies run: npm install - name: Run tests run: npm test

Bước 2: Commit và push

git add .github/workflows/ci.yml git commit -m "ci: add CI workflow" git push

Bước 3: Xem kết quả

  1. Vào tab Actions trên GitHub
  2. Xem workflow đang chạy
  3. Click vào để xem chi tiết

Các Event phổ biến

on: # Khi push push: branches: [main, develop] # Khi tạo PR pull_request: branches: [main] # Chạy theo lịch (cron) schedule: - cron: '0 0 * * *' # Mỗi ngày lúc 00:00 # Chạy thủ công workflow_dispatch:

Ví dụ Workflows

Python CI

name: Python CI on: [push, pull_request] jobs: test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Setup Python uses: actions/setup-python@v5 with: python-version: '3.11' - name: Install dependencies run: | pip install -r requirements.txt pip install pytest - name: Run tests run: pytest

Deploy to GitHub Pages

name: Deploy on: push: branches: [main] jobs: deploy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Setup Node.js uses: actions/setup-node@v4 with: node-version: '20' - name: Build run: | npm install npm run build - name: Deploy to GitHub Pages uses: peaceiris/actions-gh-pages@v4 with: github_token: ${{ secrets.GITHUB_TOKEN }} publish_dir: ./dist

Secrets

Lưu trữ thông tin nhạy cảm:

  1. SettingsSecrets and variablesActions
  2. New repository secret
  3. Sử dụng trong workflow: ${{ secrets.MY_SECRET }}

Marketplace

Tìm Actions có sẵn tại github.com/marketplace :

  • actions/checkout - Checkout code
  • actions/setup-node - Setup Node.js
  • actions/cache - Cache dependencies

Tổng kết

Bạn đã hoàn thành section Git & GitHub! 🎉

Hãy quay lại trang Git & GitHub để xem tổng quan hoặc tiếp tục học các chủ đề khác.

Last updated on