Skip to main content

Contexts

You can access context information in workflows and actions.

Observação: no momento, não há suporte para os executores hospedados no GitHub no GitHub Enterprise Server. Você pode ver mais informações sobre o suporte futuro planejado no GitHub public roadmap.

About contexts

Contexts are a way to access information about workflow runs, runner environments, jobs, and steps. Each context is an object that contains properties, which can be strings or other objects.

Os contextos, objetos e propriedades variarão significativamente em diferentes condições de execução do fluxo de trabalho. 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 "Expressions."

${{ <context> }}

Aviso: ao criar fluxos de trabalho e ações, você sempre deve considerar se o seu código pode executar entradas não confiáveis de possíveis invasores. Certos contextos devem ser tratados como entradas não confiáveis, uma vez que um invasor pode inserir seu próprio conteúdo malicioso. Para obter mais informações, confira "Noções básicas sobre o risco de injeções de script".

Context nameTypeDescription
githubobjectInformation about the workflow run. For more information, see github context.
envobjectContains environment variables set in a workflow, job, or step. For more information, see env context.
jobobjectInformation about the currently running job. For more information, see job context.
jobsobjectFor reusable workflows only, contains outputs of jobs from the reusable workflow. For more information, see jobs context.
stepsobjectInformation about the steps that have been run in the current job. For more information, see steps context.
runnerobjectInformation about the runner that is running the current job. For more information, see runner context.
secretsobjectContains the names and values of secrets that are available to a workflow run. For more information, see secrets context.
strategyobjectInformation about the matrix execution strategy for the current job. For more information, see strategy context.
matrixobjectContains the matrix properties defined in the workflow that apply to the current job. For more information, see matrix context.
needsobjectContains the outputs of all jobs that are defined as a dependency of the current job. For more information, see needs context.
inputsobjectContains the inputs of a reusable workflow. For more information, see inputs context.

As part of an expression, you can access context information using one of two syntaxes.

  • Index syntax: github['sha']
  • Property dereference syntax: github.sha

In order to use property dereference syntax, the property name must start with a letter or _ and contain only alphanumeric characters, -, or _.

If you attempt to dereference a non-existent property, it will evaluate to an empty string.

Determining when to use contexts

O GitHub Actions inclui uma coleção de variáveis chamadas contextos e uma coleção semelhante de variáveis chamadas variáveis de ambiente padrão. Estas variáveis são destinadas a serem usadas em diferentes pontos do fluxo de trabalho:

  • Variáveis de ambiente padrão: essas variáveis existem apenas no executor que está executando seu trabalho. Para obter mais informações, confira "Variáveis de ambiente padrão".
  • Contextos: você pode usar a maioria dos contextos em qualquer ponto no fluxo de trabalho, incluindo aqueles em que as variáveis de ambiente padrão não estão disponíveis. Por exemplo, você pode usar contextos com expressões para executar o processamento inicial antes que o trabalho seja encaminhado para um executor para execução. Isso permite que você use um contexto com a palavra-chave if condicional para determinar se uma etapa deve ser executada. Depois que o trabalho estiver em execução, você também poderá recuperar variáveis de contexto do executor que está executando o trabalho, como runner.os. Para ver detalhes do local em que você pode usar vários contextos em um fluxo de trabalho, confira "Disponibilidade de contexto".

O exemplo a seguir demonstra como esses diferentes tipos de variáveis de ambiente podem ser usados juntos em um trabalho:

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"

Neste exemplo, a instrução if verifica o contexto github.ref para determinar o nome do branch atual. Se o nome for refs/heads/main, as etapas seguintes serão executadas. A verificação if é processada pelo GitHub Actions, e o trabalho só será enviado ao executor se o resultado for true. Depois que o trabalho é enviado para o executor, a etapa é executada e refere-se à variável de ambiente $GITHUB_REF do executor.

Context availability

Different contexts are available throughout a workflow run. For example, the secrets context may only be used at certain places within a job.

In addition, some functions may only be used in certain places. For example, the hashFiles function is not available everywhere.

The following table indicates where each context and special function can be used within a workflow. Unless listed below, a function can be used anywhere.

