my-notes

GitHub_Actions

1 min read

GitHub Actions

Automate workflows directly in your repository.


πŸ“ Workflow Location

.github/workflows/
β”œβ”€β”€ ci.yml
β”œβ”€β”€ deploy.yml
└── test.yml

πŸ“Š Workflow Structure

graph TD
    A[Workflow] --> B[Event Trigger]
    A --> C[Jobs]
    C --> D[Steps]
    D --> E[Actions or Commands]

πŸš€ Basic Workflow

Create .github/workflows/ci.yml:

name: CI

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

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - run: npm install
      - run: npm test

πŸ“‹ Event Triggers

On Push

on:
  push:
    branches: [main, develop]

Runs on push to specified branches.


On Pull Request

on:
  pull_request:
    branches: [main]

Runs on PRs to main.


Scheduled

on:
  schedule:
    - cron: "0 0 * * *"

Runs daily at midnight UTC.


Manual Dispatch

on:
  workflow_dispatch:
    inputs:
      environment:
        description: "Deploy environment"
        required: true
        default: "staging"

Manually trigger with inputs.


πŸƒ Jobs

Single Job

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - run: npm test

Basic job structure.


Multiple Jobs

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - run: npm test

  build:
    runs-on: ubuntu-latest
    needs: test
    steps:
      - run: npm run build

Build depends on test passing.


Matrix Strategy

jobs:
  test:
    strategy:
      matrix:
        node: [16, 18, 20]
        os: [ubuntu-latest, windows-latest]
    runs-on: ${{ matrix.os }}
    steps:
      - uses: actions/setup-node@v4
        with:
          node-version: ${{ matrix.node }}

Runs on multiple Node versions and OS.


πŸ“¦ Common Actions

Checkout Code

- uses: actions/checkout@v4

Checks out your repository.


Setup Node.js

- uses: actions/setup-node@v4
  with:
    node-version: "20"
    cache: "npm"

Sets up Node with caching.


Setup Python

- uses: actions/setup-python@v5
  with:
    python-version: "3.11"

Sets up Python.


Cache Dependencies

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

Caches npm dependencies.


πŸ”§ CLI Commands

List Workflows

gh workflow list

Shows all workflows.


Run Workflow

gh workflow run workflow-name.yml

Manually triggers workflow.


View Run

gh run view

Shows recent run details.


Watch Run

gh run watch

Live-watch a running workflow.


List Runs

gh run list

Shows recent workflow runs.


View Logs

gh run view --log

Shows logs for a run.


πŸ’‘ Tips

Test Locally

Use act to test GitHub Actions locally.

Reuse Workflows

Use workflow_call for reusable workflows.



#github #actions #cicd #automation

Built with mdgarden