Skip to main content

Contexts

Learn about contexts in GitHub Actions.

About contexts

上下文是一种访问工作流运行、变量、运行器环境、作业及步骤相关信息的方式。 Each context is an object that contains properties, which can be strings or other objects.

在不同的工作流运行条件下,上下文、对象和属性大不相同。 For example, the matrix context is only populated for jobs in a matrix.

You can access contexts using the expression syntax. For more information, see 对工作流和操作中的表达式求值.

${{ <context> }}

警告

创建工作流和操作时,应始终考虑代码是否可能执行潜在攻击者的不受信任的输入。 某些上下文应被视为不受信任的输入,因为攻击者可能会插入自己的恶意内容。 有关详细信息,请参阅“GitHub Actions 的安全强化”。

Determining when to use contexts

GitHub Actions includes a collection of variables called contexts and a similar collection of variables called default variables. These variables are intended for use at different points in the workflow:

  • Default environment variables: These environment variables exist only on the runner that is executing your job. For more information, see 在变量中存储信息.
  • Contexts: You can use most contexts at any point in your workflow, including when default variables would be unavailable. For example, you can use contexts with expressions to perform initial processing before the job is routed to a runner for execution; this allows you to use a context with the conditional if keyword to determine whether a step should run. Once the job is running, you can also retrieve context variables from the runner that is executing the job, such as runner.os. For details of where you can use various contexts within a workflow, see Contexts reference.

The following example demonstrates how these different types of variables can be used together in a job:

YAML
name: CI
on: push
jobs:
  prod-check:
    if: ${{ github.ref == 'refs/heads/main' }}
    runs-on: ubuntu-latest
    steps:
      - run: echo "Deploying to production server on branch $GITHUB_REF"

In this example, the if statement checks the github.ref context to determine the current branch name; if the name is refs/heads/main, then the subsequent steps are executed. The if check is processed by GitHub Actions, and the job is only sent to the runner if the result is true. Once the job is sent to the runner, the step is executed and refers to the $GITHUB_REF variable from the runner.