Workflow keyContextSpecial functions
concurrencygithub, inputs
envgithub, secrets, inputs
jobs.<job_id>.concurrencygithub, needs, strategy, matrix, inputs
jobs.<job_id>.containergithub, needs, strategy, matrix, env, secrets, inputs
jobs.<job_id>.container.credentialsgithub, needs, strategy, matrix, env, secrets, inputs
jobs.<job_id>.container.env.<env_id>github, needs, strategy, matrix, job, runner, env, secrets, inputs
jobs.<job_id>.continue-on-errorgithub, needs, strategy, matrix, inputs
jobs.<job_id>.defaults.rungithub, needs, strategy, matrix, env, inputs
jobs.<job_id>.envgithub, needs, strategy, matrix, secrets, inputs
jobs.<job_id>.environmentgithub, needs, strategy, matrix, inputs
jobs.<job_id>.environment.urlgithub, needs, strategy, matrix, job, runner, env, steps, inputs
jobs.<job_id>.ifgithub, needs, inputsalways, cancelled, success, failure
jobs.<job_id>.namegithub, needs, strategy, matrix, inputs
jobs.<job_id>.outputs.<output_id>github, needs, strategy, matrix, job, runner, env, secrets, steps, inputs
jobs.<job_id>.runs-ongithub, needs, strategy, matrix, inputs
jobs.<job_id>.secrets.<secrets_id>github, needs, secrets
jobs.<job_id>.servicesgithub, needs, strategy, matrix, inputs
jobs.<job_id>.services.<service_id>.credentialsgithub, needs, strategy, matrix, env, secrets, inputs
jobs.<job_id>.services.<service_id>.env.<env_id>github, needs, strategy, matrix, job, runner, env, secrets, inputs
jobs.<job_id>.steps.continue-on-errorgithub, needs, strategy, matrix, job, runner, env, secrets, steps, inputshashFiles
jobs.<job_id>.steps.envgithub, needs, strategy, matrix, job, runner, env, secrets, steps, inputshashFiles
jobs.<job_id>.steps.ifgithub, needs, strategy, matrix, job, runner, env, steps, inputsalways, cancelled, success, failure, hashFiles
jobs.<job_id>.steps.namegithub, needs, strategy, matrix, job, runner, env, secrets, steps, inputshashFiles
jobs.<job_id>.steps.rungithub, needs, strategy, matrix, job, runner, env, secrets, steps, inputshashFiles
jobs.<job_id>.steps.timeout-minutesgithub, needs, strategy, matrix, job, runner, env, secrets, steps, inputshashFiles
jobs.<job_id>.steps.withgithub, needs, strategy, matrix, job, runner, env, secrets, steps, inputshashFiles
jobs.<job_id>.steps.working-directorygithub, needs, strategy, matrix, job, runner, env, secrets, steps, inputshashFiles
jobs.<job_id>.strategygithub, needs, inputs
jobs.<job_id>.timeout-minutesgithub, needs, strategy, matrix, inputs
jobs.<job_id>.with.<with_id>github, needs
on.workflow_call.inputs.<inputs_id>.defaultgithub
on.workflow_call.outputs.<output_id>.valuegithub, jobs, inputs

Example: printing context information to the log

You can print the contents of contexts to the log for debugging. The toJSON function is required to pretty-print JSON objects to the log.

Aviso: ao usar todo o contexto github, lembre-se de que ele inclui informações confidenciais, como github.token. GitHub oculta segredos quando eles são impressos no console, mas você deve ter cuidado ao exportar ou imprimir o contexto.

YAML
name: Context testing
on: push

jobs:
  dump_contexts_to_log:
    runs-on: ubuntu-latest
    steps:
      - name: Dump GitHub context
        id: github_context_step
        run: echo '${{ toJSON(github) }}'
      - name: Dump job context
        run: echo '${{ toJSON(job) }}'
      - name: Dump steps context
        run: echo '${{ toJSON(steps) }}'
      - name: Dump runner context
        run: echo '${{ toJSON(runner) }}'
      - name: Dump strategy context
        run: echo '${{ toJSON(strategy) }}'
      - name: Dump matrix context
        run: echo '${{ toJSON(matrix) }}'

github context

The github context contains information about the workflow run and the event that triggered the run. You can also read most of the github context data in environment variables. For more information about environment variables, see "Using environment variables."

Aviso: ao usar todo o contexto github, lembre-se de que ele inclui informações confidenciais, como github.token. GitHub oculta segredos quando eles são impressos no console, mas você deve ter cuidado ao exportar ou imprimir o contexto.

