Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

GitHub Actions

GitHub Actions

GitHub Actions is GitHub's built-in automation platform, allowing you to define and run automation workflows directly in your code repository without any external CI/CD tools.

Common uses include: automatically running tests after code is pushed, automatically deploying to servers after PRs are merged, and executing scheduled data-scraping scripts.

GitHub Actions iscompletely free for public repositories, and private repositories have a free allowance of 2,000 minutes per month.


Core Concepts

Before you start writing configuration files, you need to understand the following core concepts, and their relationships are as follows:



仓库(Repository)

└── Workflow(工作流)          ← 一个 .yml 文件 = 一个 Workflow

    ├── Event(触发事件)        ← 什么情况下启动这个 Workflow,如 push、PR

    └── Job(作业)× N          ← 一个 Workflow 可以包含多个并行或串行的 Job

        ├── Runner(运行器)     ← 执行 Job 的服务器,如 ubuntu-latest

        └── Step(步骤)× N     ← Job 内按顺序执行的一系列操作

            ├── Action          ← 可复用的封装好的操作,如 actions/checkout

            └── Run             ← 直接执行 Shell 命令

Concept Description Analogy
Workflow The entire automation process, defined by a .yml file, stored in the .github/workflows/ directory a complete work plan
Event Conditions that trigger a Workflow run, such as code pushes, PR creation, scheduled tasks, etc. The start conditions of the plan
Job An independent unit of work in a Workflow; each Job runs on a separate virtual machine, and multiple Jobs run in parallel by default A chapter in the plan
Step The smallest unit of operation executed in order within a Job; it can be a Shell command or an Action Each specific step in a chapter
Action Reusable, pre-packaged operations from GitHub officially, third parties, or written by yourself, referenced via uses reference ready-made tool templates
Runner The server that executes Jobs; GitHub provides three hosted environments: Ubuntu, Windows, and macOS The workers who execute the plan

Create the first Workflow

1. Directory structure

All Workflow files must be stored in the .github/workflows/ folder under the repository root, with file names ending in .yml or .yaml , and file names can be customized:



your-repo/

├── .github/

│   └── workflows/

│       ├── ci.yml          ← 持续集成流程(如运行测试)

│       ├── deploy.yml      ← 部署流程

│       └── scheduled.yml   ← 定时任务

├── src/

├── package.json

└── README.md

A repository can have multiple Workflow files, which are independent of each other and triggered by their own defined events.

2. The simplest Workflow

Below is a most basic example: every time code is pushed to the repository, print a line "Hello, GitHub Actions!":

Example

.github/workflows/hello.yml

name

:

Hello World                  

The name of the Workflow, displayed on the GitHub Actions page

on

:

push                          

Trigger condition: triggered when code is pushed to any branch

jobs

:

                           

Define all Jobs

  say-hello

:

                     

The Job's ID (custom name, unique within the same Workflow)

    name

:

Print a greeting                

The Job's display name (optional; if left blank, the Job ID is shown)

    runs-on

:

ubuntu-latest        

Specify the runtime environment: use the latest Ubuntu virtual machine provided by GitHub

    steps

:

                       

All steps under this Job, executed in order

      - name

:

Print a message              

The Step's name (optional, used to identify the step in logs)

        run

:

echo

"Hello, GitHub Actions!"

 

run: directly execute a Shell command

YAML files are very sensitive to indentation; you must useSpacefor indentation, not the Tab key. It is recommended to use VS Code and install the YAML plugin, which can detect formatting errors in real time.


Trigger events (on)

on The field defines which events trigger this Workflow. It can be a single event or a combination of multiple events.

1. Common trigger events

Events Trigger Timing Common Use Cases
push When code is pushed to the repository Run tests, code checks
pull_request When a Pull Request is created or updated Automatic review and testing before PR merge
schedule Scheduled trigger by Cron expression Scheduled backups, scheduled data scraping
workflow_dispatch Manually trigger on the GitHub web page On-demand deployment, manual script execution
release When a new version is released (Release created) Automatic packaging, release to production
workflow_call When called by another Workflow Reuse common processes (such as public testing processes)

2. Specify branch or path filtering

Example

span style="color: #007F45;">

on:

  push

:

    branches

