Skip to content
Search

GitHub Actions

lastmod 2025-12-10created 2021-06-2341 edits

Automate your workflow from idea to production

GitHub Actions now makes it easy to automate all your software workflows with world-class CI/CD. Build, test, and deploy your code right from GitHub. Make code reviews, branch management, and issue triaging work the way you want.

Categories

Actions Marketplace

Essential GitHub Actions for open source maintainers

Banned Actions

WARNING

Github Actions projects banned from use for various reasons

tj-actions/changed-files
A popular GitHub Action used to track changes in each branch; a compromised commit led to an attempt to leak CI/CD secrets
Discovered by StepSecurity's Harden-Runner, which is distributing a hardened alternative action, step-security/changed-files, for free

How to clear the cache

Go to the following page and delete it.

https://github.com/<OWNER>/<REPO>/actions/caches

Workflows

A workflow, the top-level concept in GitHub Actions, is simply an automated work process. Workflows are configured with YAML files under the .github/workflows folder in the code repository, and a single code repository can have multiple workflows, that is, multiple YAML files.

Two main things must be defined in a workflow YAML file: the #on and #jobs properties.

name

Workflow name

name: CI

on:
  # ...

jobs:
  # ...

Environment variables

name: Greeting on variable day

on:
  workflow_dispatch

env:
  DAY_OF_WEEK: Monday

services

Background services that must be running beforehand

# ...

jobs:
  test:
    runs-on: ubuntu-latest
    services:
      postgres:
        image: postgres:11
        env:
          POSTGRES_USER: postgres
          POSTGRES_PASSWORD: postgres
          POSTGRES_DB: postgres
        ports: ['5432:5432']
        options: --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5
    steps:
      # ...

on

The on property defines when the workflow runs.

Selecting specific branches

Run when pushing to the main branch or to a branch starting with releases/:

on:
  push:
    branches:
      - 'main'
      - 'releases/**'

jobs:
  # ...(생략)...

Run the workflow only when a push affects specific files

For example, this workflow runs when you push changes to JavaScript files (.js):

on:
  push:
    paths:
      - '**.js'

jobs:
  # ...(생략)...

There is also a paths-ignore filter.

Selecting specific files on specific branches

Think of it as an AND condition.

on:
  push:
    branches:
      - 'releases/**'
    paths:
      - '**.js'

Run the workflow only when specific tags are pushed

For example, this workflow runs when you push a tag starting with v1..

on:
  push:
    tags:
      - v1.**

There is also a tags-ignore filter.

To filter for major version 1 or 2, use v[12].[0-9]+.[0-9]+.

A typical semantic version pattern is:

on:
  push:
    tags:
      - '[0-9]+.[0-9]+.[0-9]+'

cron scheduler

As another example, to run the workflow every day at midnight, configure it as follows.

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

jobs:
  # ...(생략)...

Depending on a specific workflow

When the "tests" workflow has completed:

on:
  workflow_run:
    workflows: ["tests"]
    branches: [main]
    types:
      - completed

jobs:
  # ...(생략)...

Releasing manually from the web

An event is generated when you click the "Create a new release" button to create a new release page.

on:
  release:
    types: [published]

jobs:
  # ...(생략)...

For all event triggers, see here.

Filter pattern cheat sheet

You can use special characters in path, branch, and tag filters.

  • *: Matches zero or more characters, but does not match the / character. For example, Octo* matches Octocat.
  • **: Matches zero or more of any character.
  • ?: Matches zero or one of the preceding character.
  • +: Matches one or more of the preceding character.
  • [] Matches one character listed in the brackets or included in ranges. Ranges can only include a-z, A-Z, and 0-9. For example, the range[0-9a-z] matches any digit or lowercase letter. For example, [CB]at matches Cat or Bat and [1-2]00 matches 100 and 200.
  • !: At the start of a pattern makes it negate previous positive patterns. It has no special meaning if not the first character.