Aviso: ao criar fluxos de trabalho e ações, você sempre deve considerar se o seu código pode executar entradas não confiáveis de possíveis invasores. Certos contextos devem ser tratados como entradas não confiáveis, uma vez que um invasor pode inserir seu próprio conteúdo malicioso. Para obter mais informações, confira "Noções básicas sobre o risco de injeções de script".

Property nameTypeDescription
githubobjectThe top-level context available during any job or step in a workflow. This object contains all the properties listed below.
github.actionstringThe name of the action currently running, or the id of a step. GitHub removes special characters, and uses the name __run when the current step runs a script without an id. If you use the same action more than once in the same job, the name will include a suffix with the sequence number with underscore before it. For example, the first script you run will have the name __run, and the second script will be named __run_2. Similarly, the second invocation of actions/checkout will be actionscheckout2.
github.action_pathstringThe path where an action is located. This property is only supported in composite actions. You can use this path to access files located in the same repository as the action.
github.action_refstringFor a step executing an action, this is the ref of the action being executed. For example, v2.
github.action_repositorystringFor a step executing an action, this is the owner and repository name of the action. For example, actions/checkout.
github.action_statusstringFor a composite action, the current result of the composite action.
github.actorstringThe username of the user that initiated the workflow run.
github.api_urlstringThe URL of the GitHub REST API.
github.base_refstringThe base_ref or target branch of the pull request in a workflow run. This property is only available when the event that triggers a workflow run is either pull_request or pull_request_target.
github.envstringPath on the runner to the file that sets environment variables from workflow commands. This file is unique to the current step and is a different file for each step in a job. For more information, see "Workflow commands for GitHub Actions."
github.eventobjectThe full event webhook payload. You can access individual properties of the event using this context. This object is identical to the webhook payload of the event that triggered the workflow run, and is different for each event. The webhooks for each GitHub Actions event is linked in "Events that trigger workflows." For example, for a workflow run triggered by the push event, this object contains the contents of the push webhook payload.
github.event_namestringThe name of the event that triggered the workflow run.
github.event_pathstringThe path to the file on the runner that contains the full event webhook payload.
github.graphql_urlstringThe URL of the GitHub GraphQL API.
github.head_refstringThe head_ref or source branch of the pull request in a workflow run. This property is only available when the event that triggers a workflow run is either pull_request or pull_request_target.
github.jobstringThe job_id of the current job.
Note: This context property is set by the Actions runner, and is only available within the execution steps of a job. Otherwise, the value of this property will be null.
github.refstringA ref totalmente formada do branch ou tag que acionou a execução do fluxo de trabalho. Para fluxos de trabalho disparados por push, esse é o branch ou a ref da tag que foi enviada por push. Para fluxos de trabalho disparados por pull_request, esse é o branch de mesclagem de solicitação de pull. Para fluxos de trabalho disparados por release, essa é a tag de versão criada. Para outros gatilhos, esse é o branch ou a ref de tag que disparou a execução do fluxo de trabalho. Essa variável só é definida quando há um branch ou uma tag disponível para o tipo de evento. A ref fornecida tem o formato completo, o que significa que, para branches, o formato é refs/heads/<branch_name>, para solicitações de pull é refs/pull/<pr_number>/merge e para tags é refs/tags/<tag_name>. Por exemplo, refs/heads/feature-branch-1.
github.ref_namestringO nome de ref curto do branch ou tag que acionou a execução do fluxo de trabalho. Esse valor corresponde ao nome do branch ou tag mostrado em GitHub. Por exemplo, feature-branch-1.
github.ref_protectedbooleantrue se as proteções de branch estiverem configuradas para a referência que disparou a execução de fluxo de trabalho.
github.ref_typestringO tipo de ref que acionou a execução do fluxo de trabalho. Os valores válidos são branch ou tag.
github.pathstringPath on the runner to the file that sets system PATH variables from workflow commands. This file is unique to the current step and is a different file for each step in a job. For more information, see "Workflow commands for GitHub Actions."
github.repositorystringThe owner and repository name. For example, Codertocat/Hello-World.
github.repository_ownerstringThe repository owner's name. For example, Codertocat.
github.repositoryUrlstringThe Git URL to the repository. For example, git://github.com/codertocat/hello-world.git.
github.retention_daysstringThe number of days that workflow run logs and artifacts are kept.
github.run_idstringUm número exclusivo para cada fluxo de trabalho executado em um repositório. Este número não muda se você executar novamente o fluxo de trabalho.
github.run_numberstringUm número exclusivo para cada execução de um fluxo de trabalho específico em um repositório. Esse número começa em 1 para a primeira execução do fluxo de trabalho e é incrementado a cada nova operação. Este número não muda se você executar novamente o fluxo de trabalho.
github.secret_sourcestringThe source of a secret used in a workflow. Possible values are None, Actions, Dependabot, or Codespaces.
github.server_urlstringThe URL of the GitHub server. For example: https://github.com.
github.shastringO commit SHA que acionou o fluxo de trabalho. O valor do commit deste SHA depende do evento que acionou o fluxo de trabalho. Para obter mais informações, confira "Eventos que disparam fluxos de trabalho". Por exemplo, ffac537e6cbbf934b08745a378932722df287a53.
github.tokenstringA token to authenticate on behalf of the GitHub App installed on your repository. This is functionally equivalent to the GITHUB_TOKEN secret. For more information, see "Automatic token authentication."
Note: This context property is set by the Actions runner, and is only available within the execution steps of a job. Otherwise, the value of this property will be null.
github.workflowstringThe name of the workflow. If the workflow file doesn't specify a name, the value of this property is the full path of the workflow file in the repository.
github.workspacestringThe default working directory on the runner for steps, and the default location of your repository when using the checkout action.