:

     - main            

Trigger only when pushed to the main branch

      - develop        

Or trigger when pushed to the develop branch

      - 'release/**'    

Or trigger when pushed to any branch starting with release/ (** matches any character)

    paths

:

     - 'src/**'        

Further filtering: trigger only when files under the src/ directory change

      - 'package.json'  

Or trigger when the package.json file changes

                       

The two are in an "or" relationship; satisfying either one triggers

  pull_request

:

    branches

:

     - main            

Trigger only on PRs whose target branch is main (i.e., PRs to be merged into main)

    types

:

     - opened          

When a PR is created

      - synchronize    

When new commits are pushed to the PR

      - reopened        

When a PR is reopened

3. Scheduled trigger (schedule)

Use standard Cron expressions to define execution time, with the time zone being UTC (Beijing time = UTC+8, conversion required):

Example

span style="color: #007F45;">

on:

  schedule

:

   

Cron format: minute hour day month weekday

    - cron

:

'

0

2

Execute once daily at UTC 02:00 (i.e., Beijing time 10:00)

    - cron

:

'

0

9

1

'      

Execute once every Monday at UTC 09:00 (i.e., Beijing time 17:00)

    - cron

:

'*/

30

Execute once every 30 minutes

Common Cron expression quick reference:

'0 0 * * *' every day at midnight (UTC 00:00)

'0 * * * *' every hour on the hour

'0 0 * * 0' every Sunday at midnight

'0 0 1 * *' midnight on the 1st of every month

4. Manual trigger (workflow_dispatch)

workflow_dispatch Allows manually clicking a button in the Actions tab of the GitHub web page to start a Workflow; you can also define input parameters:

Example

span style="color: #007F45;">

on:

  workflow_dispatch

:

    inputs

:

      environment

:

           

The name of the input parameter (can be referenced in steps via ${{ inputs.environment }})

        description

:

'deployment target environment'  

The parameter's description, displayed in the manual trigger form

        required

:

true          

Whether it is required

        default

:

'staging'      

Default value

        type

:

choice            

Parameter type: choice (drop-down selection)

        options

:

         - staging            

Optional values

          - production

      run_tests

:

        description

:

'whether to run tests'

        required

:

false

        type

:

boolean          

Parameter type: boolean (checkbox)

        default

:

true

jobs

:

  deploy

:

    runs-on

:

ubuntu-latest

    steps

:

      - name

:

Display deployment parameters

        run

: |

         echo "Target environment: ${{ inputs.environment }}"
          echo "Run tests: ${{ inputs.run_tests }}"


Jobs and Steps in detail

1. Basic structure of a Job

Example

span style="color: #007F45;">

jobs:

  build

:

                       

Job ID, must be unique within the same Workflow

    name

:

Build the project                  

The Job's display name (optional)

    runs-on

:

ubuntu-latest        

Runtime environment (required)

   

Optional: set environment variables for the entire Job, accessible to all Steps in the Job

    env

:

      NODE_ENV

:

production

      APP_PORT

:

8080

   

Optional: set a timeout (in minutes); after timeout the Job is automatically canceled to prevent it from hanging

    timeout-minutes

:

30

    steps

:

     

Step style 1: use an Action (referenced with uses)

      - name

:

Check out code

        uses

:

actions/checkout@v4        

Reference the official checkout Action (@v4 means using version v4)

     

Step style 2: execute a Shell command (specified with run)

      - name

:

Output the Node version

        run

:

node --version

     

Step style 3: execute a multi-line Shell command (use | to indicate multiple lines)

      - name

:

Install dependencies and build

        run

: |

         npm install
          npm run build
          echo "Build complete"

2. Runtime environment (runs-on)

GitHub provides the following free hosted runners, which you can choose as needed:

tag Operating system Description
ubuntu-latest Ubuntu (latest LTS) Most commonly used, fast, with the most free allowance; recommended as the first choice
ubuntu-22.04 Ubuntu 22.04 Specify a fixed version to avoid incompatibility issues introduced by latest upgrades
windows-latest Windows Server (latest) For tests or builds that require a Windows environment
macos-latest macOS (latest) For iOS/macOS app builds; consumes the free allowance fastest (about 10 times that of Ubuntu)

