[Yandex Cloud documentation](../../index.md) > [Yandex Managed Service for Trino](../index.md) > [Step-by-step guides](index.md) > Clusters > Connecting to a cluster

# Connecting to a Trino cluster

This section presents settings for connection to the Managed Service for Trino cluster using [command line tools](#cli-tools), from [graphical IDEs](#connection-ide) and [WebSQL](#websql). To learn how to connect from your application code, see [Connection string examples](#connection-strings).

You can connect to a Managed Service for Trino cluster with disabled [private access](../concepts/network.md#private-endpoint) only from the network the cluster resides in.

{% note info %}

If the connection requires a port, use port `443`.

{% endnote %}

## Configuring security groups {#configuring-security-groups}

[Security groups](../../vpc/concepts/security-groups.md) do not restrict inbound traffic to the Managed Service for Trino cluster and do not affect the Trino web interface availability. You do not need to configure any inbound traffic rules.

You can use security groups to configure outbound traffic rules, e.g., when setting up a new [catalog](../concepts/index.md#catalog).

To connect to a Trino cluster from a Yandex Cloud VM, configure a security group for the VM you will use for connection. VM rule examples:

* For incoming traffic:

    * **Port range**: `22`.
    * **Protocol**: `TCP`.
    * **Source**: `CIDR`.
    * **CIDR blocks**: `0.0.0.0/0`.

    This rule allows inbound connections to the VM over SSH.

* For outbound traffic:

    * **Protocol**: `Any`.
    * **Port range**: `0-65535`.
    * **Destination name**: `CIDR`.
    * **CIDR blocks**: `0.0.0.0/0`.

    This rule allows all outgoing traffic, which enables you to both connect to the cluster and install any required utilities on your VM.

### Security groups for Greenplum® {#security-groups-for-greenplum}

To access the Greenplum® cluster, the Trino [connector](../concepts/greenplum-connector.md) uses the GPFDIST protocol:

* Trino coordinators and workers send queries to the Greenplum® master over TCP port `6432`.
* Greenplum® segments forward data to Trino workers over the GPFDIST TCP port.

Data transmitted between the Greenplum® and Trino clusters over the GPFDIST protocol is unencrypted. To secure your connection, configure security groups [in Yandex MPP Analytics for PostgreSQL](#configuring-security-groups-greenplum) and, optionally, [in Managed Service for Trino](#configuring-security-groups-trino).

If Greenplum® interacts with other clusters or entities inside the user network, you need to separately configure security group rules for any such clusters or entities.

#### Greenplum® side setup {#configuring-security-groups-greenplum}

{% list tabs group=traffic %}

- Incoming traffic {#incoming}

    * Rule for internal Greenplum® cluster traffic:

        * **Port range**: `0-65535`.
        * **Protocol**: `Any`.
        * **Source**: `Security group`.
        * **Security group**: `Current`.

    * Rule for connections from a Trino cluster:

        * **Port range**: `6432`.
        * **Protocol**: `TCP`.
        * **Source**: `Security group`.
        * **Security group**: Specify the Trino cluster security group.

- Outgoing traffic {#outgoing}

    * Rule for internal Greenplum® cluster traffic:

        * **Port range**: `0-65535`.
        * **Protocol**: `Any`.
        * **Source**: `Security group`.
        * **Security group**: `Current`.

    * Rule for connections to a Trino cluster:

        * **Port range**: `0-65535`.
        * **Protocol**: `TCP`.
        * **Source**: `Security group`.
        * **Security group**: Specify the Trino cluster security group.

{% endlist %}

#### Managed Service for Trino side setup {#configuring-security-groups-trino}

To configure security group rules in Trino, invert the Greenplum® rule settings. Setting up rules for a Trino cluster is optional, but this provides added security for your cluster.

{% list tabs group=traffic %}

- Incoming traffic {#incoming}

  Rule for receiving data from Greenplum® segments:

    * **Port range**: `0-65535`.
    * **Protocol**: `TCP`.
    * **Source**: `Security group`.
    * **Security group**: Specify the Greenplum® cluster security group.

- Outgoing traffic {#outgoing}

  Rule for connections to a Greenplum® master:

    * **Port range**: `6432`.
    * **Protocol**: `TCP`.
    * **Source**: `Security group`.
    * **Security group**: Specify the Greenplum® cluster security group.

{% endlist %}

## Command line tools {#cli-tools}

### Trino CLI {#trino-cli}

If you do not have the Trino CLI yet, install it using the [guide on the official Trino website](https://trino.io/docs/current/client/cli.html#installation).

To connect to an Managed Service for Trino cluster:

1. Create an [IAM token](../../iam/concepts/authorization/iam-token.md) and put it to the `TRINO_PASSWORD` environment variable:

   ```bash
   export TRINO_PASSWORD=$(yc iam create-token)
   ```

   This IAM token in `TRINO_PASSWORD` will be your password to the Managed Service for Trino cluster. To enable it, specify the `--password` flag upon connection.

1. Connect to the Managed Service for Trino cluster:

   ```bash
   ./trino c-<cluster_ID>.trino.yandexcloud.net --user iam --password
   ```

   You can get the cluster ID with the [list of clusters in the folder](cluster-list.md#list-clusters).

## Connecting from graphical IDEs {#connection-ide}

Before connecting:

1. Create an [IAM token](../../iam/concepts/authorization/iam-token.md):

   ```bash
   yc iam create-token
   ```

1. Save the token. You will use it as a password for the connection.

{% list tabs group=ide %}

- DataGrip {#datagrip}

  1. Create a data source:
     1. Select **File** → **New** → **Data Source** → **Trino**.
     1. Enter a name for the data source.
     1. Specify the connection settings on the **General** tab:
        * **Host**: `c-<cluster_ID>.trino.yandexcloud.net`.

            If you are connecting to your Managed Service for Trino cluster via a [service connection](../concepts/network.md#private-endpoint), specify `c-<cluster_ID>.trino.pe.yandexcloud.net` as the host address.

        * **Port**: `443`.
        * **User**: `iam`.
        * **Password**: Previously created IAM token.
  1. Click **Test Connection**. If the connection is successful, you will see the connection status and information about the DBMS and driver.
  1. Click **OK** to save the data source.

- DBeaver {#dbeaver}

  1. Create a new DB connection:
     1. In the **Database** menu, select **New connection**.
     1. Select **Trino** from the list.
     1. Click **Next**.
     1. Specify the connection settings on the **Main** tab:
        * **Host**: `c-<cluster_ID>.trino.yandexcloud.net`.

            If you are connecting to your Managed Service for Trino cluster via a [service connection](../concepts/network.md#private-endpoint), specify `c-<cluster_ID>.trino.pe.yandexcloud.net` as the host address.

        * **Port**: `443`.
        * Under **Authentication**, specify:
            * Username: `iam`.
            * Password: Previously created IAM token.
  1. Click **Test Connection ...**. If the connection is successful, you will see the connection status, DBMS information, and driver details.
  1. Click **Done** to save the database connection settings.

{% endlist %}

## WebSQL {#websql}

1. Open the [folder dashboard](https://console.yandex.cloud).
1. Navigate to **Managed Service for&nbsp;Trino**.
1. Open your Managed Service for Trino cluster.
1. Navigate to **WebSQL**.
1. Click **Go to WebSQL**.
1. In the SQL query editor that opens, run the following query:

   ```sql
   SELECT version() AS version;
   ```

   The response will contain Trino version information.

## Examples of connection strings {#connection-strings}

### Python {#python}

Before connecting:

1. Install the dependencies:

   ```bash
   pip3 install trino
   ```

1. Create an [IAM token](../../iam/concepts/authorization/iam-token.md) and put it to the `TOKEN` environment variable:

   ```bash
   export TOKEN=$(yc iam create-token)
   ```

{% list tabs group=instruction %}

- Connection {#connecting}

  1. Code example:

      `connect.py`

      ```python
      import os
      from contextlib import closing
      from trino.dbapi import connect
      from trino.auth import BasicAuthentication

      TIMEOUT = 10
      COORDINATOR_URL = 'c-<cluster_ID>.trino.yandexcloud.net'
      IAM_TOKEN = os.environ['TOKEN']

      def get_version():
          auth = BasicAuthentication(username='iam', password=IAM_TOKEN)
          with closing(connect(host=COORDINATOR_URL, port=443, auth=auth, request_timeout=TIMEOUT)) as conn:
              with closing(conn.cursor()) as cur:
                  cur.execute('SELECT version() as version')
                  rows = cur.fetchall()
                  print(rows[0])

      if __name__ == "__main__":
          get_version()
      ```

     You can get the cluster ID with the [list of clusters in the folder](cluster-list.md#list-clusters).

     If you are connecting to your Managed Service for Trino cluster via a [service connection](../concepts/network.md#private-endpoint), specify `c-<cluster_ID>.trino.pe.yandexcloud.net` as the host address.

  1. Connecting:

      ```bash
      python3 connect.py
      ```

{% endlist %}

### Java {#java}

Before connecting:

1. Install the dependencies:

    ```bash
    sudo apt update && sudo apt install --yes openjdk-21-jre maven
    ```

1. Create a directory for the Maven project:

    ```bash
    cd ~/ && mkdir -p project/src/main/java/com/example && cd project/
    ```

1. Create a configuration file for Maven:

    {% cut "pom.xml" %}

    ```xml
    <?xml version="1.0" encoding="utf-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">

        <modelVersion>4.0.0</modelVersion>
        <groupId>com.example</groupId>
        <artifactId>app</artifactId>
        <version>0.1.0</version>
        <packaging>jar</packaging>
        <properties>
            <maven.compiler.source>21</maven.compiler.source>
            <maven.compiler.target>21</maven.compiler.target>
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        </properties>
        <dependencies>
            <dependency>
                <groupId>io.trino</groupId>
                <artifactId>trino-jdbc</artifactId>
                <version>469</version>
            </dependency>
        </dependencies>
        <build>
            <finalName>${project.artifactId}-${project.version}</finalName>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-assembly-plugin</artifactId>
                    <version>3.7.1</version>
                    <executions>
                        <execution>
                            <goals>
                                <goal>single</goal>
                            </goals>
                            <phase>package</phase>
                            <configuration>
                                <descriptorRefs>
                                    <descriptorRef>
                                        jar-with-dependencies</descriptorRef>
                                </descriptorRefs>
                                <archive>
                                    <manifest>
                                        <mainClass>com.example.App</mainClass>
                                    </manifest>
                                </archive>
                            </configuration>
                        </execution>
                    </executions>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-jar-plugin</artifactId>
                    <version>3.4.2</version>
                    <configuration>
                        <archive>
                            <manifest>
                                <mainClass>com.example.App</mainClass>
                            </manifest>
                        </archive>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    </project>

    ```

    {% endcut %}

1. Create an [IAM token](../../iam/concepts/authorization/iam-token.md) and put it to the `TOKEN` environment variable:

   ```bash
   export TOKEN=$(yc iam create-token)
   ```

{% list tabs group=connection %}

- Connection {#connecting}

  1. Code example:

      `src/main/java/com/example/App.java`

      ```java
      package com.example;

      import java.sql.DriverManager;
      import java.util.Properties;

      public class App {
          private static final String COORDINATOR_URL = "c-<cluster_ID>.trino.yandexcloud.net";

          public static void main(String[] args) {
              String url = String.format("jdbc:trino://%s", COORDINATOR_URL);
              String iamToken = System.getenv("TOKEN");
        
              Properties properties = new Properties();
              properties.setProperty("user", "iam");
              properties.setProperty("password", iamToken);
              properties.setProperty("SSL", "true");

              try (var connection = DriverManager.getConnection(url, properties)) {
                  var rs = connection.createStatement().executeQuery("SELECT version() as VERSION");
                  if (rs.next()) {
                      System.out.println(rs.getString(1));
                  }
              } catch (Exception e) {
                  e.printStackTrace();
              }
          }
      }

      ```

      You can get the cluster ID with the [list of clusters in the folder](cluster-list.md#list-clusters).

      If you are connecting to your Managed Service for Trino cluster via a [service connection](../concepts/network.md#private-endpoint), specify `c-<cluster_ID>.trino.pe.yandexcloud.net` as the host address.

  1. Building and connecting:

      ```bash
      mvn clean package && \
      java -jar target/app-0.1.0-jar-with-dependencies.jar
      ```

{% endlist %}

### Node.js {#nodejs}

Before connecting:
1. Install the dependencies:

    ```bash
    sudo apt update && sudo apt install --yes nodejs npm && \
    npm install trino-client
    ```

1. Create an [IAM token](../../iam/concepts/authorization/iam-token.md) and put it to the `TOKEN` environment variable:

   ```bash
   export TOKEN=$(yc iam create-token)
   ```

{% list tabs group=connection %}

- Connection {#connecting}

    `app.mjs`

    ```javascript
    "use strict";
    import {BasicAuth, Trino} from 'trino-client';

    const COORDINATOR_URL = 'c-<cluster_ID>.trino.yandexcloud.net'
    let TOKEN = process.env.TOKEN

    async function get_version() {
        const trino = Trino.create({server: COORDINATOR_URL,auth: new BasicAuth('iam', TOKEN)});
        const query = await trino.query('SELECT version() as VERSION');
        const queryResult = await query.next()
        console.log(queryResult.value.data[0][0])
    }

    get_version();
    ```

    You can get the cluster ID with the [list of clusters in the folder](cluster-list.md#list-clusters).

    If you are connecting to your Managed Service for Trino cluster via a [service connection](../concepts/network.md#private-endpoint), specify `c-<cluster_ID>.trino.pe.yandexcloud.net` as the host address.

{% endlist %}

Connecting:

```bash
node app.mjs
```