Example contents of the github context

The following example context is from a workflow run triggered by the push event. The event object in this example has been truncated because it is identical to the contents of the push webhook payload.

Observação: esse contexto é apenas um exemplo. O conteúdo de um contexto depende do fluxo de trabalho que você está executando. Os contextos, objetos e propriedades variarão significativamente em diferentes condições de execução do fluxo de trabalho.

{
  "token": "***",
  "job": "dump_contexts_to_log",
  "ref": "refs/heads/my_branch",
  "sha": "c27d339ee6075c1f744c5d4b200f7901aad2c369",
  "repository": "octocat/hello-world",
  "repository_owner": "octocat",
  "repositoryUrl": "git://github.com/octocat/hello-world.git",
  "run_id": "1536140711",
  "run_number": "314",
  "retention_days": "90",
  "run_attempt": "1",
  "actor": "octocat",
  "workflow": "Context testing",
  "head_ref": "",
  "base_ref": "",
  "event_name": "push",
  "event": {
    ...
  },
  "server_url": "https://github.com",
  "api_url": "https://api.github.com",
  "graphql_url": "https://api.github.com/graphql",
  "ref_name": "my_branch",
  "ref_protected": false,
  "ref_type": "branch",
  "secret_source": "Actions",
  "workspace": "/home/runner/work/hello-world/hello-world",
  "action": "github_step",
  "event_path": "/home/runner/work/_temp/_github_workflow/event.json",
  "action_repository": "",
  "action_ref": "",
  "path": "/home/runner/work/_temp/_runner_file_commands/add_path_b037e7b5-1c88-48e2-bf78-eaaab5e02602",
  "env": "/home/runner/work/_temp/_runner_file_commands/set_env_b037e7b5-1c88-48e2-bf78-eaaab5e02602"
}

Example usage of the github context

This example workflow uses the github.event_name context to run a job only if the workflow run was triggered by the pull_request event.

YAML
name: Run CI
on: [push, pull_request]

jobs:
  normal_ci:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - name: Run normal CI
        run: ./run-tests

  pull_request_ci:
    runs-on: ubuntu-latest
    if: ${{ github.event_name == 'pull_request' }}
    steps:
      - uses: actions/checkout@v3
      - name: Run PR CI
        run: ./run-additional-pr-ci

env context

The env context contains environment variables that have been set in a workflow, job, or step. For more information about setting environment variables in your workflow, see "Workflow syntax for GitHub Actions."

The env context syntax allows you to use the value of an environment variable in your workflow file. You can use the env context in the value of any key in a step except for the id and uses keys. For more information on the step syntax, see "Workflow syntax for GitHub Actions."

If you want to use the value of an environment variable inside a runner, use the runner operating system's normal method for reading environment variables.

