About workflows
Рабочий процесс — это настраиваемый автоматизированный процесс, который будет выполнять одно или несколько заданий. Рабочие процессы определяются файлом YAML, возвращенным в репозиторий, и будут выполняться при активации события в репозитории. Либо их можно активировать вручную или по определенному расписанию.
Рабочие процессы определяются в каталоге .github/workflows
в репозитории. Репозиторий может иметь несколько рабочих процессов, каждый из которых может выполнять различные задачи, такие как:
- Создание и тестирование запросов на вытягивание
- Развертывание приложения при каждом создании выпуска
- Добавление метки при открытии новой проблемы
Workflow basics
A workflow must contain the following basic components:
- One or more events that will trigger the workflow.
- One or more jobs, each of which will execute on a runner machine and run a series of one or more steps.
- Each step can either run a script that you define or run an action, which is a reusable extension that can simplify your workflow.
For more information on these basic components, see Общие сведения о GitHub Actions.
Triggering a workflow
Триггеры рабочего процесса — это события, которые приводят к запуску рабочего процесса. Эти события могут быть следующими:
- События, происходящие в репозитории рабочего процесса
- События, происходящие за пределами GitHub и активируют
repository_dispatch
событие на GitHub - Запланированное время
- Руководство
Например, можно настроить рабочий процесс для запуска при отправке в ветвь по умолчанию репозитория, при создании выпуска или при открытии проблемы.
For more information, see Активация рабочего процесса, and for a full list of events, see События, инициирующие рабочие процессы.
Workflow syntax
Workflows are defined using YAML. For the full reference of the YAML syntax for authoring workflows, see Синтаксис рабочего процесса для GitHub Actions.
For more on managing workflow runs, such as re-running, cancelling, or deleting a workflow run, see Управление запусками рабочих процессов и развертываниями.
Using workflow templates
GitHub предоставляет предварительно настроенные шаблоны рабочих процессов, которые можно использовать как есть или настраивать для создания собственного рабочего процесса. GitHub анализирует код и показывает шаблоны рабочих процессов, которые могут быть полезны для репозитория. Например, если репозиторий содержит код Node.js, вы увидите предложения для проектов Node.js.
Эти шаблоны рабочих процессов предназначены для быстрого и быстрого запуска, предлагая ряд конфигураций, таких как:
- CI: рабочие процессы непрерывной интеграции
- Развертывания: рабочие процессы развертывания
- Автоматизация: автоматизация рабочих процессов
- Сканирование кода: рабочие процессы сканирования кода
- Страницы: рабочие процессы страниц
Используйте эти рабочие процессы в качестве отправного места для создания пользовательского рабочего процесса или их использования как есть. Полный список шаблонов рабочих процессов можно просмотреть в репозитории действий и начальных рабочих процессов.
Advanced workflow features
This section briefly describes some of the advanced features of GitHub Actions that help you create more complex workflows.
Storing secrets
If your workflows use sensitive data, such as passwords or certificates, you can save these in GitHub as secrets and then use them in your workflows as environment variables. This means that you will be able to create and share workflows without having to embed sensitive values directly in the workflow's YAML source.
This example job demonstrates how to reference an existing secret as an environment variable, and send it as a parameter to an example command.
jobs:
example-job:
runs-on: ubuntu-latest
steps:
- name: Retrieve secret
env:
super_secret: ${{ secrets.SUPERSECRET }}
run: |
example-command "$super_secret"
For more information, see Использование секретов в GitHub Actions.
Creating dependent jobs
By default, the jobs in your workflow all run in parallel at the same time. If you have a job that must only run after another job has completed, you can use the needs
keyword to create this dependency. If one of the jobs fails, all dependent jobs are skipped; however, if you need the jobs to continue, you can define this using the if
conditional statement.
In this example, the setup
, build
, and test
jobs run in series, with build
and test
being dependent on the successful completion of the job that precedes them:
jobs:
setup:
runs-on: ubuntu-latest
steps:
- run: ./setup_server.sh
build:
needs: setup
runs-on: ubuntu-latest
steps:
- run: ./build_server.sh
test:
needs: build
runs-on: ubuntu-latest
steps:
- run: ./test_server.sh
For more information, see Использование заданий в рабочем процессе.
Using a matrix
Стратегия матрицы позволяет использовать переменные в одном определении задания для автоматического создания нескольких выполнений заданий, основанных на сочетаниях переменных. Например, можно использовать стратегию матрицы для тестирования кода в нескольких версиях языка или в нескольких операционных системах. The matrix is created using the strategy
keyword, which receives the build options as an array. For example, this matrix will run the job multiple times, using different versions of Node.js:
jobs:
build:
runs-on: ubuntu-latest
strategy:
matrix:
node: [14, 16]
steps:
- uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node }}
For more information, see Выполнение вариантов заданий в рабочем процессе.
Caching dependencies
If your jobs regularly reuse dependencies, you can consider caching these files to help improve performance. Once the cache is created, it is available to all workflows in the same repository.
This example demonstrates how to cache the ~/.npm
directory:
jobs:
example-job:
steps:
- name: Cache node modules
uses: actions/cache@v4
env:
cache-name: cache-node-modules
with:
path: ~/.npm
key: ${{ runner.os }}-build-${{ env.cache-name }}-${{ hashFiles('**/package-lock.json') }}
restore-keys: |
${{ runner.os }}-build-${{ env.cache-name }}-
For more information, see Кэширование зависимостей для ускорения рабочих процессов.
Using databases and service containers
If your job requires a database or cache service, you can use the services
keyword to create an ephemeral container to host the service; the resulting container is then available to all steps in that job and is removed when the job has completed. This example demonstrates how a job can use services
to create a postgres
container, and then use node
to connect to the service.
jobs:
container-job:
runs-on: ubuntu-latest
container: node:20-bookworm-slim
services:
postgres:
image: postgres
steps:
- name: Check out repository code
uses: actions/checkout@v4
- name: Install dependencies
run: npm ci
- name: Connect to PostgreSQL
run: node client.js
env:
POSTGRES_HOST: postgres
POSTGRES_PORT: 5432
For more information, see Использование контейнерных служб.
Using labels to route workflows
If you want to be sure that a particular type of runner will process your job, you can use labels to control where jobs are executed. You can assign labels to a self-hosted runner in addition to their default label of self-hosted
. Then, you can refer to these labels in your YAML workflow, ensuring that the job is routed in a predictable way. GitHub-hosted runners have predefined labels assigned.
This example shows how a workflow can use labels to specify the required runner:
jobs:
example-job:
runs-on: [self-hosted, linux, x64, gpu]
A workflow will only run on a runner that has all the labels in the runs-on
array. The job will preferentially go to an idle self-hosted runner with the specified labels.
To learn more about self-hosted runner labels, see Использование меток с самостоятельно размещенными средствами выполнения.
Reusing workflows
Рабочие процессы можно совместно использовать в организации, публично или в частном порядке, вызвав один рабочий процесс из другого рабочего процесса. Это позволяет повторно использовать рабочие процессы, избегая дублирования и упрощая обслуживание рабочих процессов. Дополнительные сведения см. в разделе Повторное использование рабочих процессов.
Security hardening for workflows
GitHub предоставляет функции безопасности, которые можно использовать для повышения безопасности рабочих процессов. Встроенные функции %% данных variables.product.prodname_dotcom %}позволяют получать уведомления об уязвимостях в используемых действиях или автоматизировать процесс поддержания действий в рабочих процессах. Дополнительные сведения см. в разделе Использование функций безопасности GitHub для защиты использования GitHub Actions.
Using environments
You can configure environments with protection rules and secrets to control the execution of jobs in a workflow. Each job in a workflow can reference a single environment. Any protection rules configured for the environment must pass before a job referencing the environment is sent to a runner. For more information, see Управление средами для развертывания.