3. Dependencies between Jobs (needs)

By default, multiple Jobs run in parallel. Use needs to set the execution order of Jobs, forming a serial dependency relationship:

Example

span style="color: #007F45;">

jobs:

  test

:

                         

Step 1: Run tests

    runs-on

:

ubuntu-latest

    steps

:

      - uses

:

actions/checkout@v4

      - run

:

npm test

  build

:

                       

Step 2: Build the project

    runs-on

:

ubuntu-latest

    needs

:

test                  

build will only start after the test Job completes successfully

    steps

:

      - uses

:

actions/checkout@v4

      - run

:

npm run build

  deploy

:

                       

Step 3: Deploy

    runs-on

:

ubuntu-latest

    needs

:

[

test, build

]

         

deploy only begins after both test and build complete successfully

    steps

:

      - run

:

echo

"Starting deployment..."

Execution order: test → build → deploy (serial)

If needs is removed, the three Jobs will run in parallel at the same time

4. Conditional execution (if)

Pass if Can control whether a Job or Step executes; commonly used to distinguish branches, determine whether the previous step succeeded, etc.:

Example

span style="color: #007F45;">

jobs:

  deploy

:

    runs-on

:

ubuntu-latest

   

if written at the Job level: the entire Job only runs when pushed to the main branch

    if

:

github.ref == 'refs/heads/main'

    steps

:

      - uses

:

actions/checkout@v4

      - name

:

Deploys to the production environment

        run

:

./deploy.sh

     

if can also be written at the Step level, controlling whether a specific step executes

      - name

:

Send success notification

        if

:

success

(

)

           

success(): executes only when all the above Steps succeed

        run

:

echo

"Deployment successful, sending notification"

      - name

:

Send failure notification

        if

:

failure

(

)

           

failure(): executes only when any Step fails

        run

:

echo

"Deployment failed, sending alert"

      - name

:

Cleanup step that always executes

        if

:

always

(

)

             

always(): executes regardless of success or failure (commonly used to clean up temporary files)

        run

:

rm -rf ./tmp


Environment variables and Secrets

1. Environment variables (env)

Environment variables can be defined at three levels in a Workflow, with the scope narrowing in turn:

Example

Level 1: Workflow level (accessible to all Jobs and Steps)

env

:

  APP_NAME

:

my-app

  NODE_VERSION

:

'

18

'

jobs

:

  build

:

    runs-on

:

ubuntu-latest

   

Level 2: Job level (accessible only to all Steps within the current Job)

    env

:

      BUILD_MODE

:

production

    steps

:

      - name

:

Display environment variables

       

Level 3: Step level (accessible only to the current Step)

        env

:

          STEP_VAR

:

hello

        run

: |

         echo "Application name: $APP_NAME" # access Workflow-level variable
          echo "Build mode: $BUILD_MODE" # access Job-level variable
          echo "Step variable: $STEP_VAR" # access Step-level variable
          echo "Node version: $NODE_VERSION"

2. GitHub built-in variables (github context)

GitHub Actions provides a set of built-in context variables that can be referenced anywhere via ${{ }} syntax:

Example

span style="color: #007F45;">

steps:

  - name

:

Print common built-in variables

    run

: |

     echo "Repository name: ${{ github.repository }}" # e.g., your-user/your-repo
      echo "Trigger event: ${{ github.event_name }}" # e.g., push, pull_request
      echo "Current branch: ${{ github.ref_name }}" # e.g., main, develop
      echo "Commit SHA: ${{ github.sha }}" # full SHA hash of the current commit
      echo "Committer: ${{ github.actor }}" # username that triggered this Workflow
      echo "Working directory: ${{ github.workspace }}" # directory path where code is checked out
      echo "Run ID: ${{ github.run_id }}" # unique ID of this Workflow run
      echo "Run number: ${{ github.run_number }}" # which execution number this run is for the Workflow

3. Secrets (sensitive information management)

Sensitive information such as passwords, API keys, and server addressescannot be written directly in the yml file(because the code is public), and must be stored in the GitHub repository's Secrets.

Setup steps: go to the repository page → Settings → Secrets and variables → Actions → click New repository secret, fill in the name and value, then save.

Example