Property nameTypeDescription
envobjectThis context changes for each step in a job. You can access this context from any step in a job. This object contains the properties listed below.
env.<env_name>stringThe value of a specific environment variable.

Example contents of the env context

The contents of the env context is a mapping of environment variable names to their values. The context's contents can change depending on where it is used in the workflow run.

{
  "first_name": "Mona",
  "super_duper_var": "totally_awesome"
}

Example usage of the env context

This example workflow shows how the env context can be configured at the workflow, job, and step levels, as well as using the context in steps.

Quando mais de uma variável de ambiente é definida com o mesmo nome, GitHub usa a variável de ambiente mais específica. Por exemplo, uma variável de ambiente definida em uma etapa substituirá variáveis de trabalho e de fluxo de trabalho pelo mesmo nome enquanto a etapa é executada. Uma variável definida para um trabalho substituirá uma variável de fluxo de trabalho com o mesmo nome, enquanto o trabalho é executado.

YAML
name: Hi Mascot
on: push
env:
  mascot: Mona
  super_duper_var: totally_awesome

jobs:
  windows_job:
    runs-on: windows-latest
    steps:
      - run: echo 'Hi ${{ env.mascot }}'  # Hi Mona
      - run: echo 'Hi ${{ env.mascot }}'  # Hi Octocat
        env:
          mascot: Octocat
  linux_job:
    runs-on: ubuntu-latest
    env:
      mascot: Tux
    steps:
      - run: echo 'Hi ${{ env.mascot }}'  # Hi Tux

job context

The job context contains information about the currently running job.

Property nameTypeDescription
jobobjectThis context changes for each job in a workflow run. You can access this context from any step in a job. This object contains all the properties listed below.
job.containerobjectInformation about the job's container. For more information about containers, see "Workflow syntax for GitHub Actions."
job.container.idstringThe ID of the container.
job.container.networkstringThe ID of the container network. The runner creates the network used by all containers in a job.
job.servicesobjectThe service containers created for a job. For more information about service containers, see "Workflow syntax for GitHub Actions."
job.services.<service_id>.idstringThe ID of the service container.
job.services.<service_id>.networkstringThe ID of the service container network. The runner creates the network used by all containers in a job.
job.services.<service_id>.portsobjectThe exposed ports of the service container.
job.statusstringThe current status of the job. Possible values are success, failure, or cancelled.

Example contents of the job context

This example job context uses a PostgreSQL service container with mapped ports. If there are no containers or service containers used in a job, the job context only contains the status property.

{
  "status": "success",
  "container": {
    "network": "github_network_53269bd575974817b43f4733536b200c"
  },
  "services": {
    "postgres": {
      "id": "60972d9aa486605e66b0dad4abb638dc3d9116f566579e418166eedb8abb9105",
      "ports": {
        "5432": "49153"
      },
      "network": "github_network_53269bd575974817b43f4733536b200c"
    }
  }
}

Example usage of the job context

This example workflow configures a PostgreSQL service container, and automatically maps port 5432 in the service container to a randomly chosen available port on the host. The job context is used to access the number of the port that was assigned on the host.

YAML
name: PostgreSQL Service Example
on: push
jobs:
  postgres-job:
    runs-on: ubuntu-latest
    services:
      postgres:
        image: postgres
        env:
          POSTGRES_PASSWORD: postgres
        options: --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5
        ports:
          # Maps TCP port 5432 in the service container to a randomly chosen available port on the host.
          - 5432

    steps:
      - uses: actions/checkout@v3
      - run: pg_isready -h localhost -p ${{ job.services.postgres.ports[5432] }}
      - run: ./run-tests

jobs context

The jobs context is only available in reusable workflows, and can only be used to set outputs for a reusable workflow. For more information, see "Reusing workflows."

Property nameTypeDescription
jobsobjectThis is only available in reusable workflows, and can only be used to set outputs for a reusable workflow. This object contains all the properties listed below.
jobs.<job_id>.resultstringThe result of a job in the reusable workflow. Possible values are success, failure, cancelled, or skipped.
jobs.<job_id>.outputsobjectThe set of outputs of a job in a reusable workflow.
jobs.<job_id>.outputs.<output_name>stringThe value of a specific output for a job in a reusable workflow.

Example contents of the jobs context

This example jobs context contains the result and outputs of a job from a reusable workflow run.

