# Автоматизация Projects с помощью действий

Вы можете автоматизировать GitHub Actions свои проекты.

## GitHub Actions Рабочие процессы

В этой статье демонстрируется, как использовать API GraphQL и GitHub Actions добавить pull request в организационный проект. В примерах рабочих процессов, когда запрос на вытягивание помечен как "готов к проверке", в проект добавляется новая задача, для которой в поле "Состояние" указано "Выполнить", а в настраиваемое поле "Дата публикации" добавляется текущая дата.

Вы можете скопировать один из приведенных ниже рабочих процессов и изменить его, как описано в таблице ниже, в соответствии с вашими потребностями.

Проект может охватывать несколько репозиториев, но рабочий процесс зависит от репозитория. Добавьте рабочий процесс в каждый репозиторий, который требуется отслеживать проект. Дополнительные сведения о создании файлов рабочего процесса см. в разделе [Быстрый старт для GitHub Actions](/ru/enterprise-server@3.21/actions/get-started/quickstart).

Эта статья предполагает, что у вас есть базовое понимание .GitHub Actions Дополнительные сведения см. в GitHub Actionsразделе [GitHub Actions Документация](/ru/enterprise-server@3.21/actions).

Дополнительные сведения о других изменениях, которые можно внести в проект через API, см. в разделе [Использование API для управления Projects](/ru/enterprise-server@3.21/issues/planning-and-tracking-with-projects/automating-your-project/using-the-api-to-manage-projects).