The characters *, [, and ! are special characters in YAML. If you start a pattern with *, [, or !, you must enclose the pattern in quotes. Also, if you use a flow sequence with a pattern containing [ and/or ], the pattern must be enclosed in quotes.

# Valid
paths:
  - '**/README.md'

# Invalid - creates a parse error that
# prevents your workflow from running.
paths:
  - **/README.md

# Valid
branches: [ main, 'release/v[0-9].[0-9]' ]

# Invalid - creates a parse error
branches: [ main, release/v[0-9].[0-9] ]

jobs

The jobs property defines how the workflow runs.

In GitHub Actions, a job is a single unit of processing that runs on an isolated virtual machine or container. A workflow consists of at least one job. All jobs run concurrently by default, and if needed you can set dependencies between jobs to control the order in which they run.

Jobs are specified in the workflow YAML file with the jobs property, as a mapping between job identifiers (IDs) and job details.

To run a job on the latest Ubuntu environment, the most widely used one, configure it as follows.

jobs:
  job1:
    runs-on: ubuntu-latest
    steps:
      # ...(생략)...

steps

Unless it is a really simple job, a job usually runs several commands in sequence, right? So in GitHub Actions, each job is modeled as one or more steps.

A step can be a simple command or script, or a more complex command called an action, explained in detail in the next section. Use the run property to run a command or script, and the uses property to use an action.

# ...(생략)...

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

There is one thing to be careful about when specifying steps in a workflow file. Because they use the sequence type in YAML syntax, each step must be prefixed with -.

Actions

The last concept to look at is the action, which can be called the highlight of GitHub Actions and is even in the service's name. An action is a kind of work-sharing mechanism provided to make it easy to reuse repetitive steps frequently needed in GitHub Actions. Actions can be shared not only among multiple workflows within a single code repository, but if shared through a public code repository, they become usable from any code repository on GitHub.

A representative public action provided by GitHub is the checkout action (actions/checkout), used in the example just above. Since most CI/CD jobs begin by downloading code from the code repository into the job's execution environment, you can imagine without being told how widely this action is used.

On GitHub Marketplace you can easily find a wide variety of actions published by numerous vendors. In short, a large community has formed around these actions, creating a virtuous cycle in which more users and vendors flock to GitHub Actions.

runs-on

Chaining a Workflow that runs only on Tags

You can turn your CD workflow into action and run it as part of your CI with condition: .github/actiond/cd/action.yml:

name: CD
description: Run CD
runs:
  using: composite
  steps:
    - run: echo "Success!"
      shell: bash

CI:

name: CI

on:
  push:
    tags: v[1-9]+.[0-9]+.[0-9]+
  pull_request:
    branches: [develop, hotfix*]

jobs:
  sucess:
    name: Log success
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - run: echo "Success!"
      - name: Run CD
        if: github.event_name == 'push' && contains(github.event.ref, '/tags/')
        uses: ./.github/actions/cd

Have it as a separate job that is dependant on CI job using needs option

Converting it to action makes for better encapsulation IMO although requires some work.

Automatic token authentication

Just use ${{ secrets.GITHUB_TOKEN }} wherever you need it.

Service containers

name: Redis Service Example
on: push

jobs:
  # Label of the container job
  runner-job:
    # You must use a Linux environment when using service containers or container jobs
    runs-on: ubuntu-latest

    # Service containers to run with `runner-job`
    services:
      # Label used to access the service container
      redis:
        # Docker Hub image
        image: redis
        #
        ports:
          # Opens tcp port 6379 on the host and service container
          - 6379:6379

Referencing Tags

To add it in #on:

on:
  push:
    tags:
      - 'v*'

To add it as a condition:

if: startsWith(github.event.ref, 'refs/tags/v')

Postgres Test

This is a good starting point for getting Python, Django, Postgres running as a service, pytest, black, and pip caching rolling with GitHub Actions.

python-django-postgres-ci.yml

name: CI

on: [push]

jobs:

  test:
    runs-on: ubuntu-latest

    services:
      postgres:
        image: postgres:11
        env:
          POSTGRES_USER: postgres
          POSTGRES_PASSWORD: postgres
          POSTGRES_DB: postgres
        ports: ['5432:5432']
        options: --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5

    steps:
      - uses: actions/checkout@v1
        with:
          fetch-depth: 1

      - name: Set up Python 3.7
        uses: actions/setup-python@v1
        with:
          python-version: 3.7

      - uses: actions/cache@v1
        with:
          path: ~/.cache/pip
          key: ${{ runner.os }}-pip-${{ hashFiles('**/requirements.txt') }}
          restore-keys: |
            ${{ runner.os }}-pip-
      - name: Install dependencies
        run: |
          python -m pip install --upgrade pip
          python -m pip install -r requirements.txt
        if: steps.cache.outputs.cache-hit != 'true'

      - name: Test with black
        run: |
          python -m black --check .
      - name: Test with pytest
        env:
          DATABASE_URL: 'postgres://postgres:postgres@localhost:${{ job.services.postgres.ports[5432] }}/postgres'
        run: |
          python -m pytest

z-docker-publish.yml

name: docker-publish

on:
  push:
    branches:
      - master

jobs:

  docker:
    name: Build and Publish Docker image
    runs-on: ubuntu-latest

    steps:
      - name: Git - Get Sources
        uses: actions/checkout@v1
        with:
          fetch-depth: 1

      - name: Docker - Build
        run: |
          docker build . --file .docker/Dockerfile --tag changeme-web
      - name: Docker - Login
        run: |
          echo ${{ secrets.GITHUB_TOKEN }} | docker login docker.pkg.github.com --username ${{ github.actor }} --password-stdin
      - name: Docker - Tag
        run: |
          docker tag changeme-web docker.pkg.github.com/${{ github.repository }}/changeme-web:latest
      - name: Docker - Push
        run: |
          docker push docker.pkg.github.com/${{ github.repository }}/changeme-web:latest

Docker Image Build and Push

Self Hosted Runners

Speeding up github action with local caching

This action allows caching dependencies and build outputs to improve workflow execution time on self hosted machine.

Many of you probably run CI/CD pipelines on github using git action. Caches are used heavily for fast builds; at first this is no big problem, but as the service grows or the number of branches increases, caching stops working, everything is rebuilt every time, and things start to slow down. This is because GitHub Actions' default caching has a 10GB size limit.

To solve this problem, we developed a package that can cache locally on a self-hosted runner.

      - name: Cache node dependencies  
        id: node-cache  
        uses: corca-ai/local-cache@v2  
        with:  
          path: node_modules  
          key: node-${{ hashFiles(‘yarn.lock’) }}  
          clean-key: node-  

Use a self-hosted runner instead of a github-hosted runner, and where you previously used cache, just change the uses part to corca-ai/local-cache and it works right away. The cache size limit disappears, and whereas the default caching loads cache files over the network, local caching loads directly from disk, so caching speed improves dramatically. We saw a speedup of more than 5x.

See also

Favorite site

Articles

author Zer0 sitemap