{
  "example_job": {
    "result": "success",
    "outputs": {
      "output1": "hello",
      "output2": "world"
    }
  }
}

Example usage of the jobs context

This example reusable workflow uses the jobs context to set outputs for the reusable workflow. Note how the outputs flow up from the steps, to the job, then to the workflow_call trigger. For more information, see "Reusing workflows."

YAML
name: Reusable workflow

on:
  workflow_call:
    # Map the workflow outputs to job outputs
    outputs:
      firstword:
        description: "The first output string"
        value: ${{ jobs.example_job.outputs.output1 }}
      secondword:
        description: "The second output string"
        value: ${{ jobs.example_job.outputs.output2 }}

jobs:
  example_job:
    name: Generate output
    runs-on: ubuntu-latest
    # Map the job outputs to step outputs
    outputs:
      output1: ${{ steps.step1.outputs.firstword }}
      output2: ${{ steps.step2.outputs.secondword }}
    steps:
      - id: step1
        run: echo "::set-output name=firstword::hello"
      - id: step2
        run: echo "::set-output name=secondword::world"

steps context

The steps context contains information about the steps in the current job that have an id specified and have already run.

Property nameTypeDescription
stepsobjectThis context changes for each step in a job. You can access this context from any step in a job. This object contains all the properties listed below.
steps.<step_id>.outputsobjectThe set of outputs defined for the step. For more information, see "Metadata syntax for GitHub Actions."
steps.<step_id>.conclusionstringThe result of a completed step after continue-on-error is applied. Possible values are success, failure, cancelled, or skipped. When a continue-on-error step fails, the outcome is failure, but the final conclusion is success.
steps.<step_id>.outcomestringThe result of a completed step before continue-on-error is applied. Possible values are success, failure, cancelled, or skipped. When a continue-on-error step fails, the outcome is failure, but the final conclusion is success.
steps.<step_id>.outputs.<output_name>stringThe value of a specific output.

Example contents of the steps context

This example steps context shows two previous steps that had an id specified. The first step had the id named checkout, the second generate_number. The generate_number step had an output named random_number.

{
  "checkout": {
    "outputs": {},
    "outcome": "success",
    "conclusion": "success"
  },
  "generate_number": {
    "outputs": {
      "random_number": "1"
    },
    "outcome": "success",
    "conclusion": "success"
  }
}

Example usage of the steps context

This example workflow generates a random number as an output in one step, and a later step uses the steps context to read the value of that output.

YAML
name: Generate random failure
on: push
jobs:
  randomly-failing-job:
    runs-on: ubuntu-latest
    steps:
      - id: checkout
        uses: actions/checkout@v3
      - name: Generate 0 or 1
        id: generate_number
        run:  echo "::set-output name=random_number::$(($RANDOM % 2))"
      - name: Pass or fail
        run: |
          if [[ ${{ steps.generate_number.outputs.random_number }} == 0 ]]; then exit 0; else exit 1; fi

runner context

The runner context contains information about the runner that is executing the current job.

Property nameTypeDescription
runnerobjectThis context changes for each job in a workflow run. This object contains all the properties listed below.
runner.namestringO nome do executor que executa a tarefa.
runner.osstringO sistema operacional do executor que está executando o trabalho. Os valores possíveis são Linux, Windows, ou macOS.
runner.archstringA arquitetura do executor que está executando o trabalho. Os valores possíveis são X86, X64, ARM ou ARM64.
runner.tempstringO caminho para um diretório temporário no executor. Este diretório é esvaziado no início e no final de cada trabalho. Observe que os arquivos não serão removidos se a conta de usuário do executor não tiver permissão para excluí-los.
runner.tool_cachestringO caminho para o diretório que contém ferramentas pré-instaladas para executores hospedados em GitHub. Para obter mais informações, confira "Sobre os executores hospedados no GitHub".
runner.debugstringIsso será definido somente se o log de depuração estiver habilitado e sempre tiver o valor de 1. Pode ser útil como um indicador para habilitar a depuração adicional ou o log detalhado em suas etapas de trabalho.

Example contents of the runner context

The following example context is from a Linux GitHub-hosted runner.

{
  "os": "Linux",
  "arch": "X64",
  "name": "GitHub Actions 2",
  "tool_cache": "/opt/hostedtoolcache",
  "temp": "/home/runner/work/_temp"
}

Example usage of the runner context