Вы также можете использовать рабочий **процесс действий/добавления в проект** , который поддерживается GitHub и добавляет текущую проблему или pull request в указанный проект. Дополнительные сведения см. в репозитории [actions/add-to-project](https://github.com/actions/add-to-project) и файле сведений.

> [!NOTE]
> `GITHUB_TOKEN` ограничен на уровне репозитория и не может получить доступ проектык . Чтобы получить доступ проекты , можно создать GitHub App либо (рекомендовано для проектов организации), либо personal access token (рекомендовано для пользовательских проектов). Ниже приведены примеры рабочих процессов для обоих подходов.

## Пример аутентификации рабочих процессов с помощью GitHub App

Для получения дополнительной информации об аутентификации в GitHub Actions рабочем процессе с GitHub Appпомощью , см. [Создание аутентифицированных запросов API с помощью приложения GitHub в рабочем процессе GitHub Actions](/ru/enterprise-server@3.21/apps/creating-github-apps/authenticating-with-a-github-app/making-authenticated-api-requests-with-a-github-app-in-a-github-actions-workflow).

1. Создайте GitHub App или выберите существующую GitHub App компанию, принадлежащую вашей организации. Дополнительные сведения см. в разделе [Регистрация приложения GitHub](/ru/enterprise-server@3.21/apps/creating-github-apps/registering-a-github-app/registering-a-github-app).

2. Дайте разрешение GitHub App на чтение и написание организационных проектов. Для этого конкретного примера вам GitHub App также понадобятся права на чтение pull request-запросов репозиторий и проблем с репозиториями. Дополнительные сведения см. в разделе [Изменение регистрации приложения GitHub](/ru/enterprise-server@3.21/apps/maintaining-github-apps/modifying-a-github-app-registration).

   > [!NOTE]
   > Вы можете контролировать разрешение приложения на проекты организации и репозитории. Необходимо предоставить разрешение на чтение и запись в проектах организации; разрешений на чтение и запись в проектах репозитория будет недостаточно.

3. Установите их GitHub App в вашей организации. Установите его для всех репозиториев, к которым проект должен получать доступ. Дополнительные сведения см. в разделе [Установка собственного приложения GitHub](/ru/enterprise-server@3.21/apps/using-github-apps/installing-your-own-github-app).

4. Сохраняйте GitHub Appидентификатор клиента как конфигурационную переменную в репозитории или организации. В следующем рабочем процессе замените `APP_CLIENT_ID` имя переменной конфигурации. Вы можете найти идентификатор клиента на странице настроек вашего приложения или через API приложения. Дополнительные сведения см. в разделе [Конечные точки REST API для приложений](/ru/enterprise-server@3.21/rest/apps#get-an-app). Дополнительные сведения о переменных конфигурации см. в разделе [Хранение сведений в переменных](/ru/enterprise-server@3.21/actions/how-tos/write-workflows/choose-what-workflows-do/use-variables#defining-configuration-variables-for-multiple-workflows).

5. Создайте закрытый ключ для приложения. Сохраните содержимое итогового файла в виде секрета в репозитории или организации. (Сохраните все содержимое файла, включая `-----BEGIN RSA PRIVATE KEY-----` и `-----END RSA PRIVATE KEY-----`.) В следующем рабочем процессе замените `APP_PRIVATE_KEY` именем секрета. Дополнительные сведения см. в разделе [Управление приватными ключами для приложений GitHub](/ru/enterprise-server@3.21/apps/creating-github-apps/authenticating-with-a-github-app/managing-private-keys-for-github-apps). Дополнительные сведения о хранении секретов см. в разделе [Использование секретов в GitHub Actions](/ru/enterprise-server@3.21/actions/how-tos/write-workflows/choose-what-workflows-do/use-secrets).

6. В следующем рабочем процессе замените `YOUR_ORGANIZATION` названием организации. Например: `octo-org`. Замените `YOUR_PROJECT_NUMBER` номером проекта. Чтобы найти номер проекта, просмотрите URL-адрес проекта. Например, у `https://github.com/orgs/octo-org/projects/5` номер 5. Чтобы этот конкретный пример работал, проект также должен иметь поле даты публикации даты.

```yaml annotate copy
#
name: Add PR to project
# This workflow runs whenever a pull request in the repository is marked as "ready for review".
on:
  pull_request:
    types:
      - ready_for_review
jobs:
  track_pr:
    runs-on: ubuntu-latest
    steps:
    # Uses the [actions/create-github-app-token](https://github.com/marketplace/actions/create-github-app-token) action to generate an installation access token for your app from the client ID and private key. The installation access token is accessed later in the workflow as `${{ steps.generate-token.outputs.token }}`.
    #
    # Replace `APP_CLIENT_ID` with the name of the configuration variable that contains your client ID.
    #
    # Replace `APP_PRIVATE_KEY` with the name of the secret that contains your app private key.
      - name: Generate token
        id: generate-token
        uses: actions/create-github-app-token@v3
        with:
          client-id: ${{ vars.APP_CLIENT_ID }}
          private-key: ${{ secrets.APP_PRIVATE_KEY }}
      # Sets environment variables for this step.
      #
      # Replace `YOUR_ORGANIZATION` with the name of your organization. For example, `octo-org`.
      #
      # Replace `YOUR_PROJECT_NUMBER` with your project number. To find the project number, look at the project URL. For example, `https://github.com/orgs/octo-org/projects/5` has a project number of 5.
      - name: Get project data
        env:
          GH_TOKEN: ${{ steps.generate-token.outputs.token }}
          ORGANIZATION: YOUR_ORGANIZATION
          PROJECT_NUMBER: YOUR_PROJECT_NUMBER
        # Uses [GitHub CLI manual](https://cli.github.com/manual/) to query the API for the ID of the project and return the name and ID of the first 20 fields in the project. `fields` returns a union and the query uses inline fragments (`... on`) to return information about any `ProjectV2Field` and `ProjectV2SingleSelectField` fields. The response is stored in a file called `project_data.json`.
        run: |
          gh api graphql -f query='
            query($org: String!, $number: Int!) {
              organization(login: $org){
                projectV2(number: $number) {
                  id
                  fields(first:20) {
                    nodes {
                      ... on ProjectV2Field {
                        id
                        name
                      }
                      ... on ProjectV2SingleSelectField {
                        id
                        name
                        options {
                          id
                          name
                        }
                      }
                    }
                  }
                }
              }
            }' -f org=$ORGANIZATION -F number=$PROJECT_NUMBER > project_data.json

          # Parses the response from the API query and stores the relevant IDs as environment variables. Modify this to get the ID for different fields or options. For example:
          #
          # - To get the ID of a field called `Team`, add `echo 'TEAM_FIELD_ID='$(jq '.data.organization.projectV2.fields.nodes[] | select(.name== "Team") | .id' project_data.json) >> $GITHUB_ENV`.
          # - To get the ID of an option called `Octoteam` for the `Team` single select field, add `echo 'OCTOTEAM_OPTION_ID='$(jq '.data.organization.projectV2.fields.nodes[] | select(.name== "Team") |.options[] | select(.name=="Octoteam") |.id' project_data.json) >> $GITHUB_ENV`.
          #
          # **Note:** This workflow assumes that you have a project with a single select field called "Status" that includes an option called "Todo" and a date field called "Date posted". You must modify this section to match the fields that are present in your table.

          echo 'PROJECT_ID='$(jq '.data.organization.projectV2.id' project_data.json) >> $GITHUB_ENV
          echo 'DATE_FIELD_ID='$(jq '.data.organization.projectV2.fields.nodes[] | select(.name== "Date posted") | .id' project_data.json) >> $GITHUB_ENV
          echo 'STATUS_FIELD_ID='$(jq '.data.organization.projectV2.fields.nodes[] | select(.name== "Status") | .id' project_data.json) >> $GITHUB_ENV
          echo 'TODO_OPTION_ID='$(jq '.data.organization.projectV2.fields.nodes[] | select(.name== "Status") | .options[] | select(.name=="Todo") |.id' project_data.json) >> $GITHUB_ENV

# Sets environment variables for this step. `GH_TOKEN` is the token generated in the first step. `PR_ID` is the ID of the pull request that triggered this workflow.
      - name: Add PR to project
        env:
          GH_TOKEN: ${{ steps.generate-token.outputs.token }}
          PR_ID: ${{ github.event.pull_request.node_id }}
        # Uses [GitHub CLI manual](https://cli.github.com/manual/) and the API to add the pull request that triggered this workflow to the project. The `jq` flag parses the response to get the ID of the created item.
        run: |
          item_id="$( gh api graphql -f query='
            mutation($project:ID!, $pr:ID!) {
              addProjectV2ItemById(input: {projectId: $project, contentId: $pr}) {
                item {
                  id
                }
              }
            }' -f project=$PROJECT_ID -f pr=$PR_ID --jq '.data.addProjectV2ItemById.item.id')"

          # Stores the ID of the created item as an environment variable.
          echo 'ITEM_ID='$item_id >> $GITHUB_ENV

# Saves the current date as an environment variable in `yyyy-mm-dd` format.
      - name: Get date
        run: echo "DATE=$(date +"%Y-%m-%d")" >> $GITHUB_ENV

# Sets environment variables for this step. `GH_TOKEN` is the token generated in the first step.
      - name: Set fields
        env:
          GH_TOKEN: ${{ steps.generate-token.outputs.token }}
        # Sets the value of the `Status` field to `Todo`. Sets the value of the `Date posted` field.
        run: |
          gh api graphql -f query='
            mutation (
              $project: ID!
              $item: ID!
              $status_field: ID!
              $status_value: String!
              $date_field: ID!
              $date_value: Date!
            ) {
              set_status: updateProjectV2ItemFieldValue(input: {
                projectId: $project
                itemId: $item
                fieldId: $status_field
                value: {
                  singleSelectOptionId: $status_value
                  }
              }) {
                projectV2Item {
                  id
                  }
              }
              set_date_posted: updateProjectV2ItemFieldValue(input: {
                projectId: $project
                itemId: $item
                fieldId: $date_field
                value: {
                  date: $date_value
                }
              }) {
                projectV2Item {
                  id
                }
              }
            }' -f project=$PROJECT_ID -f item=$ITEM_ID -f status_field=$STATUS_FIELD_ID -f status_value=${{ env.TODO_OPTION_ID }} -f date_field=$DATE_FIELD_ID -f date_value=$DATE --silent
```

## Пример аутентификации рабочих процессов с помощью personal access token

1. Создайте personal access token (classic) с `project` и `repo` прицелами. Дополнительные сведения см. в разделе [Управление личными маркерами доступа](/ru/enterprise-server@3.21/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens).
2. Сохраните personal access token это как секрет в своём репозитории или организации.
3. В следующем рабочем процессе замените `YOUR_TOKEN` именем секрета. Замените `YOUR_ORGANIZATION` названием организации. Например: `octo-org`. Замените `YOUR_PROJECT_NUMBER` номером проекта. Чтобы найти номер проекта, просмотрите URL-адрес проекта. Например, у `https://github.com/orgs/octo-org/projects/5` номер 5.

```yaml annotate copy
# This workflow runs whenever a pull request in the repository is marked as "ready for review".
name: Add PR to project
on:
  pull_request:
    types:
      - ready_for_review
jobs:
  track_pr:
    runs-on: ubuntu-latest
    steps:
    # Sets environment variables for this step.
    #
    # If you are using a personal access token, replace `YOUR_TOKEN` with the name of the secret that contains your personal access token.
    #
    # Replace `YOUR_ORGANIZATION` with the name of your organization. For example, `octo-org`.
    #
    # Replace `YOUR_PROJECT_NUMBER` with your project number. To find the project number, look at the project URL. For example, `https://github.com/orgs/octo-org/projects/5` has a project number of 5.
      - name: Get project data
        env:
          GH_TOKEN: ${{ secrets.YOUR_TOKEN }}
          ORGANIZATION: YOUR_ORGANIZATION
          PROJECT_NUMBER: YOUR_PROJECT_NUMBER
        # Uses [GitHub CLI manual](https://cli.github.com/manual/) to query the API for the ID of the project and return the name and ID of the first 20 fields in the project. `fields` returns a union and the query uses inline fragments (`... on`) to return information about any `ProjectV2Field` and `ProjectV2SingleSelectField` fields. The response is stored in a file called `project_data.json`.
        run: |
          gh api graphql -f query='
            query($org: String!, $number: Int!) {
              organization(login: $org){
                projectV2(number: $number) {
                  id
                  fields(first:20) {
                    nodes {
                      ... on ProjectV2Field {
                        id
                        name
                      }
                      ... on ProjectV2SingleSelectField {
                        id
                        name
                        options {
                          id
                          name
                        }
                      }
                    }
                  }
                }
              }
            }' -f org=$ORGANIZATION -F number=$PROJECT_NUMBER > project_data.json

          # Parses the response from the API query and stores the relevant IDs as environment variables. Modify this to get the ID for different fields or options. For example:
          #
          # - To get the ID of a field called `Team`, add `echo 'TEAM_FIELD_ID='$(jq '.data.organization.projectV2.fields.nodes[] | select(.name== "Team") | .id' project_data.json) >> $GITHUB_ENV`.
          # - To get the ID of an option called `Octoteam` for the `Team` single select field, add `echo 'OCTOTEAM_OPTION_ID='$(jq '.data.organization.projectV2.fields.nodes[] | select(.name== "Team") |.options[] | select(.name=="Octoteam") |.id' project_data.json) >> $GITHUB_ENV`.
          #
          # **Note:** This workflow assumes that you have a project with a single select field called "Status" that includes an option called "Todo" and a date field called "Date posted". You must modify this section to match the fields that are present in your table.

          echo 'PROJECT_ID='$(jq '.data.organization.projectV2.id' project_data.json) >> $GITHUB_ENV
          echo 'DATE_FIELD_ID='$(jq '.data.organization.projectV2.fields.nodes[] | select(.name== "Date posted") | .id' project_data.json) >> $GITHUB_ENV
          echo 'STATUS_FIELD_ID='$(jq '.data.organization.projectV2.fields.nodes[] | select(.name== "Status") | .id' project_data.json) >> $GITHUB_ENV
          echo 'TODO_OPTION_ID='$(jq '.data.organization.projectV2.fields.nodes[] | select(.name== "Status") | .options[] | select(.name=="Todo") |.id' project_data.json) >> $GITHUB_ENV

# Sets environment variables for this step. Replace `YOUR_TOKEN` with the name of the secret that contains your personal access token.
      - name: Add PR to project
        env:
          GH_TOKEN: ${{ secrets.YOUR_TOKEN }}
          PR_ID: ${{ github.event.pull_request.node_id }}
        # Uses [GitHub CLI manual](https://cli.github.com/manual/) and the API to add the pull request that triggered this workflow to the project. The `jq` flag parses the response to get the ID of the created item.
        run: |
          item_id="$( gh api graphql -f query='
            mutation($project:ID!, $pr:ID!) {
              addProjectV2ItemById(input: {projectId: $project, contentId: $pr}) {
                item {
                  id
                }
              }
            }' -f project=$PROJECT_ID -f pr=$PR_ID --jq '.data.addProjectV2ItemById.item.id')"

          # Stores the ID of the created item as an environment variable.
          echo 'ITEM_ID='$item_id >> $GITHUB_ENV

# Saves the current date as an environment variable in `yyyy-mm-dd` format.
      - name: Get date
        run: echo "DATE=$(date +"%Y-%m-%d")" >> $GITHUB_ENV

# Sets environment variables for this step. Replace `YOUR_TOKEN` with the name of the secret that contains your personal access token.
      - name: Set fields
        env:
          GH_TOKEN: ${{ secrets.YOUR_TOKEN }}
        # Sets the value of the `Status` field to `Todo`. Sets the value of the `Date posted` field.
        run: |
          gh api graphql -f query='
            mutation (
              $project: ID!
              $item: ID!
              $status_field: ID!
              $status_value: String!
              $date_field: ID!
              $date_value: Date!
            ) {
              set_status: updateProjectV2ItemFieldValue(input: {
                projectId: $project
                itemId: $item
                fieldId: $status_field
                value: {
                  singleSelectOptionId: $status_value
                  }
              }) {
                projectV2Item {
                  id
                  }
              }
              set_date_posted: updateProjectV2ItemFieldValue(input: {
                projectId: $project
                itemId: $item
                fieldId: $date_field
                value: {
                  date: $date_value
                }
              }) {
                projectV2Item {
                  id
                }
              }
            }' -f project=$PROJECT_ID -f item=$ITEM_ID -f status_field=$STATUS_FIELD_ID -f status_value=${{ env.TODO_OPTION_ID }} -f date_field=$DATE_FIELD_ID -f date_value=$DATE --silent

```