span style="color: #007F45;">

steps

:

 

Reference the set Secret in a Step via ${{ secrets.secret_name }}

 

The Secret's value is automatically masked with *** in logs and won't be leaked

  - name

:

Deploy to server

    env

:

      SSH_KEY

:

$

{

{

secrets.SSH_PRIVATE_KEY

}

}

     

Server SSH private key

      SERVER_IP

:

$

{

{

secrets.DEPLOY_SERVER_IP

}

}

   

Server IP address

    run

: |

     echo "$SSH_KEY" > ~/.ssh/id_rsa
      chmod 600 ~/.ssh/id_rsa
      ssh user@$SERVER_IP "cd /app && git pull && pm2 restart all"

 

GitHub automatically provides GITHUB_TOKEN for operating this repository (such as pushing code, creating Release)

 

No need to create manually; just use it directly

  - name

:

Push changes to repository

    run

: |

     git config user.name "github-actions[bot]"
      git config user.email "github-actions[bot]@users.noreply.github.com"
      git add .
      git commit -m "Automatic update [skip ci]"
      git push

    env

:

      GITHUB_TOKEN

:

$

{

{

secrets.GITHUB_TOKEN

}

}

   

Automatically provided by GitHub, no need to create manually


Common Actions introduction

GitHub official and community provide a large number of ready-to-use Actions, referenced via uses: action名称@版本 , which can avoid repeatedly writing common operations.

1. actions/checkout (check out code)

The first step of almost every Workflow is to check out the repository code, using the official actions/checkout:

Example

span style="color: #007F45;">

steps

:

 

Most basic usage: check out the latest code of the current branch to the working directory

  - uses

:

actions/checkout@v4

 

Advanced usage: customize by passing parameters via with

  - uses

:

actions/checkout@v4

    with

:

      ref

:

develop              

Check out a specified branch (by default, checks out the branch where the triggering event occurred)

      fetch-depth

:

0

           

Check out the complete git history (by default, only the latest commit is checked out)

                               

Setting it to 0 gets all history, so commands like git log work properly

      submodules

:

true          

Also initialize and update git submodules (submodule)

2. actions/setup-node (configure Node.js environment)

Example

span style="color: #007F45;">

steps:

  - uses

:

actions/checkout@v4

  - name

:

Configure Node.js environment

    uses

:

actions/setup-node@v4

    with

:

      node-version

:

'

20

'        

Specify Node.js version

 

After configuration, the npm and node commands can be used directly

  - run

:

node --version

  - run

:

npm install

  - run

:

npm test

3. actions/setup-python (configure Python environment)

Example

span style="color: #007F45;">

steps:

  - uses

:

actions/checkout@v4

  - name

:

Configure Python environment

    uses

:

actions/setup-python@v5

    with

:

      python-version

:

'

3.11

'  

Specify the Python version

  - name

:

Install dependencies

    run

:

pip install -r requirements.txt

  - name

:

Running tests

    run

:

pytest tests/

4. actions/cache (cache dependencies to speed up builds)

Re-downloading dependencies every time a Workflow runs is slow. Using the cache Action, you can cache dependencies and use the cache directly next time, greatly reducing build time:

Example

span style="color: #007F45;">

steps:

  - uses

:

actions/checkout@v4

  - uses

:

actions/setup-node@v4

    with

:

      node-version

:

'

20

'

  - name

:

Cache node_modules

    uses

:

actions/cache@v4

    with

:

      path

:

~/.npm                            

Specify the directory to cache

      key

:

$

{

{

runner.os

}

}

-node-$

{

{

hashFiles

(

'**/package-lock.json'

)

}

}

     

key: the unique identifier of the cache

     

hashFiles('**/package-lock.json'): generate a hash value based on the lock file content

     

If the lock file is unchanged, the key is unchanged and the cache is hit directly; if the lock file changes, dependencies are reinstalled

      restore-keys

: |

       ${{ runner.os }}-node-

     

restore-keys: a fallback matching strategy when the key is not hit, using the most recent valid cache

  - run

:

npm ci                              

npm ci is more suitable for CI scenarios than npm install, being faster and stricter

  - run

:

npm test

5. actions/upload-artifact / download-artifact (transfer files between Jobs)

