GitHub Actions CI

Continuous Integration (CI) and Continuous Delivery/Deployment (CD) have become indispensable practices in modern software development. They help teams deliver code changes more frequently and reliably by automating the build, test, and deployment phases. Among the many tools available, GitHub Actions stands out for its deep integration with the GitHub ecosystem, offering a powerful and flexible way to automate virtually any aspect of your development workflow directly within your repository.

What is GitHub Actions?

GitHub Actions is an event-driven automation platform that allows you to automate tasks directly in your GitHub repository. These tasks are defined in workflows, which are YAML files stored in the .github/workflows directory of your repository. When a specific event occurs (e.g., a push to a branch, a pull request opening, a scheduled time), GitHub Actions executes the workflow.

Core Concepts

To effectively use GitHub Actions, understanding its core components is crucial:

  • Workflow: A configurable automated process made up of one or more jobs. Workflows are defined in YAML files and triggered by events.
  • Event: A specific activity in a repository that triggers a workflow. Common events include push, pull_request, schedule, workflow_dispatch (manual trigger), and issues.
  • Job: A set of steps that execute on the same runner. Each job runs independently in parallel by default, but you can configure dependencies.
  • Step: An individual task within a job. A step can be a shell command, a script, or an action.
  • Action: The smallest portable building block of a workflow. Actions are reusable units of code, often created by the community or GitHub, that perform specific tasks (e.g., checking out code, setting up Node.js, publishing to a registry).
  • Runner: A server that runs your workflow. GitHub provides hosted runners (Ubuntu, Windows, macOS), or you can host your own self-hosted runners.

Creating Your First Workflow: Build and Test

Let's create a simple workflow that builds a Node.js project and runs its tests whenever code is pushed to the main branch or a pull request is opened.

Create a file named .github/workflows/ci.yml in your repository:

YAML:
name: Node.js CI

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

jobs:
  build-and-test:
    runs-on: ubuntu-latest

    strategy:
      matrix:
        node-version: [16.x, 18.x, 20.x]

    steps:
    - uses: actions/checkout@v4
      with:
        fetch-depth: 0 # Fetches all history for all branches and tags

    - name: Use Node.js ${{ matrix.node-version }}
      uses: actions/setup-node@v4
      with:
        node-version: ${{ matrix.node-version }}
        cache: 'npm' # Caches npm dependencies to speed up subsequent runs

    - name: Install dependencies
      run: npm ci

    - name: Run tests
      run: npm test

Explanation:

  • name: Node.js CI: The name of your workflow, visible in the GitHub Actions tab.
  • on: push, pull_request: Specifies the events that trigger this workflow. Here, it runs on pushes to main and pull requests targeting main.
  • jobs:: Defines the jobs in the workflow.
  • build-and-test:: The ID of our single job.
  • runs-on: ubuntu-latest: Specifies that this job will run on the latest Ubuntu-hosted runner.
  • strategy: matrix:: This is powerful! It allows you to run the same job multiple times with different configurations. Here, it will run the build-and-test job for Node.js versions 16.x, 18.x, and 20.x concurrently.
  • steps:: The sequence of tasks for the job.
* uses: actions/checkout@v4: This action checks out your repository code onto the runner.
* uses: actions/setup-node@v4: This action sets up the specified Node.js version. cache: 'npm' is an optimization that caches node_modules to speed up npm ci on subsequent runs.
* run: npm ci: Executes the npm ci command (clean install) to install dependencies.
* run: npm test: Executes the npm test command to run your project's tests.

Advanced Features and Best Practices

1. Secrets: Store sensitive information (API keys, tokens, passwords) as encrypted secrets in your repository settings. Access them in workflows using secrets.YOUR_SECRET_NAME.

Code:
yaml
    - name: Deploy to Staging
      env:
        AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
        AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
      run: aws s3 sync build/ s3://your-staging-bucket

2. Artifacts: Use actions/upload-artifact and actions/download-artifact to persist data between jobs or download build outputs after a workflow run. This is crucial for passing build artifacts from a build job to a deployment job.

Code:
yaml
    # In a build job
    - name: Upload build artifact
      uses: actions/upload-artifact@v4
      with:
        name: my-app-build
        path: build/

    # In a deployment job (after the build job completes)
    - name: Download build artifact
      uses: actions/download-artifact@v4
      with:
        name: my-app-build
        path: build/

3. Environment Variables: Define custom environment variables at the workflow, job, or step level using the env keyword.

Code:
yaml
    jobs:
      my-job:
        runs-on: ubuntu-latest
        env:
          MY_GLOBAL_VAR: "workflow-level"
        steps:
        - name: Step with specific env var
          env:
            MY_STEP_VAR: "step-level"
          run: echo "Global: $MY_GLOBAL_VAR, Step: $MY_STEP_VAR"

4. Conditional Execution: Use if conditions to control when jobs or steps run.

Code:
yaml
    - name: Deploy only on main branch pushes
      if: github.ref == 'refs/heads/main' && github.event_name == 'push'
      run: deploy_script.sh

5. Job Dependencies: Use needs to specify that a job depends on the successful completion of another job.

Code:
yaml
    jobs:
      build:
        runs-on: ubuntu-latest
        steps: [...]
      test:
        runs-on: ubuntu-latest
        needs: build # This job will run only after 'build' completes successfully
        steps: [...]
      deploy:
        runs-on: ubuntu-latest
        needs: [build, test] # This job runs only after both 'build' and 'test' complete
        steps: [...]

6. Reusable Workflows: For complex projects or monorepos, you can define reusable workflows to avoid duplication and enforce consistency.

Code:
yaml
    # .github/workflows/reusable-build.yml
    on:
      workflow_call:
        inputs:
          node_version:
            required: true
            type: string
    jobs:
      build:
        runs-on: ubuntu-latest
        steps:
          - uses: actions/setup-node@v4
            with:
              node-version: ${{ inputs.node_version }}
          - run: npm install && npm build

    # .github/workflows/main.yml
    on: push
    jobs:
      call-build:
        uses: ./.github/workflows/reusable-build.yml
        with:
          node_version: '20.x'

GitHub Actions offers a robust and highly customizable platform for automating your CI/CD pipelines. By leveraging its features, you can significantly streamline your development process, improve code quality, and accelerate delivery. Experiment with different actions, explore the marketplace for community-contributed actions, and tailor your workflows to fit your project's unique needs.
 

Related Threads

Who Read This Thread (Total Members: 1)

Personalization

Style editor

Settings Colours

  • Mobile users cannot use these functions.

    Alternate header

    You can easily choose the alternate header layout for a different look.

    View Mode Selection

    Switch between full screen and narrow screen modes.

    Grid View

    Browse content easily with grid mode and get a tidy look.

    Image Grid Mode

    Display your content in a tidy and visually rich way with background images.

    Close Sidebar

    Create a wider working area by hiding the sidebar.

    Sticky Sidebar

    Keep constant access by pinning the sidebar and manage your content easily.

    Box view

    You can add a box-style frame to the sides of your style or remove the existing frame. Applies to resolutions above 1300px.

    Corner Rounding Control

    Customize the look as you like by turning the corner rounding effect on and off.

  • Choose your colour

    Choose the colour that reflects your style and achieve aesthetic harmony.

Back
QR Code