This example workflow uses the runner context to set the path to the temporary directory to write logs, and if the workflow fails, it uploads those logs as artifact.

YAML
name: Build
on: push

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - name: Build with logs
        run: |
          mkdir ${{ runner.temp }}/build_logs
          ./build.sh --log-path ${{ runner.temp }}/build_logs
      - name: Upload logs on fail
        if: ${{ failure() }}
        uses: actions/upload-artifact@v3
        with:
          name: Build failure logs
          path: ${{ runner.temp }}/build_logs

secrets context

The secrets context contains the names and values of secrets that are available to a workflow run. The secrets context is not available for composite actions due to security reasons. If you want to pass a secret to a composite action, you need to do it explicitly as an input. For more information about secrets, see "Encrypted secrets."

GITHUB_TOKEN is a secret that is automatically created for every workflow run, and is always included in the secrets context. For more information, see "Automatic token authentication."

Aviso: o GitHub elimina de modo automático os segredos impressos no log, mas você deve evitar imprimir segredos no log intencionalmente.

Property nameTypeDescription
secretsobjectThis context is the same for each job in a workflow run. You can access this context from any step in a job. This object contains all the properties listed below.
secrets.GITHUB_TOKENstringAutomatically created token for each workflow run. For more information, see "Automatic token authentication."
secrets.<secret_name>stringThe value of a specific secret.

Example contents of the secrets context

The following example contents of the secrets context shows the automatic GITHUB_TOKEN, as well as two other secrets available to the workflow run.

{
  "github_token": "***",
  "NPM_TOKEN": "***",
  "SUPERSECRET": "***"
}

Example usage of the secrets context

Este exemplo de fluxo de trabalho usa a ação do rotulador, que requer o GITHUB_TOKEN como o valor para o parâmetro de entrada repo-token:

YAML
name: Pull request labeler
on: [ pull_request_target ]

permissions:
  contents: read
  pull-requests: write

jobs:
  triage:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/labeler@v4
        with:
          repo-token: ${{ secrets.GITHUB_TOKEN }}

strategy context

For workflows with a matrix, the strategy context contains information about the matrix execution strategy for the current job.

Property nameTypeDescription
strategyobjectThis context changes for each job in a workflow run. You can access this context from any job or step in a workflow. This object contains all the properties listed below.
strategy.fail-fastbooleanWhen true, all in-progress jobs are canceled if any job in a matrix fails. For more information, see "Workflow syntax for GitHub Actions."
strategy.job-indexnumberThe index of the current job in the matrix. Note: This number is a zero-based number. The first job's index in the matrix is 0.
strategy.job-totalnumberThe total number of jobs in the matrix. Note: This number is not a zero-based number. For example, for a matrix with four jobs, the value of job-total is 4.
strategy.max-parallelnumberThe maximum number of jobs that can run simultaneously when using a matrix job strategy. For more information, see "Workflow syntax for GitHub Actions."

Example contents of the strategy context

The following example contents of the strategy context is from a matrix with four jobs, and is taken from the final job. Note the difference between the zero-based job-index number, and job-total which is not zero-based.

{
  "fail-fast": true,
  "job-index": 3,
  "job-total": 4,
  "max-parallel": 4
}

Example usage of the strategy context

This example workflow uses the strategy.job-index property to set a unique name for a log file for each job in a matrix.

YAML
name: Test matrix
on: push

jobs:
  test:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        test-group: [1, 2]
        node: [14, 16]
    steps:
      - uses: actions/checkout@v3
      - run: npm test > test-job-${{ strategy.job-index }}.txt
      - name: Upload logs
        uses: actions/upload-artifact@v3
        with:
          name: Build log for job ${{ strategy.job-index }}
          path: test-job-${{ strategy.job-index }}.txt

matrix context

For workflows with a matrix, the matrix context contains the matrix properties defined in the workflow file that apply to the current job. For example, if you configure a matrix with the os and node keys, the matrix context object includes the os and node properties with the values that are being used for the current job.

There are no standard properties in the matrix context, only those which are defined in the workflow file.

Property nameTypeDescription
matrixobjectThis context is only available for jobs in a matrix, and changes for each job in a workflow run. You can access this context from any job or step in a workflow. This object contains the properties listed below.
matrix.<property_name>stringThe value of a matrix property.

Example contents of the matrix context

