Workflow commands for github actions

Supported software

The software tools included in GitHub-hosted runners are updated weekly. The update process takes several days, and the list of preinstalled software on the branch is updated after the whole deployment ends.

Preinstalled software

Workflow logs include a link to the preinstalled tools on the exact runner. To find this information in the workflow log, expand the section. Under that section, expand the section. The link following will describe the preinstalled tools on the runner that ran the workflow.

For more information, see «Viewing workflow run history.»

For the overall list of included tools for each runner operating system, see the links below:

  • Ubuntu 20.04 LTS
  • Ubuntu 18.04 LTS
  • Windows Server 2022
  • Windows Server 2019
  • Windows Server 2016
  • macOS 11
  • macOS 10.15

GitHub-hosted runners include the operating system’s default built-in tools, in addition to the packages listed in the above references. For example, Ubuntu and macOS runners include , , and , among other default tools.

Using preinstalled software

We recommend using actions to interact with the software installed on runners. This approach has several benefits:

  • Usually, actions provide more flexible functionality like versions selection, ability to pass arguments, and parameters
  • It ensures the tool versions used in your workflow will remain the same regardless of software updates

If there is a tool that you’d like to request, please open an issue at actions/virtual-environments. This repository also contains announcements about all major software updates on runners.

Installing additional software

You can install additional software on GitHub-hosted runners. For more information, see «Customizing GitHub-hosted runners».

Creating a reusable workflow

Reusable workflows are YAML-formatted files, very similar to any other workflow file. As with other workflow files, you locate reusable workflows in the directory of a repository. Subdirectories of the directory are not supported.

For a workflow to be reusable, the values for must include :

Using inputs and secrets in a reusable workflow

You can define inputs and secrets, which can be passed from the caller workflow and then used within the called workflow. There are three stages to using an input or a secret in a reusable workflow.

  1. In the reusable workflow, use the and keywords to define inputs or secrets that will be passed from a caller workflow.

    For details of the syntax for defining inputs and secrets, see and .

  2. Reference the input or secret in the reusable workflow.

    In the example above, is an environment secret that’s been added to the environment. This environment is therefore referenced within the job.

    Note: Environment secrets are encrypted strings that are stored in an environment that you’ve defined for a repository. Environment secrets are only available to workflow jobs that reference the appropriate environment. For more information, see «.»

  3. Pass the input or secret from the caller workflow.

    To pass named inputs to a called workflow, use the keyword in a job. Use the keyword to pass named secrets. For inputs, the data type of the input value must match the type specified in the called workflow (either boolean, number, or string).

Example reusable workflow

This reusable workflow file named (we’ll refer to this later in the ) takes an input string and a secret from the caller workflow and uses them in an action.

Using a workflow template

GitHub provides preconfigured workflow templates that you can customize to create your own continuous integration workflow. GitHub analyzes your code and shows you CI templates that might be useful for your repository. For example, if your repository contains Node.js code, you’ll see suggestions for Node.js projects. You can use workflow templates as a starting place to build your custom workflow or use them as-is.

You can browse the full list of workflow templates in the actions/starter-workflows repository.

  1. On GitHub.com, navigate to the main page of the repository.
  2. Under your repository name, click Actions.

  3. If your repository already has existing workflows: In the upper-left corner, click New workflow.

  4. Under the name of the template you’d like to use, click Set up this workflow.

Using labels to route workflows

This feature helps you assign jobs to a specific hosted runner. 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 . Then, you can refer to these labels in your YAML workflow, ensuring that the job is routed in a predictable way.

This example shows how a workflow can use labels to specify the required runner:

A workflow will only run on a runner that has all the labels in the array. The job will preferentially go to an idle self-hosted runner with the specified labels. If none are available and a GitHub-hosted runner with the specified labels exists, the job will go to a GitHub-hosted runner.

To learn more about self-hosted runner labels, see «Using labels with self-hosted runners.»

Azure PowerShell

  • 1.0.0
  • 1.6.0
  • 2.3.2
  • 2.6.0
  • 2.8.0
  • 3.1.0
  • 3.5.0
Each major Go release is supported until there are two newer major releases. For example, Go 1.5 was supported until the Go 1.7 release, and Go 1.6 was supported until the Go 1.8 release. We fix critical problems, including critical security problems, in supported releases as needed by issuing minor revisions

GOLang

Go 1.11,1.12,1.13

Java:

  • Java 7
  • Default JDK set to 11

PHP

  • 7.1
  • 7.2
  • 7.3

