GitHub Actions помогает автоматизировать такие задачи, как сборка, тестирование и развертывание в вашем репозитории GitHub.
Одним щелчком мыши вы можете опубликовать готовый код или пакет на npm, GitHub Pages, как образ docker, развернуть продакшен-код у облачного провайдера и так далее.
Проблемы начинаются, когда вы решаетесь испытать GitHub Actions. Это может занять много времени и обернуться головной болью. Сперва вам нужно локально изменить файл GitHub Actions, затем перенести локальный код в репозиторий GitHub и ждать результата.
Чтобы решить эту проблему, вы можете использовать act — инструмент командной строки (CLI) для тестирования и написания GitHub action («действия» GitHub) локально. Благодаря act вам не нужно будет коммитить / пушить свой локальный код в репозиторий GitHub. Вы сможете протестировать GitHub action локально, на своей машине.
В этой статье мы разберем:
Как установить act для работы с GitHub Actions
Инструмент act работает с Docker. Поэтому, прежде чем приступить к работе с act, сначала установите Docker в свою систему.
От редакции Techrocks: подробнее о Docker можно почитать, например, в обзорной статье «Docker: практическое руководство для начинающих».
Чтобы установить act, вам нужно выполнить следующую команду:
# Window
choco install act-cli
# MacOS
brew install act
# Linux
curl https://raw.githubusercontent.com/nektos/act/master/install.sh | sudo bash
Как настроить и инициализировать act
После успешной установки act на вашу машину нужно запустить его в вашем проекте.
Во время установки act спрашивает, какой размер образа Docker должен быть установлен: большой, средний или микро.
Образы Docker бывают разного размера; выбирать нужно соответственно нуждам проекта:
Docker Micro имеет размер 200 МБ. Такой образ годится для небольших проектов.
Размер образа Docker Medium — 500 МБ, его используют большие проекты.
Docker Large — 17 ГБ, его используют корпоративные проекты.
Act использует образ Docker для локального запуска GitHub action.
$ act
Вывод команды в терминале выглядит следующим образом:
$ test-github-actions git:(main) ✗ act
? Please choose the default image you want to use with act:
— Large size image: ca. 17GB download + 53.1GB storage, you will need 75GB of free disk space, snapshots of GitHub Hosted Runners without snap and pulled docker images
— Medium size image: ~500MB, includes only necessary tools to bootstrap actions and aims to be compatible with most actions
— Micro size image: <200MB, contains only NodeJS required to bootstrap actions, doesn’t work with all actions
Default image and other options can be changed manually in ~/.actrc (please refer to https://github.com/nektos/act#configuration for additional information about file structure) Micro
[Build Ghost and test theme/install] Start image=node:16-buster-slim
INFO[0023] Parallel tasks (0) below minimum, setting to 1
[Build Ghost and test theme/install] docker pull image=node:16-buster-slim platform= username= forcePull=true
INFO[0031] Parallel tasks (0) below minimum, setting to 1
[Build Ghost and test theme/install] docker create image=node:16-buster-slim platform= entrypoint=[«tail» «-f» «/dev/null»] cmd=[] network=»host»
[Build Ghost and test theme/install] docker run image=node:16-buster-slim platform= entrypoint=[«tail» «-f» «/dev/null»] cmd=[] network=»host»
[Build Ghost and test theme/install] git clone ‘https://github.com/vimtor/action-zip’ # ref=v1.2
[Build Ghost and test theme/install] git clone ‘https://github.com/softprops/action-gh-release’ # ref=v0.1.15
[Build Ghost and test theme/install] Run Main actions/checkout@v4
[Build Ghost and test theme/install] docker cp src=/home/officialrajdeepsingh/medium/test-github-actions/. dst=/home/officialrajdeepsingh/medium/test-github-actions
[Build Ghost and test theme/install] Success — Main actions/checkout@v4
[Build Ghost and test theme/install] Run Main Easy Zip Files
[Build Ghost and test theme/install] docker cp src=/home/officialrajdeepsingh/.cache/act/vimtor-action-zip@v1.2/ dst=/var/run/act/actions/vimtor-action-zip@v1.2/
[Build Ghost and test theme/install] docker exec cmd=[node /var/run/act/actions/vimtor-action-zip@v1.2/dist/index.js] user= workdir=
| Ready to zip «build/ home.txt» into example.zip
| — build/
| — home.txt
|
| Zipped file example.zip successfully
[Build Ghost and test theme/install] Success — Main Easy Zip Files
[Build Ghost and test theme/install] Cleaning up container for job install
[Build Ghost and test theme/install] Job succeeded
В этом примере мы использовали микро-образ.
После загрузки образа из Docker-репозитория act запускает GitHub action.
Для настройки act генерирует файл ~/.actrc на вашей машине. Этот файл содержит имя образа Docker.
# .actrc
-P ubuntu-latest=node:16-buster-slim
-P ubuntu-22.04=node:16-bullseye-slim
-P ubuntu-20.04=node:16-buster-slim
-P ubuntu-18.04=node:16-buster-slim
Чтобы установить другие образы Docker, удалите файл ~/.actrc и повторно запустите act.
Возможная ошибка при инициализации
Из-за зависимости от Docker мы можем столкнуться с некоторыми ошибками при первой инициализации act CLI.
$ act
Выглядеть ошибка может следующим образом:
$ test-github-actions git:(main) ✗ act
ERRO[0000] daemon Docker Engine socket not found and containerDaemonSocket option was not set
? Please choose the default image you want to use with act:
— Large size image: ca. 17GB download + 53.1GB storage, you will need 75GB of free disk space, snapshots of GitHub Hosted Runners without snap and pulled docker images
— Medium size image: ~500MB, includes only necessary tools to bootstrap actions and aims to be compatible with most actions
— Micro size image: <200MB, contains only NodeJS required to bootstrap actions, doesn’t work with all actions
Default image and other options can be changed manually in ~/.actrc (please refer to https://github.com/nektos/act#configuration for additional information about file structure) Micro
[Build Ghost and test theme/install] Start image=node:16-buster-slim
INFO[0305] Parallel tasks (0) below minimum, setting to 1
[Build Ghost and test theme/install] docker pull image=node:16-buster-slim platform= username= forcePull=true
Error: Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?
В приведенном коде вы видите ошибку «Cannot connect to the Docker daemon». Она возникает из-за демона Docker. Проще говоря, демон Docker не запущен. Проблема решается просто: нужно запустить Docker и повторно выполнить команду act.
Есть два способа запуска сервисов Docker:
Откройте десктопное приложение Docker в своем окне, и ваш сервис Docker будет запущен.
Запустите Docker с помощью команды systemctl start docker в Linux.
Проверить, запущен ли ваш Docker, можно с помощью следующей команды:
$ systemctl status docker
● docker.service — Docker Application Container Engine
Loaded: loaded (/etc/systemd/system/docker.service; enabled; preset: enabled)
Drop-In: /nix/store/fibzdkfv6in4xw39rm0c7bq4nadzisas-system-units/docker.service.d
└─overrides.conf
Active: active (running) since Mon 2024-02-26 12:38:37 IST; 3h 39min ago
TriggeredBy: ● docker.socket
Docs: https://docs.docker.com
Main PID: 1186 (dockerd)
IP: 0B in, 0B out
IO: 109.0M read, 152.0K written
Tasks: 40
Memory: 148.5M
CPU: 1min 40.817s
CGroup: /system.slice/docker.service
├─1186 /nix/store/7pzis8dkhs461kl1bg2fp0202dw6r5i5-moby-24.0.5/libexec/docker/dockerd —config-file=/nix/store/3rlv5f0zldcc120b01szywidl0qz9x4p-daemon.json
└─1256 containerd —config /var/run/docker/containerd/containerd.toml
Feb 26 12:38:37 nixos dockerd[1256]: time=»2024-02-26T12:38:37.532987858+05:30″ level=info msg=»containerd successfully booted in 0.016901s»
Feb 26 12:38:37 nixos dockerd[1186]: time=»2024-02-26T12:38:37.562515048+05:30″ level=info msg=»[graphdriver] using prior storage driver: overlay2″
Feb 26 12:38:37 nixos dockerd[1186]: time=»2024-02-26T12:38:37.564062690+05:30″ level=info msg=»Loading containers: start.»
Feb 26 12:38:37 nixos dockerd[1186]: time=»2024-02-26T12:38:37.778478313+05:30″ level=info msg=»Default bridge (docker0) is assigned with an IP address 172.17.0.0/16. Daemon option —bip can be used to set a preferred IP address»
Feb 26 12:38:37 nixos dockerd[1186]: time=»2024-02-26T12:38:37.805931545+05:30″ level=info msg=»Loading containers: done.»
Feb 26 12:38:37 nixos dockerd[1186]: time=»2024-02-26T12:38:37.828589904+05:30″ level=info msg=»Docker daemon» commit=v24.0.5 graphdriver=overlay2 version=24.0.5
Feb 26 12:38:37 nixos dockerd[1186]: time=»2024-02-26T12:38:37.828929197+05:30″ level=info msg=»Daemon has completed initialization»
Feb 26 12:38:37 nixos systemd[1]: Started Docker Application Container Engine.
Feb 26 12:38:37 nixos dockerd[1186]: time=»2024-02-26T12:38:37.841992729+05:30″ level=info msg=»API listen on /run/docker.sock»
Feb 26 12:38:37 nixos dockerd[1186]: time=»2024-02-26T12:38:37.841993669+05:30″ level=info msg=»API listen on /run/docker.sock»
Как использовать act
У инструмента act много опций, но мы рассмотрим только несколько наиболее важных. Чтобы просмотреть все опции, выполните команду act —help.
Вот некоторые функции act CLI, доступные при использовании опций:
События
Списки
Запуск определенных заданий
Граф
Переменные среды
Секреты
События
В act действие по умолчанию — это push. Это действие, опять же, по умолчанию, запускает только события push.
Запуск act с дефолтным событием push:
$ act
Вы можете изменить событие, передав второй аргумент — имя вашего действия. В нашем случае мы передадим pull_request.
$ act pull_request
Доступных триггеров для запуска рабочих процессов довольно много. Вы можете ознакомиться с ними в документации по GitHub action.
Списки
Опция -l выводит список всех доступных заданий, которые вы записали в .github/workflows.
$ act -l
Вывод команды в терминале выглядит следующим образом:
$ act -l
Stage Job ID Job name Workflow name Workflow file Events
0 zip zip Convert files into Zip build-project.yml release
0 request_test request_test Pull Request fork.yml fork
0 pull_request_test pull_request_test Pull Request issues.yml issues
0 show show Convert files into Zip folder test.yml pull_request
Запуск определенных заданий
С помощью опции —job вы можете запускать определенные задания из ваших workflows.
Следите за тем, чтобы имя задания было уникальным, иначе будут запущены все задания с таким же именем в вашем workflow. Если вы не можете передать событие по умолчанию, запустите событие push.
Синтаксис:
act —job <имя-вашего-задания>
Допустим, мы запускаем конкретное задание — show:
$ act —job ‘show’
Граф
Опция —graph отображает структуру доступных заданий рабочего процесса в терминале в схематическом виде.
$ act —graph
Вывод команды выглядит следующим образом:
$ act —graph
╭─────╮ ╭──────────────╮ ╭───────────────────╮ ╭──────╮
│ zip │ │ request_test │ │ pull_request_test │ │ show │
╰─────╯ ╰──────────────╯ ╰───────────────────╯ ╰──────╯
Переменные окружения
Использовать переменные окружения в act очень просто. Вам нужно только создать новый файл .env. Окружение, доступное в файле .env, act загружает автоматически. Например, мы добавляем переменную ENV_ID.
# .env
ENV_ID=’My Env’
Чтобы использовать переменные окружения ENV_ID, используйте синтаксис ${{ env.ENV_ID }} в вашем GitHub action:
# .github/workflows/test.yml
name: Convert files into Zip folder
on: pull_request
jobs:
show:
runs-on: ubuntu-latest
steps:
— name: Show Env
run: echo «Env ${{ env.ENV_ID }}»
С помощью опции —env-file можно изменить дефолтное имя файла .env на my-custom.env.
$ act —env-file=my-custom.env
Секреты
Чтобы загружать секреты окружения с помощью act, нужно создать новый файл .secrets. При этом секреты окружения, доступные в файле secrets, загружаются автоматически. Например, мы добавляем переменные APP_SECRET и APP_ID.
APP_SECRET=’7824jurd789gyu45esxgfgf48822166974gtredsyujn’
APP_ID=’7878974561587′
Чтобы использовать переменные окружения APP_SECRET, используйте синтаксис ${{ secrets.APP_SECRE}} в вашем GitHub action:
# .github/workflows/test.yml
name: Learn environment secrets
on: pull_request
jobs:
show:
runs-on: ubuntu-latest
steps:
— name: Show env
run: echo «App SECRET ${{ secrets.APP_SECRET }}»
— name: Show varibale
run: echo «App ID ${{ secrets.APP_ID }}»
Вы можете загрузить свой собственный файл my-custom.secrets, содержащий все ваши секреты, с помощью опции —secret-file.
$ act —secret-file=my-custom.secrets
Заключение
Инструмент командной строки act помогает сэкономить время и силы при локальной работе с GitHub. На данный момент нет другого инструмента, который позволял бы запускать GitHub actions локально.
Но и act не полностью совместим с GitHub actions. Некоторые функции не реализованы, например, параллелизм, нет контекста vars, контекст github неполон и так далее.
Перевод статьи «How to Run GitHub Actions Locally Using the act CLI Tool».
Запись Как запустить GitHub Actions локально впервые появилась techrocks.ru.