The following example contents of the matrix context is from a job in a matrix that has the os and node matrix properties defined in the workflow. The job is executing the matrix combination of an ubuntu-latest OS and Node.js version 16.

{
  "os": "ubuntu-latest",
  "node": 16
}

Example usage of the matrix context

This example workflow creates a matrix with os and node keys. It uses the matrix.os property to set the runner type for each job, and uses the matrix.node property to set the Node.js version for each job.

YAML
name: Test matrix
on: push

jobs:
  build:
    runs-on: ${{ matrix.os }}
    strategy:
      matrix:
        os: [ubuntu-latest, windows-latest]
        node: [14, 16]
    steps:
      - uses: actions/checkout@v3
      - uses: actions/setup-node@v3
        with:
          node-version: ${{ matrix.node }}
      - name: Install dependencies
        run: npm ci
      - name: Run tests
        run: npm test

needs context

The needs context contains outputs from all jobs that are defined as a direct dependency of the current job. Note that this doesn't include implicitly dependent jobs (for example, dependent jobs of a dependent job). For more information on defining job dependencies, see "Workflow syntax for GitHub Actions."

Property nameTypeDescription
needsobjectThis context is only populated for workflow runs that have dependent jobs, and changes for each job in a workflow run. You can access this context from any job or step in a workflow. This object contains all the properties listed below.
needs.<job_id>objectA single job that the current job depends on.
needs.<job_id>.outputsobjectThe set of outputs of a job that the current job depends on.
needs.<job_id>.outputs.<output name>stringThe value of a specific output for a job that the current job depends on.
needs.<job_id>.resultstringThe result of a job that the current job depends on. Possible values are success, failure, cancelled, or skipped.

Example contents of the needs context

The following example contents of the needs context shows information for two jobs that the current job depends on.

{
  "build": {
    "result": "success",
    "outputs": {
      "build_id": "ABC123"
    }
  },
  "deploy": {
    "result": "failure",
    "outputs": {}
  }
}

Example usage of the needs context

This example workflow has three jobs: a build job that does a build, a deploy job that requires the build job, and a debug job that requires both the build and deploy jobs and runs only if there is a failure in the workflow. The deploy job also uses the needs context to access an output from the build job.

YAML
name: Build and deploy
on: push

jobs:
  build:
    runs-on: ubuntu-latest
    outputs:
      build_id: ${{ steps.build_step.outputs.build_id }}
    steps:
      - uses: actions/checkout@v3
      - name: Build
        id: build_step
        run: |
          ./build
          echo "::set-output name=build_id::$BUILD_ID"
  deploy:
    needs: build
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - run: ./deploy --build ${{ needs.build.outputs.build_id }}
  debug:
    needs: [build, deploy]
    runs-on: ubuntu-latest
    if: ${{ failure() }}
    steps:
      - uses: actions/checkout@v3
      - run: ./debug

inputs context

The inputs context contains input properties passed to an action or to a reusable workflow. The input names and types are defined in the workflow_call event configuration of a reusable workflow, and the input values are passed from jobs.<job_id>.with in an external workflow that calls the reusable workflow.

There are no standard properties in the inputs context, only those which are defined in the workflow file.

Property nameTypeDescription
inputsobjectThis context is only available in a reusable workflow. You can access this context from any job or step in a workflow. This object contains the properties listed below.
inputs.<name>string or number or booleanEach input value passed from an external workflow.

Example contents of the inputs context

The following example contents of the inputs context is from a workflow that has defined the build_id, deploy_target, and perform_deploy inputs.

{
  "build_id": 123456768,
  "deploy_target": "deployment_sys_1a",
  "perform_deploy": true
}

Example usage of the inputs context in a reusable workflow

This example reusable workflow uses the inputs context to get the values of the build_id, deploy_target, and perform_deploy inputs that were passed to the reusable workflow from the caller workflow.

YAML
name: Reusable deploy workflow
on:
  workflow_call:
    inputs:
      build_id:
        required: true
        type: number
      deploy_target:
        required: true
        type: string
      perform_deploy:
        required: true
        type: boolean

jobs:
  deploy:
    runs-on: ubuntu-latest
    if: ${{ inputs.perform_deploy }}
    steps:
      - name: Deploy build to target
        run: deploy --build ${{ inputs.build_id }} --target ${{ inputs.deploy_target }}