Android:

  • «platforms;android-26»
  • «platforms;android-25»
  • «platforms;android-24»
  • «platforms;android-23»
  • «platforms;android-22»
  • «platforms;android-21»
  • «platforms;android-19»
  • «platforms;android-17»
  • «build-tools;26.0.3»
  • «build-tools;26.0.2»
  • «build-tools;26.0.1»
  • «build-tools;26.0.0»
  • «build-tools;25.0.3»
  • «build-tools;25.0.2»
  • «build-tools;25.0.1»
  • «build-tools;25.0.0»
  • «build-tools;24.0.3»
  • «build-tools;24.0.2»
  • «build-tools;24.0.1»
  • «build-tools;24.0.0»
  • «build-tools;23.0.3»
  • «build-tools;23.0.2»
  • «build-tools;23.0.1»
  • «build-tools;22.0.1»
  • «build-tools;21.1.2»
  • «build-tools;20.0.0»
  • «build-tools;19.1.0»
  • «add-ons;addon-google_apis-google-24»
  • «add-ons;addon-google_apis-google-23»
  • «add-ons;addon-google_apis-google-22»
  • «add-ons;addon-google_apis-google-21»
  • «cmake;3.6.4111459»

Using workflow commands to access toolkit functions

The actions/toolkit includes a number of functions that can be executed as workflow commands. Use the syntax to run the workflow commands within your YAML file; these commands are then sent to the runner over . For example, instead of using code to set an output, as below:

You can use the command in your workflow to set the same value:

The following table shows which toolkit functions are available within a workflow:

Toolkit function Equivalent workflow command
Accessible using environment file
Accessible using environment file
Accessible using environment variable
Accessible using environment variable
Accessible using environment variable
Used as a shortcut for and

Программы контроля версий

Все файлы исходного кода в проекте называются базой кода. В крупных проектах над кодовой базой часто работает много разработчиков. Каждое изменение кода необходимо отслеживать и идентифицировать. При необходимости изменения должны быть обратимыми. Если разные разработчики вносят изменения в один и тот же файл исходного кода, их правки необходимо объединить.

Поэтому неудивительно, что существуют программы, называемые системами контроля версий, чтобы упростить управление изменениями в кодовой базе. Системы контроля версий содержат все предыдущие версии каждого файла в базе кода, и каждое изменение записывается, комментируется и отслеживается.

Как передать какой-нибудь токен, нигде его не публикуя? Или что такое secrets в конфигах?

Всякие токены доступа, опубликованные в публичном доступе, это большой риск для вашей секьюрности. Как передавать их в зашифрованном виде? Гитхаб уже позаботился об этом, создав secrets. Их можно найти в любом репозитории: settings -> secrets. Там можно создать секрет с любым именем, например, MY_TOKEN, добавить к нему значение, и тогда в любом экшене можно будет написать , и это значение будет использоваться

Прикольные вещи:1. Один раз создав и сохранив секрет, посмотреть его значение будет уже нельзя, только обновить2. Если попытаться вывести значение секрета в логах или внутри кода экшена, выведется ***3. Однако лучше не логгировать секреты вообще, так как любую защиту такого рода все же можно обойти

Using labels to route workflows

This feature helps you assign jobs to a specific hosted runner. 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 . 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:

A workflow will only run on a runner that has all the labels in the array. The job will preferentially go to an idle self-hosted runner with the specified labels. If none are available and a GitHub-hosted runner with the specified labels exists, the job will go to a GitHub-hosted runner.

To learn more about self-hosted runner labels, see «Using labels with self-hosted runners.»

To learn more about GitHub-hosted runner labels, see .

Echoing command outputs

Enables or disables echoing of workflow commands. For example, if you use the command in a workflow, it sets an output parameter but the workflow run’s log does not show the command itself. If you enable command echoing, then the log shows the command, such as .

Command echoing is disabled by default. However, a workflow command is echoed if there are any errors processing the command.

The , , , and commands do not support echoing because their outputs are already echoed to the log.

You can also enable command echoing globally by turning on step debug logging using the secret. For more information, see «Enabling debug logging». In contrast, the workflow command lets you enable command echoing at a more granular level, rather than enabling it for every workflow in a repository.

Example toggling command echoing

The step above prints the following lines to the log:

Only the second and workflow commands are included in the log because command echoing was only enabled when they were run. Even though it is not always echoed, the output parameter is set in all cases.

Сборка завершена

Шаги по сборке из исходного кода обычно просты:

Ознакомьтесь с инструкциями по сборке в репозитории.Убедитесь, что у вас установлены необходимые инструменты, и установите все, что отсутствует.Клонируйте репозиторий на свой компьютер.Следуйте инструкциям по сборке, которые зачастую так же просты, как ввод make.Скопируйте файл (ы) в нужные места.