Different Jobs run on separate virtual machines, and files cannot be shared directly. Through artifacts you can pass one Job's output files to another Job:

Example

span style="color: #007F45;">

jobs:

  build

:

    runs-on

:

ubuntu-latest

    steps

:

      - uses

:

actions/checkout@v4

      - run

:

npm install && npm run build    

Build artifacts are output to the ./dist directory

      - name

:

Upload build artifacts

        uses

:

actions/upload-artifact@v4

        with

:

          name

:

dist-files                  

The artifact's name (referenced by this name when downloading)

          path

:

./dist                      

The directory or file path to upload

          retention-days

:

7

                 

Number of days to retain the artifact (maximum 90 days)

  deploy

:

    runs-on

:

ubuntu-latest

    needs

:

build                            

Execute after the build Job completes

    steps

:

      - name

:

Download build artifacts

        uses

:

actions/download-artifact@v4

        with

:

          name

:

dist-files                  

Consistent with the name used when uploading

          path

:

./dist                      

The local directory to download to

      - name

:

Deploy files

        run

:

rsync -avz ./dist/ user@server:/var/www/html/


Matrix builds (Matrix)

Matrix builds allow you to run in parallel across multiple environments with a single Job configuration, commonly used for cross-version and cross-OS compatibility testing:

Example

span style="color: #007F45;">

jobs:

  test

:

    name

:

Test Node $

{

{

matrix.node-version

}

}

on $

{

{

matrix.os

}

}

    runs-on

:

$

{

{

matrix.os

}

}

       

Read the runtime environment from the matrix variable

    strategy

:

      matrix

:

        os

:

[

ubuntu-latest, windows-latest, macos-latest

]

 

3 operating systems

        node-version

:

[

'

18

', '

20

', '

22

'

]

                   

3 Node versions

       

The above combinations produce 3 × 3 = 9 parallel Jobs

      fail-fast

:

false                

Default true: cancel all remaining Jobs after one Job fails

                                     

Set to false: even if a combination fails, other combinations continue running,

                                     

making it easy to see test results for all environments

    steps

:

      - uses

:

actions/checkout@v4

      - name

:

Configure Node.js $

{

{

matrix.node-version

}

}

        uses

:

actions/setup-node@v4

        with

:

          node-version

:

$

{

{

matrix.node-version

}

}

 

Reference matrix variables

      - run

:

npm ci

      - run

:

npm test

Example

Advanced usage: exclude unwanted combinations via exclude, and append special configurations via include

strategy

:

  matrix

:

    os

:

[

ubuntu-latest, windows-latest

]

    node-version

:

[

'

18

', '

20

'

]

    exclude

:

      - os

:

windows-latest

        node-version

:

'

18

'    

Exclude the windows + Node 18 combination

    include

:

      - os

:

ubuntu-latest

        node-version

:

'

20

'

        experimental

:

true    

Append extra variables for specific combinations (can be referenced in steps via matrix.experimental)


Practical Examples

Example 1: Node.js project CI (automatic testing)

Every time code is pushed or a PR is created, automatically install dependencies, run code checks, and test:

Example

.github/workflows/ci.yml

name

:

Node.js CI

on

:

  push

:

    branches

:

[

main, develop

]

  pull_request

:

    branches

:

[

main

]

jobs

:

  test

:

    name

:

Code checking and testing

    runs-on

:

ubuntu-latest

    steps

:

      - name

:

Check out code

        uses

:

actions/checkout@v4

      - name

:

Configure Node.js environment

        uses

:

actions/setup-node@v4

        with

:

          node-version

:

'

20

'

          cache

:

'npm'                      

setup-node has built-in cache support, more concise than using a separate cache Action

      - name

:

Install dependencies

        run

:

npm ci                          

npm ci installs strictly according to package-lock.json,

                                             

more suitable for CI scenarios than npm install

      - name

:

Run code checks (ESLint)

        run

:

npm run lint

      - name

:

Run unit tests

        run

:

npm test -- --coverage          

Generate a test coverage report at the same time

      - name

:

Upload the coverage report

        uses

:

actions/upload-artifact@v4

        if

:

always

(

)

                       

Upload the report regardless of whether tests pass (to make it easy to see failure reasons)

        with

