[Yandex Cloud documentation](../../index.md) > [Yandex API Gateway](../index.md) > [Tutorials](index.md) > Serverless-based backend > Interactive debugging of functions in Cloud Functions

# Interactive debugging of functions in Yandex Cloud Functions


In this tutorial, you will set up a system to interactively debug [functions](../../functions/concepts/function.md) in Yandex Cloud Functions by redirecting requests to a local server. For more information about this solution, see the [yc-serverless-live-debug repository](https://github.com/yandex-cloud/yc-serverless-live-debug).

To set up the interactive function debugging system:

1. [Get your cloud ready](#prepare-cloud).
1. [Install the required tools](#install-utilities).
1. [Create a cloud administrator service account](#create-account).
1. [Deploy your resources](#create-resources).
1. [Run the debugging service](#run-client).

If you no longer need the resources you created, [delete them](#clear-out).
 
## Get your cloud ready {#prepare-cloud}

Sign up for Yandex Cloud and create a [billing account](../../billing/concepts/billing-account.md):
1. Navigate to the [management console](https://console.yandex.cloud) and log in to Yandex Cloud or create a new account.
1. On the **[Yandex Cloud Billing](https://center.yandex.cloud/billing/accounts)** page, make sure you have a billing account linked and it has the `ACTIVE` or `TRIAL_ACTIVE` [status](../../billing/concepts/billing-account-statuses.md). If you do not have a billing account, [create one](../../billing/quickstart/index.md) and [link](../../billing/operations/pin-cloud.md) a cloud to it.

If you have an active billing account, you can create or select a [folder](../../resource-manager/concepts/resources-hierarchy.md#folder) for your infrastructure on the [cloud page](https://console.yandex.cloud/cloud).

[Learn more about clouds and folders here](../../resource-manager/concepts/resources-hierarchy.md).

### Required paid resources {#paid-resources}

The infrastructure support costs include:

* Fee for function invocations and computing resources allocated to run the functions (see [Yandex Cloud Functions pricing](../../functions/pricing.md)).
* Fee for the number of requests to the API gateway (see [Yandex API Gateway pricing](../pricing.md)).
* Fee for YDB operations and data storage (see [Yandex Managed Service for YDB pricing](../../ydb/pricing/serverless.md)).
* Fee for logging operations and log storage (see [Yandex Cloud Logging pricing](../../logging/pricing.md)).

## Install the required tools {#install-utilities}

1. [Install Terraform](../../tutorials/infrastructure-management/terraform-quickstart.md#install-terraform).
1. Create a directory named `live-debug-test` and open it:

    ```
    mkdir live-debug-test
    cd live-debug-test
    ```

1. Install the `yc-serverless-live-debug` package:

    ```
    npm i -D @yandex-cloud/serverless-live-debug
    ```

## Create a cloud administrator service account {#create-account}

1. Create a [service account](../../iam/concepts/users/service-accounts.md):
   
    {% list tabs group=instructions %}

    - Management console {#console}

      1. In the [management console](https://console.yandex.cloud), select the folder where you want to create a service account.
      1. Navigate to **Identity and Access Management**.
      1. Click **Create service account**.
      1. Specify the service account name, e.g., `sa-live-debug`.

          The naming requirements are as follows:

          * Length: between 3 and 63 characters.
          * It can only contain lowercase Latin letters, numbers, and hyphens.
          * It must start with a letter and cannot end with a hyphen.

      1. Click **Create**.

    - CLI {#cli}

      If you do not have the Yandex Cloud CLI yet, [install and initialize it](../../cli/quickstart.md#install).

      The folder used by default is the one specified when [creating](../../cli/operations/profile/profile-create.md) the CLI profile. To change the default folder, use the `yc config set folder-id <folder_ID>` command. You can also specify a different folder for any command using `--folder-name` or `--folder-id`. If you access a resource by its name, the search will be limited to the default folder. If you access a resource by its ID, the search will be global, i.e., through all folders based on access permissions.

      To create a service account, run this command:

      ```bash
      yc iam service-account create --name sa-live-debug
      ```

      Where `name` is the service account name in the following format:

      * Length: between 3 and 63 characters.
      * It can only contain lowercase Latin letters, numbers, and hyphens.
      * It must start with a letter and cannot end with a hyphen.

      Result:

      ```text
      id: ajehr0to1g8b********
      folder_id: b1gv87ssvu49********
      created_at: "2023-03-04T09:03:11.665153755Z"
      name: sa-live-debug
      ```

    - Terraform {#tf}

      If you do not have Terraform yet, [install it and configure the Yandex Cloud provider](../../tutorials/infrastructure-management/terraform-quickstart.md#install-terraform).
      
      
      To manage infrastructure using Terraform under a service account or user accounts (a Yandex account, a federated account, or a local user), [authenticate](../../terraform/authentication.md) using the appropriate method.

      1. In the configuration file, specify the properties of the resources you want to create:
    
          ```hcl
          resource "yandex_iam_service_account" "sa" {
            name        = "sa-live-debug"
            description = "<service_account_description>"
            folder_id   = "<folder_ID>"
          }
          ```

          Where:

          * `name`: Service account name. This is a required setting.
          * `description`: Service account description. This is an optional setting.
          * `folder_id`: [Folder ID](../../resource-manager/operations/folder/get-id.md). This is an optional setting. It defaults to the value specified in the provider settings.

          For more information about `yandex_iam_service_account` properties, see [this Terraform provider guide](../../terraform/resources/iam_service_account.md).
    
      1. Make sure the configuration files are correct.

          1. In the terminal, navigate to the directory where you created your configuration file.
          1. Run a check using this command:

              ```bash
              terraform plan
              ```

          If the configuration is correct, the terminal will display information about the service account. Otherwise, Terraform will show any detected errors. 

      1. Deploy the cloud resources.

          1. If the configuration is correct, run this command:

              ```bash
              terraform apply
              ```

    - API {#api}

      To create a service account, use the [create](../../iam/api-ref/ServiceAccount/create.md) REST API method for the [ServiceAccount](../../iam/api-ref/ServiceAccount/index.md) resource or the [ServiceAccountService/Create](../../iam/api-ref/grpc/ServiceAccount/create.md) gRPC API call.

    {% endlist %}

1. Assign the service account the `admin` [role](../../iam/concepts/access-control/roles.md) for the cloud:

    {% list tabs group=instructions %}

    - Management console {#console}

      1. On the management console [home page](https://console.yandex.cloud), select your cloud.
      1. Navigate to the ![image](../../_assets/console-icons/persons.svg) **Access bindings** tab.
      1. Find the `sa-live-debug` account in the list and click ![image](../../_assets/console-icons/ellipsis.svg).
      1. Select ![image](../../_assets/console-icons/pencil.svg) **Edit roles**.
      1. Click ![image](../../_assets/console-icons/plus.svg) **Add role** in the window that opens and select `admin`.
      1. Click **Save**.

    - CLI {#cli}

      Run this command:

      ```
      yc resource-manager cloud add-access-binding <cloud_ID> \
         --role admin \
         --subject serviceAccount:<service_account_ID>
      ```

      Result:
      ```
      done (1s)
      ```

    - Terraform {#tf}

      1. In the configuration file, describe the resources you want to create:

          ```
          resource "yandex_resourcemanager_cloud_iam_member" "admin" {
            cloud_id = "<cloud_ID>"
            role     = "admin"
            member   = "serviceAccount:<service_account_ID>"
          }
          ```

          Where:

          * `cloud_id`: [Cloud ID](../../resource-manager/operations/cloud/get-id.md). This is a required setting.
          * `role`: Role being assigned. This is a required setting.
          * `member`: User or service account getting the role. Use this format: `userAccount:<user_ID>` or `serviceAccount:<service_account_ID>`. This is a required setting.

          For more information about `yandex_resourcemanager_folder_iam_member` properties, see [this provider guide](../../terraform/resources/iam_service_account_iam_member.md).

      1. Make sure the configuration files are correct.

          1. In the terminal, navigate to the directory where you created your configuration file.
          1. Run a check using this command:

              ```
               terraform plan
              ```

              If the configuration is correct, the terminal will display a list of the resources and their settings. Otherwise, Terraform will show any detected errors.

      1. Deploy the cloud resources.

          1. If the configuration is correct, run this command:

              ```
              terraform apply
              ```

    - API {#api}

      To assign a role for a cloud to a service account, use the [setAccessBindings](../../iam/api-ref/ServiceAccount/setAccessBindings.md) REST API method for the [ServiceAccount](../../iam/api-ref/ServiceAccount/index.md) resource or the [ServiceAccountService/SetAccessBindings](../../iam/api-ref/grpc/ServiceAccount/setAccessBindings.md) gRPC API call.

    {% endlist %}

## Deploy your resources {#create-resources}

1. Set up your CLI profile to use the service account to run operations:

    {% list tabs group=instructions %}

    - CLI {#cli}

      1. Create an [authorized key](../../iam/concepts/authorization/key.md) for the service account and save it to the file:

          ```
          yc iam key create \
            --service-account-id <service_account_ID> \
            --folder-id <folder_ID> \
            --output key.json
          ```

          Where:
          * `--service-account-id`: `sa-live-debug` service account ID.
          * `--folder-id`: Service account folder ID.
          * `--output`: Authorized key file name.

          Result:

          ```
          id: aje8nn871qo4********
          service_account_id: ajehr0to1g8********
          created_at: "2023-03-04T09:16:43.479156798Z"
          key_algorithm: RSA_2048
          ```

      1. Create a CLI profile to run operations on behalf of the service account:

          ```
          yc config profile create sa-live-debug
          ```

          Result:

          ```
          Profile 'sa-live-debug' created and activated
          ```

      1. Configure the profile:

          ```
          yc config set service-account-key key.json
          yc config set cloud-id <cloud_ID>
          ```

          Where:
          * `service-account-key`: Service account authorized key file.
          * `cloud-id`: [Cloud ID](../../resource-manager/operations/cloud/get-id.md).

      1. Add the credentials to the environment variables:

          ```
          export YC_TOKEN=$(yc iam create-token)
          export YC_CLOUD_ID=$(yc config get cloud-id)
          ```

    {% endlist %}

1. Deploy the resources in the cloud by running this command:

    ```
    npx serverless-live-debug deploy
    ```

    As a result, the command will create a folder named `live-debug` in the cloud and deploy all required resources there.

## Run the debugging service {#run-client}

1. In the `live-debug-test` directory, create a file named `live-debug.config.ts`:

    ```
    nano live-debug.config.ts
    ```

1. Copy the code with the following configuration to `live-debug.config.ts`:

    ```
    import { defineConfig } from '@yandex-cloud/serverless-live-debug';
    import { Handler } from '@yandex-cloud/function-types';

    export default defineConfig({
      handler: <Handler.Http>(event => {
        console.log('got request', event);
        return {
          statusCode: 200,
          body: `Hello from local code!`,
        };
      })
    });
    ```

1. Start the debugging service by running the following command:

    ```
    npx serverless-live-debug run
    ```

    Result:

    ```
    Using config: live-debug.config.ts
    Running local client...
    Starting child...
    Child started
    Watching changes in: live-debug.config.ts
    WS connection opened
    Local client ready.
    Check url: https://d5dm1lba80md********.i9******.apigw.yandexcloud.net
    Waiting requests...
    ```

    Where `Check url` is the public address of the [API Gateway](../concepts/index.md).

1. Make sure the debug code is working properly by opening another terminal and running this command:

    ```
    curl https://d5dm1lba80md********.i9******.apigw.yandexcloud.net
    ```

    Result:

    ```
    Hello from local code!
    ```

For more information about usage examples, see the [yc-serverless-live-debug](https://github.com/yandex-cloud/yc-serverless-live-debug) repository. 

## How to delete the resources you created {#clear-out}

Delete the folder with the resources required for interactive debugging of functions in Cloud Functions:

{% list tabs group=instructions %}

- Management console {#console}

  1. In the [management console](https://console.yandex.cloud/cloud), select `live-debug`. 
  1. Click ![image](../../_assets/console-icons/ellipsis.svg) next to the folder and select **Delete**.
  1. In the **Folder deletion period** field, select `Delete now`.
  1. Click **Delete**.

- API {#api}

  To delete a folder, use the [delete](../../resource-manager/api-ref/Folder/delete.md) REST API method for the [Folder](../../resource-manager/api-ref/Folder/index.md) resource or the [FolderService/Delete](../../resource-manager/api-ref/grpc/Folder/delete.md) gRPC API call.

{% endlist %}