Если в инструкциях по сборке есть непонятные шаги, посмотрите, есть ли у проекта форум или сообщество, в которое вы можете отправить вопрос. Если у приложения есть веб-сайт, у них может быть страница «Свяжитесь с нами». Электронная почта разработчика, поддерживающего проект боксов, находится на странице «О программе» сайт коробки. Это щедрый жест с его стороны, типичный для более широкого сообщества разработчиков ПО.

Using outputs from a reusable workflow

A reusable workflow may generate data that you want to use in the caller workflow. To use these outputs, you must specify them as the outputs of the reusable workflow.

The following reusable workflow has a single job containing two steps. In each of these steps we set a single word as the output: «hello» and «world.» In the section of the job, we map these step outputs to job outputs called: and . In the section we then define two outputs for the workflow itself, one called which we map to , and one called which we map to .

We can now use the outputs in the caller workflow, in the same way you would use the outputs from a job within the same workflow. We reference the outputs using the names defined at the workflow level in the reusable workflow: and . In this workflow, calls the reusable workflow and prints the outputs from the reusable workflow («hello world») to standard output in the workflow log.

For more information on using job outputs, see «.»

Using labels to route workflows

This feature helps you assign jobs to a specific hosted runner. 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 . Then, you can refer to these labels in your YAML workflow, ensuring that the job is routed in a predictable way.

This example shows how a workflow can use labels to specify the required runner:

A workflow will only run on a runner that has all the labels in the array. The job will preferentially go to an idle self-hosted runner with the specified labels. If none are available and a GitHub-hosted runner with the specified labels exists, the job will go to a GitHub-hosted runner.

To learn more about self-hosted runner labels, see «Using labels with self-hosted runners.»

docker context support