:

          name

:

coverage-report

          path

:

./coverage

Example 2: Python project CI

Example

.github/workflows/python-ci.yml

name

:

Python CI

on

:

  push

:

    branches

:

[

main

]

  pull_request

:

jobs

:

  test

:

    runs-on

:

ubuntu-latest

    steps

:

      - uses

:

actions/checkout@v4

      - name

:

Configure Python environment

        uses

:

actions/setup-python@v5

        with

:

          python-version

:

'

3.11

'

          cache

:

'pip'                      

Cache pip dependencies

      - name

:

Install dependencies

        run

: |

         python -m pip install --upgrade pip
          pip install -r requirements.txt
          pip install flake8 pytest # install code checking and testing tools

      - name

:

Run code format checks (flake8)

        run

: |

         # Check for syntax errors and undefined variables (E9, F63, F7, F82 series); report an error and exit if problems are found
          flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics
          # Check code style (maximum line length 120); only count the number of problems, do not report an error or exit
          flake8 . --count --max-line-length=120 --statistics

      - name

:

Running tests

        run

:

pytest tests/ -v                

-v output detailed test results

Example 3: Build and push a Docker image

Example

.github/workflows/docker.yml

name

:

Build and push a Docker image

on

:

  push

:

    branches

:

[

main

]

    tags

:

     - 'v*'                              

Triggered when pushing a tag starting with v, such as v1.0.0

jobs

:

  docker

:

    runs-on

:

ubuntu-latest

    steps

:

      - uses

:

actions/checkout@v4

     

Use the official Docker metadata Action to automatically generate image tags

     

For example, when pushing tag v1.2.3, multiple tags such as 1.2.3, 1.2, 1, and latest are automatically generated

      - name

:

Extract Docker metadata (image tags, etc.)

        id

:

meta                          

Set an ID for this Step so subsequent Steps can reference its output

        uses

:

docker/metadata-action@v5

        with

:

          images

:

your-dockerhub-username/your-image-name

      - name

:

Log in to Docker Hub

        uses

:

docker/login-action@v3

        with

:

          username

:

$

{

{

secrets.DOCKERHUB_USERNAME

}

}

          password

:

$

{

{

secrets.DOCKERHUB_TOKEN

}

}

 

Use an Access Token instead of a password, which is more secure

      - name

:

Build and push the image

        uses

:

docker/build-push-action@v5

        with

:

          context

:

.                      

Directory where the Dockerfile is located (current directory)

          push

:

true                      

true: push to the Registry after the build completes

          tags

:

$

{

{

steps.meta.outputs.tags

}

}

     

Reference the tag list generated by the meta Step

          labels

:

$

{

{

steps.meta.outputs.labels

}

}

 

Reference the tag information generated by the meta Step

Example 4: Automatically deploy to a server after building

Example

.github/workflows/deploy.yml

name

:

Build and deploy

on

:

  push

:

    branches

:

[

main

]

                     

Deployment is triggered only when pushed to the main branch

jobs

:

  build-and-deploy

:

    runs-on

:

ubuntu-latest

    steps

:

      - uses

:

actions/checkout@v4

      - uses

:

actions/setup-node@v4

        with

:

          node-version

:

'

20

'

          cache

:

'npm'

      - name

:

Install dependencies and build

        run

: |

         npm ci
          npm run build # build artifacts are output to the ./dist directory

      - name

:

Deploy to the server via SSH

        uses

:

appleboy/ssh-action@v1.0.3  

Third-party SSH Action, no need to configure SSH manually

        with

:

          host

:

$

{

{

secrets.SERVER_HOST

}

}

     

Server IP or domain name

          username

:

$

{

{

secrets.SERVER_USER

}

}

 

SSH login username

          key

:

$

{

{

secrets.SSH_PRIVATE_KEY

}

}

   

SSH private key content (corresponding to the public key on the server)

          port

:

22

                             

SSH port, default 22

          script

: |

           # The following commands execute on the remote server
            cd /var/www/my-app
            git pull origin main
            npm ci --production
            pm2 restart my-app # restart the Node.js app with pm2
            echo "Deployment complete: $(date)"

Example 5: Scheduled task (automatic database backup)

Example

.github/workflows/backup.yml

name

:

Schedule database backup

on

:

  schedule

:

    - cron

:

'

0

2

Execute daily at UTC 02:00 (Beijing time 10:00)

  workflow_dispatch

:

                     

Also supports manual triggering, convenient for temporary backups

jobs

:

  backup

:

    runs-on

:

ubuntu-latest

    steps

:

      - name

:

Execute the backup script via SSH

        uses

:

appleboy/ssh-action@v1.0.3

        with

:

          host

:

$

{

{

secrets.SERVER_HOST

}

}

          username

:

$

{

{

secrets.SERVER_USER

}

}

          key

:

$

{

{

secrets.SSH_PRIVATE_KEY

}

}

          script

: |

           TIMESTAMP=$(date +%Y%m%d_%H%M%S)
            BACKUP_FILE="/backup/db_$TIMESTAMP.sql"

            # Perform database backup
            mysqldump -u root -p${{ secrets.DB_PASSWORD }} my_database > $BACKUP_FILE

            # Compress the backup file
            gzip $BACKUP_FILE

            # Delete backup files older than 30 days to avoid filling the disk
            find /backup -name "*.sql.gz" -mtime +30 -delete

            echo "Backup complete: ${BACKUP_FILE}.gz"


Debugging tips

1. Enable Debug logs

When a Workflow fails but the log information is insufficient, you can enable detailed debug mode. Method: go to the repository Settings → Secrets and variables → Actions, add the following two Secrets (set both values to true):

2. Print context information to assist troubleshooting

Example

span style="color: #007F45;">

steps:

  - name

:

Print all context information (for debugging; add when troubleshooting, remove after resolving)

    run

: |

     echo "=== github context ==="
      echo '${{ toJson(github) }}' # toJson() formats the object into a JSON string for output
      echo "=== env context ==="
      echo '${{ toJson(env) }}'
      echo "=== job context ==="
      echo '${{ toJson(job) }}'

3. Test Workflow locally (using act)

Having to push code every time to test a Workflow is very inefficient.act is an open-source tool that can simulate running GitHub Actions locally, greatly improving debugging efficiency:



# Install act (requires Docker to be installed locally)

# macOS

brew install act



# Linux

curl https://raw.githubusercontent.com/nektos/act/master/install.sh | sudo bash



# Run all workflows in the repository root directory

act



# Only run workflows triggered by specified events

act push



# Run the specified Job

act -j build

During local testing,act will use Docker containers to simulate the GitHub runtime environment, but some Actions (such as actions/cache) may behave differently in local simulation than in a real environment; the final result is subject to the actual run on GitHub.


Common Issues and Notes

1. Permission issues (Permission denied)

If a Workflow needs to push code to the repository or operate on Issues, you need to explicitly declare permissions in the configuration file:

Example

Set permissions at the Workflow top level or Job level

permissions

:

  contents

:

write      

Allow read/write access to repository contents (code, files)

  issues

:

write        

Allow creating and modifying Issues

  pull-requests

:

write  

Allow operating on Pull Requests

Principle of least privilege: only open permissions actually needed; the rest default to read or none

2. Avoid Workflow loop triggers

If a Workflow automatically pushes code to the repository, it may trigger a new push event, causing an infinite loop. Solution: add the [skip ci] keyword in the auto-commit message, and GitHub will skip the Workflow trigger for that commit:

git commit -m "自动格式化代码 [skip ci]"

3. YAML special character escaping

in run When a Shell command in a field uses ${{ }} expressions, and the expression contains special YAML characters such as a colon (:), you need to wrap the entire value in quotes, or first assign it to an environment variable and then use it:

Example

span style="color: #007F45;">

steps

:

 

Not recommended: ${{ }} expressions embedded directly in complex commands may cause YAML parsing errors

  - run

:

echo $

{

{

github.event.pull_request.title

}

}

 

Recommended: first assign the value to an environment variable, then use the environment variable in Shell

  - name

:

Print PR title

    env

:

      PR_TITLE

:

$

{

{

github.event.pull_request.title

}

}

    run

:

echo

"PR title: $PR_TITLE"

For more complete documentation, please refer to the official documentation:https://docs.github.com/zh/actions