The current isn’t respected (#583).

You can work around this by setting before running , with e.g:

export DOCKER_HOST=$(docker context inspect --format '``.`Endpoints`.`docker`.`Host`')

Runners

GitHub Actions offers managed virtual environments for running workflows. In order for to run your workflows locally, it must run a container for the runner defined in your workflow file. Here are the images that uses for each runner type and size:

GitHub Runner Micro Docker Image Medium Docker Image Large Docker Image

Windows and macOS based platforms are currently unsupported and won’t work (see issue #97)

Using labels to route workflows

This feature helps you assign jobs to a specific hosted runner. 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 . 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:

A workflow will only run on a runner that has all the labels in the array. The job will preferentially go to an idle self-hosted runner with the specified labels. If none are available and a GitHub-hosted runner with the specified labels exists, the job will go to a GitHub-hosted runner.

To learn more about self-hosted runner labels, see «Using labels with self-hosted runners.»

To learn more about GitHub-hosted runner labels, see .

GitHub

GitHub был создан в результате успеха git. Основатели увидели растущую потребность в безопасных удаленных репозиториях git. Они начали бизнес предоставление облачной платформы чтобы группы разработчиков могли размещать удаленные репозитории. По состоянию на апрель 2019 года на GitHub размещено более 100 миллионов репозиториев.

Если приложение является проектом с открытым исходным кодом, очень высоки шансы, что оно будет размещено на GitHub. Доступны и другие платформы репозиториев, такие как BitBucket и GitLab, но на GitHub приходится львиная доля репозиториев с открытым исходным кодом.

About GitHub-hosted runners

A GitHub-hosted runner is a virtual machine hosted by GitHub with the GitHub Actions runner application installed. GitHub offers runners with Linux, Windows, and macOS operating systems.

When you use a GitHub-hosted runner, machine maintenance and upgrades are taken care of for you. You can run workflows directly on the virtual machine or in a Docker container.

You can specify the runner type for each job in a workflow. Each job in a workflow executes in a fresh instance of the virtual machine. All steps in the job execute in the same instance of the virtual machine, allowing the actions in that job to share information using the filesystem.

The GitHub Actions runner application is open source. You can contribute and file issues in the runner repository.

Cloud hosts for GitHub-hosted runners

GitHub hosts Linux and Windows runners on Standard_DS2_v2 virtual machines in Microsoft Azure with the GitHub Actions runner application installed. The GitHub-hosted runner application is a fork of the Azure Pipelines Agent. Inbound ICMP packets are blocked for all Azure virtual machines, so ping or traceroute commands might not work. For more information about the Standard_DS2_v2 machine resources, see «» in the Microsoft Azure documentation.

GitHub hosts macOS runners in GitHub’s own macOS Cloud.

Workflow continuity for GitHub-hosted runners

If GitHub Actions services are temporarily unavailable, then a workflow run is discarded if it has not been queued within 30 minutes of being triggered. For example, if a workflow is triggered and the GitHub Actions services are unavailable for 31 minutes or longer, then the workflow run will not be processed.

In addition, if the workflow run has been successfully queued, but has not been processed by a GitHub-hosted runner within 45 minutes, then the queued workflow run is discarded.

Administrative privileges of GitHub-hosted runners

The Linux and macOS virtual machines both run using passwordless . When you need to execute commands or install tools that require more privileges than the current user, you can use without needing to provide a password. For more information, see the «Sudo Manual.»

Windows virtual machines are configured to run as administrators with User Account Control (UAC) disabled. For more information, see «How User Account Control works» in the Windows documentation.

Installation through package managers

brew install act

or if you want to install version based on latest commit, you can run below (it requires compiler to be installed installed but Homebrew will suggest you how to install it, if you don’t have it):

brew install act --HEAD
sudo port install act
choco install act-cli
scoop install act
yay -S act

Global install:

nix-env -iA nixpkgs.act

or through :

nix-shell -p act

If you have Go 1.16+, you can install latest released version of directly from source by running:

go install github.com/nektos/act@latest

or if you want to install latest unreleased version:

go install github.com/nektos/act@master

If you want a smaller binary size, run above commands with

go install -ldflags="-s -w" github.com/nektos/act@...

Сборка приложения

Чтобы собрать приложение, мы должны следовать инструкциям в репозитории GitHub. Иногда мы запускаем определенный файл оболочки, а другие — make. Инструкции по сборке, которым мы следуем, говорят нам запустить make.

Утилита make читает и выполняет набор инструкций из make-файла. Эти инструкции говорят make, как скомпилировать программу и связать ее вместе. make передает инструкции компилятору и другим инструментам сборки.

Команда, которую нам предлагают использовать, вызовет make дважды. Первый вызов make создает приложение, а второй запускает набор тестов.

Команда, которую нам сказали использовать инструкции по сборке:

make && make test

Многие строки вывода быстро прокручиваются в окне терминала. Примерно через минуту вы вернетесь в командную строку.

Using labels to route workflows

This feature helps you assign jobs to a specific hosted runner. 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 . Then, you can refer to these labels in your YAML workflow, ensuring that the job is routed in a predictable way.

This example shows how a workflow can use labels to specify the required runner:

A workflow will only run on a runner that has all the labels in the array. The job will preferentially go to an idle self-hosted runner with the specified labels. If none are available and a GitHub-hosted runner with the specified labels exists, the job will go to a GitHub-hosted runner.

To learn more about self-hosted runner labels, see «Using labels with self-hosted runners.»

Использование GitHub Actions с C++ и CMake

В этом посте я хочу показать файл конфигурации GitHub Actions для проекта C++, использующего CMake.

GitHub Actions это предоставляемая GitHub инфраструктура CI/CD. Сейчас GitHub Actions предлагает следующие виртуальные машины (runners):

Виртуальное окружение Имя рабочего процесса YAML
Windows Server 2019 windows-latest
Ubuntu 18.04 ubuntu-latest or ubuntu-18.04
Ubuntu 16.04 ubuntu-16.04
macOS Catalina 10.15 macos-latest

Каждая виртуальная машина имеет одинаковые доступные аппаратные ресурсы:

  • 2х ядерное CPU
  • 7 Гб оперативной памяти
  • 14 Гб на диске SSD

Каждое задание рабочего процесса может выполняться до 6 часов.

К сожалению, когда я включил GitHub Actions в проекте C++, мне предложили такой рабочий процесс:

Это немного не то, что можно использовать с CMake.

Клонирование репозитория

Каждый репозиторий GitHub имеет определенный веб-адрес, используемый Git для клонирования репозитория на ваш компьютер. На главной странице репозитория ящиков есть зеленая кнопка с надписью «Клонировать или скачать».

Нажмите кнопку, чтобы увидеть веб-адрес. Это адрес, который мы должны передать команде git при клонировании репозитория.

Перейдите в каталог, в который мы хотим клонировать репозиторий, и затем используйте эту команду. Если ваше окно терминала поддерживает это, вы можете скопировать и вставить веб-адрес в команду. Нажмите Ctrl + Shift + V, чтобы вставить в окно терминала GNOME.

Git клонирует удаленный репозиторий и создает на вашем компьютере локальный. Он сообщает нам, что клонируется в каталог под названием «ящики».

Каталог боксов создается в каталоге, из которого вы запустили команду git. Если мы переключимся в каталог box и посмотрим на его содержимое, мы увидим тот же список файлов и папок, который мы видели на странице GitHub.

Большой! Мы успешно клонировали исходный код и другие файлы на наш компьютер. Теперь нам нужно создать приложение.

Creating a workflow template

Workflow templates can be created by users with write access to the organization’s repository. The templates can then be used by organization members who have permission to create workflows.

Your workflow templates can be used to create workflows in public repositories only. Organizations using GitHub Enterprise Cloud can also use workflow templates to create workflows in private repositories. For more information, see the GitHub Enterprise Cloud documentation.

Note: To avoid duplication in workflows created from a template you can call reusable workflows from within a workflow template. This can help make your workflows easier to maintain. For more information, see «Reusing workflows.»

This procedure demonstrates how to create a workflow template and metadata file. The metadata file describes how the template is presented to users when they are creating a new workflow.

  1. If it doesn’t already exist, create a new public repository named in your organization.

  2. Create a directory named .

  3. Create your new workflow file inside the directory.

    If you need to refer to a repository’s default branch, you can use the placeholder. When a workflow is created using your template, the placeholder will be automatically replaced with the name of the repository’s default branch.

    For example, this file named demonstrates a basic workflow.

  4. Create a metadata file inside the directory. The metadata file must have the same name as the workflow file, but instead of the extension, it must be appended with . For example, this file named contains the metadata for a workflow file named :

    • — Required. The name of the workflow template. This is displayed in the list of available templates.
    • — Required. The description of the workflow template. This is displayed in the list of available templates.
    • — Optional. Defines an icon for the workflow’s entry in the template list. The must be an SVG icon of the same name, and must be stored in the directory. For example, a SVG file named is referenced as .
    • — Optional. Defines the language category of the workflow. When a user views the available templates, those templates that match the same language will feature more prominently. For information on the available language categories, see https://github.com/github/linguist/blob/master/lib/linguist/languages.yml.
    • — Optional. Allows the template to be used if the user’s repository has a file in its root directory that matches a defined regular expression.

To add another workflow template, add your files to the same directory. For example:

Overview

Rather than copying and pasting from one workflow to another, you can make workflows reusable. You and anyone with access to the reusable workflow can then call the reusable workflow from another workflow.

Reusing workflows avoids duplication. This makes workflows easier to maintain and allows you to create new workflows more quickly by building on the work of others, just as you do with actions. Workflow reuse also promotes best practice by helping you to use workflows that are well designed, have already been tested, and have been proved to be effective. Your organization can build up a library of reusable workflows that can be centrally maintained.

The diagram below shows three build jobs on the left of the diagram. After each of these jobs completes successfully a dependent job called «Deploy» runs. This job calls a reusable workflow that contains three jobs: «Staging», «Review», and «Production.» The «Production» deployment job only runs after the «Staging» job has completed successfully. Using a reusable workflow to run deployment jobs allows you to run those jobs for each build without duplicating code in workflows.

A workflow that uses another workflow is referred to as a «caller» workflow. The reusable workflow is a «called» workflow. One caller workflow can use multiple called workflows. Each called workflow is referenced in a single line. The result is that the caller workflow file may contain just a few lines of YAML, but may perform a large number of tasks when it’s run. When you reuse a workflow, the entire called workflow is used, just as if it was part of the caller workflow.

If you reuse a workflow from a different repository, any actions in the called workflow run as if they were part of the caller workflow. For example, if the called workflow uses , the action checks out the contents of the repository that hosts the caller workflow, not the called workflow.

When a reusable workflow is triggered by a caller workflow, the context is always associated with the caller workflow. The called workflow is automatically granted access to and . For more information about the context, see «.»

Reusable workflows and workflow templates

Workflow templates allow everyone in your organization who has permission to create workflows to do so more quickly and easily. When people create a new workflow, they can choose a template and some or all of the work of writing the workflow will be done for them. Inside workflow templates, you can also reference reusable workflows to make it easy for people to benefit from reusing centrally managed workflow code. If you use a tag or branch name when referencing the reusable workflow then you can ensure that everyone who reuses that workflow will always be using the same YAML code. However, if you reference a reusable workflow by a tag or branch, be sure that you can trust that version of the workflow. For more information, see «.»

For more information, see «Creating workflow templates.»

Рейтинг
( Пока оценок нет )
Понравилась статья? Поделиться с друзьями:
Мой редактор ОС
Добавить комментарий

;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: