[Yandex Cloud documentation](../../index.md) > [Yandex Managed Service for ClickHouse®](../index.md) > [Step-by-step guides](index.md) > Clusters > Creating a cluster

# Creating a ClickHouse® cluster



A ClickHouse® cluster consists of one or more database hosts. If the cluster consists of multiple hosts, you can set up [replication](../concepts/replication.md) between them. Use one of the [coordination services](../concepts/coordination-system.md) for replication: ClickHouse® Keeper or ZooKeeper.

For more information on how to choose a coordination service, see [Selecting a coordination service](../concepts/coordination-system.md#coordination-system-selection).

The ClickHouse® Keeper and ZooKeeper hosts are counted towards the cloud [resource quota](https://console.yandex.cloud/cloud?section=quotas) and [cluster cost calculation](../pricing.md).


Cluster DB connections are managed by Connection Manager. Creating a cluster automatically creates:

* [Connection Manager](../../metadata-hub/concepts/connection-manager.md) connection with information about the database connection.

* [Yandex Lockbox secret](../../metadata-hub/concepts/secret.md) that stores the DB owner's user password.

The connection and secret will be created for each new database user. To view all connections, open the **Connections** tab on the cluster page. You need the `connection-manager.viewer` role to view the connection details.

Connection Manager and secrets created with it are free of charge.



## Roles for creating a cluster {#roles}

To create a Managed Service for ClickHouse® cluster, you need the [vpc.user](../../vpc/security/index.md#vpc-user) role and the [managed-clickhouse.editor](../security.md#managed-clickhouse-editor) role or higher.

To attach your service account to a cluster, e.g., to [use Yandex Object Storage](s3-access.md), make sure your Yandex Cloud account has the [iam.serviceAccounts.user](../../iam/security/index.md#iam-serviceAccounts-user) role or higher.

For more information about assigning roles, see [this Yandex Identity and Access Management guide](../../iam/operations/roles/grant.md).


## Creating a cluster with ClickHouse® Keeper {#create-cluster}

{% list tabs group=instructions %}

- Management console {#console}



  To create a Managed Service for ClickHouse® cluster with the ClickHouse® Keeper coordination service:

  1. In the [management console](https://console.yandex.cloud), select the folder where you want to create your database cluster.
  1. Navigate to **Managed Service for&nbsp;ClickHouse**.
  1. Click **Create cluster**.
  1. Enter a cluster name in the **Cluster name** field. The cluster name must be unique within the folder.
  1. Select the environment where you want to create your cluster (you cannot change the environment once the cluster is created):
      * `PRODUCTION`: For stable versions of your applications.
      * `PRESTABLE`: For testing purposes. The prestable environment is similar to the production environment and likewise covered by an SLA, but it is the first to get new features, improvements, and bug fixes. In the prestable environment, you can test new versions for compatibility with your application.
  1. Select the [ClickHouse® version](../concepts/update-policy.md) the Managed Service for ClickHouse® cluster will use from the **Version** drop-down list. For most clusters, we recommend selecting the latest LTS version.

  1. Under **Resources**:

      * Select the platform, VM type, and host class. The latter determines the technical specifications of the VMs the database hosts will be deployed on. All available options are listed under [Host classes](../concepts/instance-types.md). When you change the host class for a cluster, the specifications of all existing instances also change.

      
      * Select the [disk type](../concepts/storage.md).

        The type you select determines the increments for changing the disk size:
        
        * Network HDDs and SSDs: In increments of 1 GB.
        * Local SSDs:
            * For **Intel Broadwell** and **Intel Cascade Lake**: In 100 GB increments.
            * For **Intel Ice Lake** and **AMD Zen 4**: In 368 GB increments.
        * Non-replicated SSDs and ultra high-speed network SSDs with three replicas: In increments of 93 GB.


      * Select the size of your data and backup disk. For details on how backups consume storage space, see [Backups](../concepts/backup.md).

      * Optionally, configure [automatic increase of storage size](../concepts/storage.md#autoscaling) for ClickHouse®:

        * In the **Increase size** field, select one or both thresholds:
          * **In the maintenance window when full at more than**: Scheduled expansion threshold. When reached, the storage expands during the next [maintenance window](../concepts/maintenance.md#maintenance-window).
            
            For a scheduled expansion, you need to set up a [maintenance window](../concepts/maintenance.md#maintenance-window) schedule.
        
          * **Immediately when full at more than**: Immediate expansion threshold. When reached, the storage expands immediately.
        * Specify a threshold value (as a percentage of the total storage size). If you select both thresholds, make sure the immediate expansion threshold is not less than the scheduled one.
        * Set **Maximum storage size**.

        The automatic storage size increase settings for ClickHouse® apply to all existing shards. If you add a new shard, it will use the settings of the oldest shard.

  
  1. Under **Network settings**, select the cloud network to host your cluster and security groups for cluster network traffic. You may need to additionally [set up security groups](connect/index.md#configuring-security-groups) to be able connect to the cluster.


  1. Optionally, under **Sharding settings**:

      * Enable **Cluster sharding** to create a cluster with multiple [shards](../concepts/sharding.md) from the outset. You can add shards either when creating or updating a cluster.

      * Set up shards created together with the cluster. To change a shard's settings, click ![pencil](../../_assets/console-icons/pencil.svg) next to its number:

          * **Shard name** and its **Weight**.

          * **Configuration** of shard hosts:

              * **Default**: Hosts will inherit the cluster configuration.

              * **Redefined**: Set the host class, storage settings, and DBMS settings for all shard hosts.

      To add shards to a cluster, click **Add shard**.

  1. Under **Hosts**:

      * Set up database hosts created together with the cluster. To change the host settings, click ![pencil](../../_assets/console-icons/pencil.svg) next to the host number:

        * **Availability zone**: Select the [availability zone](../../overview/concepts/geo-scope.md).

        
        * **Subnet**: Specify a [subnet](../../vpc/concepts/network.md#subnet) in the selected availability zone.

        * **Public access**: Allow [access](connect/index.md) to the host from the internet.


        * If cluster [sharding](../concepts/sharding.md) is enabled, select a shard.

        To add hosts to your cluster, click **Add host**.

      * Select a [coordination service](../concepts/coordination-system.md): **ClickHouse Keeper (on separate hosts)** or **Embedded ClickHouse Keeper**.

        {% note alert %}
        
        You cannot disable ClickHouse® Keeper after creating a cluster. You will not be able to use ZooKeeper hosts as well.
        
        {% endnote %}

  1. If **ClickHouse Keeper (on separate hosts)** is selected, configure the following settings:

      * Under **Clickhouse Keeper host class**, select the platform, VM type, and [host class](../concepts/instance-types.md).
      * Under **ClickHouse Keeper storage size**, select the [disk type](../concepts/storage.md) and storage size. Optionally, configure [automatic increase of storage size](../concepts/storage.md#autoscaling) for ClickHouse® Keeper.
      * Under **Clickhouse Keeper hosts**, change the settings of the automatically added ClickHouse® Keeper hosts as appropriate.

        To change the host settings, click ![pencil](../../_assets/console-icons/pencil.svg) next to the host and specify the following:

        * **Availability zone**: Select the [availability zone](../../overview/concepts/geo-scope.md).

        
        * **Subnet**: Select the [subnet](../../vpc/concepts/network.md#subnet) in the selected availability zone.


  1. Under **DBMS settings**:

      * If you want to manage cluster users via SQL, select **User management via SQL** from the drop-down list in the **Enabled** field and enter the `admin` password. This disables user management through other interfaces.

        Otherwise, select **Disabled**.


      * If you want to manage databases via SQL, select **Enabled** from the drop-down list in the **Managing databases via SQL** field. This disables database management through other interfaces. This field is inactive if user management via SQL is disabled.

        Otherwise, select **Disabled**.

        {% note warning %}
        
        You cannot disable settings for user or database management via SQL once they are enabled. You can enable them as required later when [reconfiguring your cluster](update.md#SQL-management).
        
        {% endnote %}

      * Specify a username.

        The username may contain Latin letters, numbers, hyphens, and underscores but must begin with a letter or underscore. The name may be up to 32 characters long.

      
      * Specify a user password:

        * **Enter manually**: Select this option to set your own password. It must be from 8 to 128 characters long.

        * **Generate**: Select this option to generate a password using Connection Manager.

        To view the password after creating a cluster, select the **Users** tab and click **View password** for the relevant user. This will open the page of the Yandex Lockbox secret containing the password. To view passwords, you need the `lockbox.payloadViewer` role.


      * Specify a database name. The database name may include Latin letters, numbers, and underscores. It may be up to 63 characters long. You cannot create a database named `default`.

      * Select the database engine:

        * `Atomic`, the default option, supports the non-blocking `DROP TABLE` and `RENAME TABLE` operations and atomic `EXCHANGE TABLES` operations.
        * `Replicated` supports table metadata replication across all database replicas. The set of tables and their schemas will be the same for all replicas.

          It is only available in [replicated](../concepts/replication.md) clusters.

        You can only set the engine when creating a database and cannot change it later.

      * Enable [hybrid storage](../concepts/storage.md#hybrid-storage-features) for the cluster, if required.

        {% note warning %}

        You cannot disable this option.

        {% endnote %}

      * [Configure the DBMS](../concepts/settings-list.md#server-level-settings), if required. You can do it later.

        Using the Yandex Cloud interfaces, you can manage a limited number of settings. Using SQL queries, you can [specify the ClickHouse® settings at the query level](change-query-level-settings.md).

  1. Specify the cluster service settings, if required:

      * **Backup start time (UTC)**: Time interval during which the cluster backup starts. Time is specified in 24-hour UTC format. The default time is `22:00 - 23:00` UTC.
      
      * **Retention period for automatic backups, days**: Retention period for automatic backups, in days. Backups are automatically deleted once their retention period expires. The default is 7 days. For more information, see [Backups](../concepts/backup.md#storage).
      
          Changing the retention period affects both new and existing automatic backups. For example, the initial retention period was 7 days, and the remaining lifetime of a single automatic backup is 1 day. If the retention period increases to 9 days, the remaining lifetime for this backup will now be 3 days.
      
      * **Maintenance**: [Maintenance](../concepts/maintenance.md) window settings:
      
         * To enable maintenance at any time, select **At any time** (default).
         * To specify the preferred maintenance start time, select **By schedule** and specify the day of the week and the UTC time interval. For example, you can choose a time when the cluster is least loaded.
         
         Both active and stopped clusters are subject to maintenance. Maintenance operations include DBMS updates, patches, etc.
      
      
      * **Service account**: Account user programs can use to manage the cluster. For more information, see [this guide](../security.md).
      
      * **Disk encryption**: This option enables disk encryption with a [custom KMS key](../../kms/concepts/key.md). Set a key in one of the following ways:
      
         * To [create](../../kms/operations/key.md#create) a new key, click **Create**.
      
         * To use a previously created key, select it in the **KMS key** field.
      
         Learn more about disk encryption in [Storage](../concepts/storage.md#disk-encryption).
      
      
      * **DataLens access**: This option enables you to analyze cluster data in [Yandex DataLens](../../datalens/concepts/index.md).
      
      
      * **WebSQL access**: This option enables you to [run SQL queries](web-sql-query.md) against cluster databases from the Yandex Cloud management console using Yandex WebSQL.
      
      
      
      
      * **Access from Metrica and AppMetrica**: This option enables you to [import data from AppMetrica](https://appmetrica.yandex.ru/docs/en/common/cloud) to a cluster.
      
      * **Serverless access**: Enable this option to allow cluster access from [Yandex Cloud Functions](../../functions/concepts/index.md). Learn more about access setup in [this Cloud Functions guide](../../functions/operations/database-connection.md).
      
      
      * **Yandex Query access**: Enable this option to allow cluster access from [Yandex Query](../../query/concepts/index.md). This feature is at the [Preview](../../overview/concepts/launch-stages.md) stage.
      
      * **Deletion protection**: Manages cluster protection against accidental deletion.
      
         Even with cluster deletion protection enabled, one can still delete a user or database or connect manually and delete the database contents.

  1. Click **Create cluster**.

- 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 Managed Service for ClickHouse® cluster with the built-in ClickHouse® Keeper coordination service:

  
  1. Check whether the folder has any subnets for cluster hosts:

      ```bash
      yc vpc subnet list
      ```

     If there are no subnets in the folder, [create the right ones](../../vpc/operations/subnet-create.md) in VPC.


  1. View the description of the CLI command for creating a cluster:

      ```bash
      yc managed-clickhouse cluster create --help
      ```

  1. Specify the cluster properties in this command (the example does not show all that are available):

      
      ```bash
      yc managed-clickhouse cluster create \
        --name <cluster_name> \
        --environment <environment> \
        --network-name <network_name> \
        --shard name=<shard_name>,weight=<shard_weight> \
        --host type=clickhouse,`
              `zone-id=<availability_zone>,`
              `subnet-id=<subnet_ID>,`
              `assign-public-ip=<public_access_to_host>,`
              `shard-name=<shard_name> \
        --clickhouse-resource-preset <host_class> \
        --clickhouse-disk-type <disk_type> \
        --clickhouse-disk-size <storage_size_in_GB> \
        --embedded-keeper true \
        --user name=<username>,password=<user_password> \
        --database name=<DB_name> \
        --security-group-ids <list_of_security_group_IDs> \
        --websql-access=<access_from_WebSQL> \
        --deletion-protection
      ```


      Where:

      * `--environment`: Cluster environment, `prestable` or `production`.
      * `--shard`: [Shard](../concepts/sharding.md) properties, such as name and weight.

        To create a cluster with multiple shards from the outset, specify this flag as many times as needed. If you do not specify the `--shard` flag, the new cluster will have a single shard named `shard1`.

      * `--host`: Host settings:
        * `type`: Host type, `clickhouse`.
        * `zone-id`: Availability zone.

        
        * `subnet-id`: Subnet ID. Specify if the selected availability zone has two or more subnets.
        * `assign-public-ip`: Internet access to the host via a public IP address, `true` or `false`.

          {% note warning %}
          
          For a more secure cluster with public host access enabled, use only trusted IP addresses or subnets in the cluster's security group rules. Learn more in [Configuring security groups](connect/index.md#configuring-security-groups).
          
          {% endnote %}


        * `shard-name`: Name of the shard the host will reside in.

        
        If you create a cluster of two or more ClickHouse® hosts without the coordination service and the cluster [network](../../vpc/concepts/network.md) has [subnets](../../vpc/concepts/network.md#subnet) in each [availability zone](../../overview/concepts/geo-scope.md), the system automatically adds three ZooKeeper hosts one in each subnet.
        
        If subnets are located only in some availability zones, or you want to use a different coordination service, manually specify the coordination service and its host settings.


        Specify a separate `--host` flag for each host.

      * `--clickhouse-resource-preset`: ClickHouse® [host class](../concepts/instance-types.md).
      * `--clickhouse-disk-type`: ClickHouse® [disk type](../concepts/storage.md).
      * `--clickhouse-disk-size`: ClickHouse® storage size in GB.
      * `--embedded-keeper`: Use of the built-in ClickHouse® Keeper [coordination service](../concepts/coordination-system.md), `true` or `false`.

        {% note alert %}
        
        You cannot disable ClickHouse® Keeper after creating a cluster. You will not be able to use ZooKeeper hosts as well.
        
        {% endnote %}

      * `--user`: Contains the ClickHouse® user `name` and `password`.

        The username may contain Latin letters, numbers, hyphens, and underscores but must begin with a letter or underscore. The name may be up to 32 characters long.

        The password must be from 8 to 128 characters long.

        
        {% note info %}

        You can also generate a password using Connection Manager. To do this, edit the command, specifying the user properties as follows:

        ```bash
          --user name=<username>,generate-password=true
        ```

        To view the password, select your cluster in the [management console](https://console.yandex.cloud), navigate to the **Users** tab, and click **View password** for the relevant user. This will open the page of the Yandex Lockbox secret containing the password. To view passwords, you need the `lockbox.payloadViewer` role.

        {% endnote %}


      
      * `--security-group-ids`: Security group IDs, comma-separated.

          {% note warning %}
          
          If you specified security group IDs when creating a cluster, you may need to [configure these security groups](connect/index.md#configuring-security-groups) to enable cluster access.
          
          {% endnote %}


      * `--websql-access`: Enables [SQL queries](web-sql-query.md) against cluster databases from the Yandex Cloud management console using Yandex WebSQL. The default value is `false`.

      * `--deletion-protection`: Cluster protection from accidental deletion, `true` or `false`.

        Even with cluster deletion protection enabled, one can still delete a user or database or connect manually and delete the database contents.

      You can manage cluster users and databases via SQL.

      {% note warning %}
      
      You cannot disable settings for user or database management via SQL once they are enabled. You can enable them as required later when [reconfiguring your cluster](update.md#SQL-management).
      
      {% endnote %}

      1. To enable [user management via SQL](cluster-users.md#sql-user-management):

         * Set `--enable-sql-user-management` to `true`.
         * Set a password for `admin` in the `--admin-password` parameter.

         ```bash
         yc managed-clickhouse cluster create \
           ...
           --enable-sql-user-management true \
           --admin-password "<admin_password>"
         ```


      1. To enable [database management via SQL](databases.md#sql-database-management):

         * Set `--enable-sql-user-management` and `--enable-sql-database-management` to `true`.
         * Set a password for `admin` in the `--admin-password` parameter.

         ```bash
         yc managed-clickhouse cluster create \
           ...
           --enable-sql-user-management true \
           --enable-sql-database-management true \
           --admin-password "<admin_user_password>"
         ```

      
      1. To encrypt the disk with a [custom KMS key](../../kms/concepts/key.md), provide `--disk-encryption-key-id <KMS_key_ID>`.

         To learn more about disk encryption, see [Storage](../concepts/storage.md#disk-encryption).

      1. To allow access to the cluster from [Yandex Cloud Functions](../../functions/concepts/index.md), provide `--serverless-access`. For more information about access setup, see [this Cloud Functions guide](../../functions/operations/database-connection.md).


      1. To allow access to the cluster from [Yandex Query](../../query/concepts/index.md), provide the `--yandexquery-access=true` parameter. This feature is at the [Preview](../../overview/concepts/launch-stages.md) stage.


      1. To [configure hybrid storage](../concepts/storage.md#hybrid-storage-settings):

         * Set `--cloud-storage` to `true` to enable hybrid storage.

            {% note info %}
            
            Once hybrid storage is enabled, you cannot disable it.
            
            {% endnote %}

         * Provide the hybrid storage settings in the relevant parameters:

            * `--cloud-storage-data-cache`: Enables caching files in the cluster storage. The default value is `true` (enabled).
            * `--cloud-storage-data-cache-max-size`: Sets the maximum cache size, in bytes, allocated in the cluster storage. If no value is set, the maximum cache size defaults to half the size of the cluster storage.
            * `--cloud-storage-move-factor`: Sets the minimum percentage of free space in the cluster storage. If your free space percentage is below this value, the data will be moved to Yandex Object Storage. The minimum value is `0`, the maximum value is `1`, and the default value is `0.01`.
            * `--cloud-storage-prefer-not-to-merge`: Disables [merging of data parts](https://clickhouse.com/docs/enen/engines/table-engines/mergetree-family/custom-partitioning-key) in cluster and object storages. To disable merges, set the parameter to `true` or provide it with no value. To keep merges enabled, set the parameter to `false` or do not provide it in the CLI command when creating a cluster.

         ```bash
         yc managed-clickhouse cluster create \
            ...
            --cloud-storage=true \
            --cloud-storage-data-cache=<file_storage> \
            --cloud-storage-data-cache-max-size=<memory_size_in_bytes> \
            --cloud-storage-move-factor=<share_of_free_space> \
            --cloud-storage-prefer-not-to-merge=<merging_data_parts>
           ...
         ```

         Where:
         * `--cloud-storage-data-cache`: Set to store files in a cluster storage, `true` or `false`.
         * `--cloud-storage-prefer-not-to-merge`: Disables merging of data parts in a cluster and object storage, `true` or `false`.

      1. To configure automatic ClickHouse® storage expansion settings, use the `--disk-size-autoscaling` flag:

         ```bash
         yc managed-clickhouse cluster create \
           ...
           --disk-size-autoscaling clickhouse-disk-size-limit=<maximum_storage_size_in_GB>,`
                                  `clickhouse-planned-usage-threshold=<scheduled_expansion_threshold_in_percent>,`
                                  `clickhouse-emergency-usage-threshold=<immediate_expansion_threshold_in_percent>
           ...
         ```

         Where:

         * `clickhouse-disk-size-limit`: Maximum ClickHouse® storage size, in GB.
         * `clickhouse-planned-usage-threshold`: ClickHouse® storage utilization threshold to trigger an increase during the next maintenance window, in percent. The default value is `0` (auto increase disabled).

           The valid values range from `0` to `100`.

         * `clickhouse-emergency-usage-threshold`: Utilization threshold for the ClickHouse® storage capacity, in percent, to trigger an immediate increase. The default value is `0` (auto increase disabled).

           The valid values range from `0` to `100`.

         {% note warning %}

         * If you specify both thresholds for ClickHouse®, `clickhouse-emergency-usage-threshold` must not be less than `clickhouse-planned-usage-threshold`.

         * When using `clickhouse-planned-usage-threshold`, make sure to set up a [maintenance window](../concepts/maintenance.md).

         {% endnote %}

         The automatic storage expansion settings specified for ClickHouse® apply to all shards. To use individual settings for a particular shard, provide the same parameters in the `--shard` flag.

         ```bash
         yc managed-clickhouse cluster create \
           ...
           --shard name=<shard_name>,`
                  `disk-size-limit=<maximum_storage_size_in_GB>,`
                  `planned-usage-threshold=<scheduled_expansion_threshold_in_percent>,`
                  `emergency-usage-threshold=<immediate_expansion_threshold_in_percent>
           ...
         ```

      1. To set a [maintenance window](../concepts/maintenance.md), use the `--maintenance-window` flag:

         ```bash
         yc managed-clickhouse cluster create \
           ...
           --maintenance-window type=<maintenance_type>,`
                               `hour=<hour>,`
                               `day=<day_of_week>
           ...
         ```

         Where `--maintenance-window` defines the maintenance window settings:

         * `type`: Maintenance window type. Valid values:

           * `anytime`: Any time (default).
           * `weekly`: On schedule. To use this value, you need to provide `hour` and `day`.

         * `hour`: Time of day (UTC). The valid values range from `1` to `24`.
         * `day`: Day of week. The valid values are `MON`, `TUE`, `WED`, `THU`, `FRI`, `SAT`, and `SUN`.


- Terraform {#tf}

  With [Terraform](https://www.terraform.io/), you can quickly create a cloud infrastructure in Yandex Cloud and manage it using configuration files. These files store the infrastructure description written in HashiCorp Configuration Language (HCL). If you change the configuration files, Terraform automatically detects which part of your configuration is already deployed, and what should be added or removed.
  
  Terraform is distributed under the [Business Source License](https://github.com/hashicorp/terraform/blob/main/LICENSE). The [Yandex Cloud provider for Terraform](https://github.com/yandex-cloud/terraform-provider-yandex) is distributed under the [MPL-2.0](https://www.mozilla.org/en-US/MPL/2.0/) license.
  
  For more information about the provider resources, see the guides on the [Terraform](https://www.terraform.io/docs/providers/yandex/index.html) website or [its mirror](../../terraform/index.md).

  To create a Managed Service for ClickHouse® cluster with the built-in ClickHouse® Keeper coordination service:

    1. In the command line, navigate to the directory that will contain the Terraform configuration files describing your infrastructure. If there is no such directory, create one.

    1. 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. Create a configuration file describing the [cloud network](../../vpc/concepts/network.md#network) and [subnets](../../vpc/concepts/network.md#subnet).
        * Network: Description of the [cloud network](../../vpc/concepts/network.md#network) to host the cluster. If you already have a network in place, you do not need to describe it again.
        * Subnets: Description of the [subnets](../../vpc/concepts/network.md#network) to connect the cluster hosts to. If you already have suitable subnets, you do not need to describe them again.

        Below is an example of a configuration file describing a single-subnet cloud network:

        ```hcl
        resource "yandex_vpc_network" "<network_name_in_Terraform>" {
          name = "<network_name>"
        }

        resource "yandex_vpc_subnet" "<subnet_name_in_Terraform>" {
          name           = "<subnet_name>"
          zone           = "<availability_zone>"
          network_id     = yandex_vpc_network.<network_name_in_Terraform>.id
          v4_cidr_blocks = ["<subnet>"]
        }
        ```

    1. Create a configuration file describing the cluster resources to create:

       * Database cluster: Description of the cluster and its hosts. Optionally, here:
          * Specify the [DBMS server-level settings](../concepts/settings-list.md#server-level-settings). You can also provide them later.
          * Enable cluster protection against accidental deletion.

             Even with cluster deletion protection enabled, one can still delete a user or database or connect manually and delete the database contents.

       * Database: Cluster database description.
       * User: Cluster user description. Optionally, specify the [DBMS user-level settings](../concepts/settings-list.md#dbms-user-settings) here. You can also provide them later.

          Using the Yandex Cloud interfaces, you can manage a limited number of settings. Using SQL queries, you can [specify the ClickHouse® settings at the query level](change-query-level-settings.md).

       Below is an example structure of a configuration file describing a cluster of three ClickHouse® hosts:

       ```hcl
       resource "yandex_mdb_clickhouse_cluster_v2" "<cluster_name>" {
         name                = "<cluster_name>"
         environment         = "<environment>"
         network_id          = yandex_vpc_network.<network_name_in_Terraform>.id
         security_group_ids  = ["<list_of_security_group_IDs>"]
         embedded_keeper     = true
         deletion_protection = <cluster_deletion_protection>

         clickhouse = {
           resources = {
             resource_preset_id = "<host_class>"
             disk_type_id       = "<disk_type>"
             disk_size          = <storage_size_in_GB>
           }
         }

         shards = {
           "<shard_name>" = {
             weight = <shard_weight>
           }
         }

         hosts = {
           "<host_1_name>" = {
             type             = "CLICKHOUSE"
             zone             = "<availability_zone>"
             subnet_id        = yandex_vpc_subnet.<subnet_name_in_Terraform>.id
             assign_public_ip = <public_access_to_host>
             shard_name       = "<shard_name>"
           }

           "<host_2_name>" = {
             type             = "CLICKHOUSE"
             zone             = "<availability_zone>"
             subnet_id        = yandex_vpc_subnet.<subnet_name_in_Terraform>.id
             assign_public_ip = <public_access_to_host>
             shard_name       = "<shard_name>"
           }

           "<host_3_name>" = {
             type             = "CLICKHOUSE"
             zone             = "<availability_zone>"
             subnet_id        = yandex_vpc_subnet.<subnet_name_in_Terraform>.id
             assign_public_ip = <public_access_to_host>
             shard_name       = "<shard_name>"
           }
         }
       }

       resource "yandex_mdb_clickhouse_database" "<DB_name>" {
         cluster_id = yandex_mdb_clickhouse_cluster_v2.<cluster_name>.id
         name       = "<DB_name>"
       }

       resource "yandex_mdb_clickhouse_user" "<username>" {
         cluster_id = yandex_mdb_clickhouse_cluster_v2.<cluster_name>.id
         name       = "<username>"
         password   = "<user_password>"
         permission {
           database_name = yandex_mdb_clickhouse_database.<DB_name>.name
         }
         settings {
           <parameter_1_name> = <value_1>
           <parameter_2_name> = <value_2>
           ...
         }
       }
       ```

       Where:

       * `--embedded-keeper`: Use of the built-in ClickHouse® Keeper [coordination service](../concepts/coordination-system.md), `true` or `false`.

          {% note alert %}
          
          You cannot disable ClickHouse® Keeper after creating a cluster. You will not be able to use ZooKeeper hosts as well.
          
          {% endnote %}

       * `deletion_protection`: Cluster deletion protection, `true` or `false`.

       * `shards`: Cluster [shards](../concepts/sharding.md) as an associative array of elements. The key specifies the shard name, and the value includes the `weight` parameter, i.e., the shard weight.

       * `hosts`: Cluster hosts as an associative array of elements. The key specifies the host name, and the value, the host parameters. Each element in the array has the following structure:

          * `type`: Host type, `CLICKHOUSE`.
          * `zone`: [Availability zone](../../overview/concepts/geo-scope.md).
          * `subnet_id`: [Subnet ID](../../vpc/concepts/network.md#subnet).
          * `assign_public_ip`: Public access to the ClickHouse® host, `true` or `false`.

            {% note warning %}
            
            For a more secure cluster with public host access enabled, use only trusted IP addresses or subnets in the cluster's security group rules. Learn more in [Configuring security groups](connect/index.md#configuring-security-groups).
            
            {% endnote %}

          * `shard_name`: Shard name.

          If you create a cluster of two or more ClickHouse® hosts without the coordination service and the cluster [network](../../vpc/concepts/network.md) has [subnets](../../vpc/concepts/network.md#subnet) in each [availability zone](../../overview/concepts/geo-scope.md), the system automatically adds three ZooKeeper hosts one in each subnet.
          
          If subnets are located only in some availability zones, or you want to use a different coordination service, manually specify the coordination service and its host settings.

       For a user, specify the following:

       * `name` and `password`: ClickHouse® username and password, respectively.

          The username may contain Latin letters, numbers, hyphens, and underscores but must begin with a letter or underscore. The name may be up to 32 characters long.

          It must be from 8 to 128 characters long.

          
          {% note info %}

          You can also generate a password using Connection Manager. To do this, specify `generate_password = true` instead of `"password" = "<user_password>"`.

          To view the password, select your cluster in the [management console](https://console.yandex.cloud), navigate to the **Users** tab, and click **View password** for the relevant user. This will open the page of the Yandex Lockbox secret containing the password. To view passwords, you need the `lockbox.payloadViewer` role.

          {% endnote %}


       * `permission`: List of databases the user should have access to.

       1. To set up the [maintenance window](../concepts/maintenance.md) that will also apply to stopped clusters, add the `maintenance_window` section to the cluster description:
          
          ```hcl
          resource "yandex_mdb_clickhouse_cluster_v2" "<cluster_name>" {
            ...
            maintenance_window {
              type = "<maintenance_type>"
              day  = "<day_of_week>"
              hour = <hour>
            }
            ...
          }
          ```
          
          Where:
          
          * `type`: Maintenance type. The possible values include:
              * `ANYTIME`: Any time.
              * `WEEKLY`: On a schedule.
          * `day`: Day of week for the `WEEKLY` type, i.e., `MON`, `TUE`, `WED`, `THU`, `FRI`, `SAT`, or `SUN`.
          * `hour`: Sequence number of UTC hour interval for the `WEEKLY` type, from `1` to `24`.
          
            > For example, `1` stands for the interval from `00:00` to `01:00`, and `5`, from `04:00` to `05:00`.

       1. To enable access from other services and allow [running SQL queries from the management console](web-sql-query.md) using Yandex WebSQL, add the `access` section with the settings you need:

          ```hcl
          resource "yandex_mdb_clickhouse_cluster_v2" "<cluster_name>" {
            ...
            access = {
              data_lens    = <access_from_DataLens>
              metrika      = <access_from_Metrica_and_AppMetrica>
              serverless   = <access_from_Cloud_Functions>
              yandex_query = <access_from_Yandex_Query>
              web_sql      = <run_SQL_queries_from_management_console>
            }
            ...
          }
          ```

          Where:

          * `data_lens`: Access from DataLens, `true` or `false`.
          * `metrika`: Access from Yandex Metrica and AppMetrica, `true` or `false`.
          * `serverless`: Access from Cloud Functions, `true` or `false`.
          * `yandex_query`: Access from Yandex Query, `true` or `false`.
          * `web_sql`: Running SQL queries from the management console, `true` or `false`.

       1. You can manage cluster users and databases via SQL.

          {% note warning %}
          
          You cannot disable settings for user or database management via SQL once they are enabled. You can enable them as required later when [reconfiguring your cluster](update.md#SQL-management).
          
          {% endnote %}

          *  To enable [user management via SQL](../concepts/user-access-rights.md#sql-user-management), add the `sql_user_management` field set to `true` and the `admin_password` field with the `admin` user's password to the cluster description:
             
             ```hcl
             resource "yandex_mdb_clickhouse_cluster_v2" "<cluster_name>" {
               name                = "<cluster_name>"
               ...
               admin_password      = "<admin_user_password>"
               sql_user_management = true
               ...
             }
             ```

          * To enable [database management via SQL](databases.md#sql-database-management), add to the cluster description the `sql_user_management` and `sql_database_management` fields set to `true` and the `admin_password` field with the `admin` user password:
            
            ```hcl
            resource "yandex_mdb_clickhouse_cluster_v2" "<cluster_name>" {
              name                    = "<cluster_name>"
              ...
              admin_password          = "<admin_user_password>"
              sql_database_management = true
              sql_user_management     = true
              ...
            }
            ```

       1. To encrypt the disk with a [custom KMS key](../../kms/concepts/key.md), add the `disk_encryption_key_id` parameter:

          ```hcl
          resource "yandex_mdb_clickhouse_cluster_v2" "<cluster_name>" {
            ...
            disk_encryption_key_id = <KMS_key_ID>
            ...
          }
          ```

          To learn more about disk encryption, see [Storage](../concepts/storage.md#disk-encryption).

       For more information about the resources you can create with Terraform, see [this provider guide](../../terraform/resources/mdb_clickhouse_cluster.md).

    1. Make sure the Terraform configuration files are correct:

       1. In the command line, navigate to the directory that contains the current Terraform configuration files defining the infrastructure.
       1. Run this command:
       
          ```bash
          terraform validate
          ```
       
          Terraform will show any errors found in your configuration files.

    1. Create a cluster:

       1. Run this command to view the planned changes:
       
          ```bash
          terraform plan
          ```
       
          If you described the configuration correctly, the terminal will display a list of the resources to update and their parameters. This is a verification step that does not apply changes to your resources.
       
       1. If everything looks correct, apply the changes:
          1. Run this command:
       
             ```bash
             terraform apply
             ```
       
          1. Confirm updating the resources.
          1. Wait for the operation to complete.

       All the required resources will be created in the specified folder. You can check resource availability and their settings in the [management console](https://console.yandex.cloud).

    {% note warning "Timeouts" %}
    
    The Terraform provider sets the following timeouts for Managed Service for ClickHouse® cluster operations:
    
    * Creating a cluster, including by restoring from a backup: 60 minutes.
    * Updating a cluster: 90 minutes.
    * Deleting a cluster: 30 minutes.
    
    Operations exceeding the timeout are aborted.
    
    {% cut "How to change these limits" %}
    
    Add the `timeouts` section to your cluster description, such as the following:
    
    ```hcl
    resource "yandex_mdb_clickhouse_cluster_v2" "<cluster_name>" {
      ...
      timeouts = {
        create = "1h30m" # 1 hour 30 minutes
        update = "2h"    # 2 hours
        delete = "30m"   # 30 minutes
      }
    }
    ```
    
    {% endcut %}
    
    {% endnote %}


- REST API {#api}

    To create a Managed Service for ClickHouse® cluster with the built-in ClickHouse® Keeper coordination service:

    1. [Get an IAM token for API authentication](../api-ref/authentication.md) and put it into an environment variable:

        ```bash
        export IAM_TOKEN="<IAM_token>"
        ```

    1. Call the [Cluster.Create](../api-ref/Cluster/create.md) method, e.g., via the following [cURL](https://curl.se/) request:

        1. Create a file named `body.json` and paste the following code into it (the example does not show all the available properties):

            
            ```json
            {
              "folderId": "<folder_ID>",
              "name": "<cluster_name>",
              "environment": "<environment>",
              "networkId": "<network_ID>",
              "securityGroupIds": [
                "<security_group_1_ID>",
                "<security_group_2_ID>",
                ...
                "<security_group_N_ID>"
              ],
              "configSpec": {
                "version": "<ClickHouse®_version>",
                "embeddedKeeper": true,
                "clickhouse": {
                  "resources": {
                    "resourcePresetId": "<ClickHouse®_host_class>",
                    "diskSize": "<storage_size_in_bytes>",
                    "diskTypeId": "<disk_type>"
                  },
                  "diskSizeAutoscaling": {
                    "plannedUsageThreshold": "<scheduled_expansion_threshold_in_percent>",
                    "emergencyUsageThreshold": "<immediate_expansion_threshold_in_percent>",
                    "diskSizeLimit": "<maximum_storage_size_in_bytes>"
                  }
                },
                "access": {
                  "dataLens": <access_from_DataLens>,
                  "webSql": <run_SQL_queries_from_management_console>,
                  "metrika": <access_from_Metrica_and_AppMetrica>,
                  "serverless": <access_from_Cloud_Functions>,
                  "dataTransfer": <access_from_Data_Transfer>,
                  "yandexQuery": <access_from_Yandex_Query>
                },
                "cloudStorage": {
                  "enabled": <hybrid_storage_use>,
                  "moveFactor": "<share_of_free_space>",
                  "dataCacheEnabled": <temporary_file_storage>,
                  "dataCacheMaxSize": "<maximum_memory_for_file_storage>",
                  "preferNotToMerge": <disabling_data_part_merging>
                },
                "adminPassword": "<admin_user_password>",
                "sqlUserManagement": <user_management_via_SQL>,
                "sqlDatabaseManagement": <database_management_via_SQL>
              },
              "databaseSpecs": [
                {
                  "name": "<DB_name>",
                  "engine": "<database_engine>"
                },
                { <similar_settings_for_database_2> },
                { ... },
                { <similar_settings_for_database_N> }
              ],
              "userSpecs": [
                {
                  "name": "<username>",
                  "password": "<user_password>",
                  "permissions": [
                    {
                      "databaseName": "<DB_name>"
                    }
                  ]
                },
                { <similar_settings_for_user_2> },
                { ... },
                { <similar_settings_for_user_N> }
              ],
              "hostSpecs": [
                {
                  "zoneId": "<availability_zone>",
                  "type": "<host_type>",
                  "subnetId": "<subnet_ID>",
                  "assignPublicIp": <public_access_to_host>,
                  "shardName": "<shard_name>"
                },
                { <similar_settings_for_host_2> },
                { ... },
                { <similar_settings_for_host_N> }
              ],
              "shardSpecs": [
                {
                  "name": "<shard_name>",
                  "configSpec": {
                    "clickhouse": {
                      "weight": "<shard_weight>", 
                      "resources": {
                        "resourcePresetId": "<host_class_in_shard>",
                        "diskSize": "<storage_size_in_bytes>",
                        "diskTypeId": "<disk_type>"
                      },
                      "diskSizeAutoscaling": {
                        "plannedUsageThreshold": "<scheduled_expansion_threshold_in_percent>",
                        "emergencyUsageThreshold": "<immediate_expansion_threshold_in_percent>",
                        "diskSizeLimit": "<maximum_storage_size_in_bytes>"
                      },
                      "config": {
                        <DBMS_settings>
                      }
                    }
                  }
                },
                { <similar_set_of_settings_for_shard_2> },
                { ... },
                { <similar_set_of_settings_for_shard_N> }
              ],
              "deletionProtection": <cluster_deletion_protection>,
              "maintenanceWindow": {
                "weeklyMaintenanceWindow": {
                  "day": "<day_of_week>",
                  "hour": "<hour>"
                }
              }
            }
            ```


            Where:

            * `name`: Cluster name.
            * `environment`: Cluster environment, `PRODUCTION` or `PRESTABLE`.
            * `networkId`: ID of the [network](../../vpc/concepts/network.md) where the cluster will be deployed.

            
            * `securityGroupIds`: [Security group](../../vpc/concepts/security-groups.md) IDs as an array of strings. Each string is a security group ID.

                {% note warning %}
                
                If you specified security group IDs when creating a cluster, you may need to [configure these security groups](connect/index.md#configuring-security-groups) to enable cluster access.
                
                {% endnote %}


            * `configSpec`: Cluster configuration:

                * `version`: ClickHouse® version, 25.8.24.21 LTS, 26.3.12.3 LTS, 26.4.4.38 and 26.5.2.39.
                * `embeddedKeeper`: Use of the built-in ClickHouse® Keeper [coordination service](../concepts/coordination-system.md), `true` or `false`.

                    {% note alert %}
                    
                    You cannot disable ClickHouse® Keeper after creating a cluster. You will not be able to use ZooKeeper hosts as well.
                    
                    {% endnote %}

                * `clickhouse`: ClickHouse® configuration:

                    * `resources.resourcePresetId`: [Host class](../concepts/instance-types.md) ID. You can get the list of available host classes with their IDs by calling the [ResourcePreset.list](../api-ref/ResourcePreset/list.md) method.
                    * `resources.diskSize`: Disk size, in bytes.
                    * `resources.diskTypeId`: [Disk type](../concepts/storage.md).
                    * `diskSizeAutoscaling`: Automatic storage expansion settings for ClickHouse®:

                      * `plannedUsageThreshold`: Utilization threshold for the ClickHouse® storage capacity, in percent, to trigger an increase during the next maintenance window. The default value is `0` (auto increase disabled).
                      
                        The valid values range from `0` to `100`.
                      
                      * `emergencyUsageThreshold`: Utilization threshold for the ClickHouse® storage capacity, in percent, to trigger an immediate increase. The default value is `0` (auto increase disabled).
                      
                        The valid values range from `0` to `100`.
                      
                      * `diskSizeLimit`: Maximum ClickHouse® storage size, in bytes.
                      
                      {% note warning %}
                      
                      * If you specify both thresholds, `emergencyUsageThreshold` must not be less than `plannedUsageThreshold`.
                      
                      * When using `plannedUsageThreshold`, make sure to set up a [maintenance window](../concepts/maintenance.md).
                      
                      {% endnote %}
                      
                      The automatic storage expansion settings for ClickHouse® apply to all existing shards. If you add a new shard, it will use the settings of the oldest shard. These values are not saved in the ClickHouse® configuration.
                      
                      To view information about a specific shard, including automatic storage size increase settings, use the [Cluster.GetShard](../api-ref/Cluster/getShard.md) method and provide the cluster ID and shard name in the request.
                      
                      You can get the cluster ID with the [list of clusters](cluster-list.md#list-clusters) in the folder.
                      
                      You can get the shard name with the [list of shards](shards.md#list-shards) in the cluster.

                * `access`: Settings enabling cluster access from other services and [running SQL queries from the management console](web-sql-query.md) using Yandex WebSQL:

                    * `dataLens`: Enable access from DataLens, `true` or `false`. The default value is `false`. For more information about setting up a connection, see [Connecting from DataLens](datalens-connect.md).
                    
                    * `webSql`: Enable [SQL queries](web-sql-query.md) against cluster databases from the Yandex Cloud management console using Yandex WebSQL, `true` or `false`. The default value is `false`.
                    
                    
                    * `metrika`: Enable [data import from AppMetrica to your cluster](https://appmetrica.yandex.com/docs/common/cloud/about.html), `true` or `false`. The default value is `false`.
                    
                    * `serverless`: Enable access to the cluster from [Yandex Cloud Functions](../../functions/concepts/index.md), `true` or `false`. The default value is `false`. Learn more about access setup in [this Cloud Functions guide](../../functions/operations/database-connection.md).
                    
                    * `dataTransfer`: Enable access to the cluster from [Yandex Data Transfer](../../data-transfer/concepts/index.md) in Serverless mode, `true` or `false`. The default value is `false`.
                    
                        This will enable you to connect to Yandex Data Transfer running in Kubernetes via a special network to make other operations, e.g., transfer launch and deactivation, run faster.
                    
                    
                    * `yandexQuery`: Enable access to the cluster from [Yandex Query](../../query/concepts/index.md), `true` or `false`. This feature is at the [Preview](../../overview/concepts/launch-stages.md) stage. The default value is `false`.

                * `cloudStorage`: [Hybrid storage](../concepts/storage.md#hybrid-storage-features) settings:

                    * `enabled`: Enable hybrid storage in the cluster if it is disabled, `true` or `false`. The default value is `false` (disabled).
                    
                        {% note info %}
                        
                        Once hybrid storage is enabled, you cannot disable it.
                        
                        {% endnote %}
                    
                    * `moveFactor`: Minimum percentage of free space in the cluster storage. If your free space percentage is below this value, the data will be moved to Yandex Object Storage.
                    
                        The minimum value is `0`, the maximum value is `1`, and the default value is `0.01`.
                    
                    * `dataCacheEnabled`: Enable caching files in the cluster storage, `true` or `false`.
                    
                        The default value is `true` (enabled).
                    
                    * `dataCacheMaxSize`: Maximum cache size, in bytes, allocated in the cluster storage.
                        
                        If no value is set, the maximum cache size defaults to half the size of the cluster storage.
                    
                    * `preferNotToMerge`: Disable [merging of data parts](https://clickhouse.com/docs/enen/engines/table-engines/mergetree-family/custom-partitioning-key) in the cluster and object storage, `true` or `false`.
                    
                        To disable merging, set to `true`. To leave merging enabled, set to `false`.

                * `sql...` and `adminPassword`: Group of settings for user and database management via SQL:

                    * `adminPassword`: `admin` password.
                    * `sqlUserManagement`: [User management via SQL](cluster-users.md#sql-user-management), `true` or `false`.
                    * `sqlDatabaseManagement`: [Database management via SQL](databases.md#sql-database-management), `true` or `false`. For that, you also need to enable user management via SQL.


                    {% note warning %}
                    
                    You cannot disable settings for user or database management via SQL once they are enabled. You can enable them as required later when [reconfiguring your cluster](update.md#SQL-management).
                    
                    {% endnote %}

            * `databaseSpecs`: Database settings as an array of elements, one per database. Each element has the following structure:

                * `name`: Database name.
                * `engine`: Database engine. The possible values are:

                  * `DATABASE_ENGINE_ATOMIC` (default): `Atomic` engine; supports non-blocking `DROP TABLE` and `RENAME TABLE` queries, and atomic `EXCHANGE TABLES` queries.
                  * `DATABASE_ENGINE_REPLICATED`: `Replicated` engine; supports table metadata replication across all database replicas. The set of tables and their schemas will be the same for all replicas.
                                      
                    It is only available in [replicated](../concepts/replication.md) clusters.
                  
                  * `DATABASE_ENGINE_UNSPECIFIED`: This value will set the default engine, i.e., `DATABASE_ENGINE_ATOMIC`.
                                      
                  You can only set the engine when creating a database and cannot change it later.

            * `userSpecs`: User settings as an array of elements, one per user. Each element has the following structure:

                * `name`: Username. It may contain Latin letters, numbers, hyphens, and underscores, and must start with a letter or underscore. The name may be up to 32 characters long.
                * `password`: User password. The password must be from 8 to 128 characters long.
                
                    
                    You can also generate a password using Connection Manager. To do this, specify `"generatePassword": true` instead of `"password": "<user_password>"`.
                
                    To view the password, select your cluster in the [management console](https://console.yandex.cloud), navigate to the **Users** tab, and click **View password** for the relevant user. This will open the page of the Yandex Lockbox secret containing the password. To view passwords, you need the `lockbox.payloadViewer` role.
                
                
                * `permissions`: List of databases the user should have access to.
                
                    The list appears as an array of `databaseName` parameters. Each parameter contains the name of a separate database.

            * `hostSpecs`: Cluster host settings as an array of elements, one per host. Each element has the following structure:

                * `type`: Host type, `CLICKHOUSE`.
                * `zoneId`: [Availability zone](../../overview/concepts/geo-scope.md).

                
                * `subnetId`: [Subnet](../../vpc/concepts/network.md#subnet) ID.


                * `shardName`: [Shard](../concepts/sharding.md) name. This setting is only relevant for `CLICKHOUSE` hosts.

                
                * `assignPublicIp`: Internet access to the host via a public IP address, `true` or `false`.

                   {% note warning %}
                   
                   For a more secure cluster with public host access enabled, use only trusted IP addresses or subnets in the cluster's security group rules. Learn more in [Configuring security groups](connect/index.md#configuring-security-groups).
                   
                   {% endnote %}

                If you create a cluster of two or more ClickHouse® hosts without the coordination service and the cluster [network](../../vpc/concepts/network.md) has [subnets](../../vpc/concepts/network.md#subnet) in each [availability zone](../../overview/concepts/geo-scope.md), the system automatically adds three ZooKeeper hosts one in each subnet.
                
                If subnets are located only in some availability zones, or you want to use a different coordination service, manually specify the coordination service and its host settings.


            * `shardSpecs`: Shard settings as an array of elements, one per shard. If you skip this section in the request, the new cluster will have a single shard named `shard1`. You can specify the following settings:

                * `name`: Shard name.
                * `weight`: Shard weight.
                * `configSpec.clickhouse`: Shard host configuration, i.e., including host class, storage settings, and DBMS settings. If you skip the shard host configuration, it will be inherited from the cluster configuration.

            * `deletionProtection`: Cluster deletion protection, `true` or `false`. The default value is `false`.

                Even with cluster deletion protection enabled, one can still delete a user or database or connect manually and delete the database contents.

            * `maintenanceWindow`: Maintenance window settings:

                * `weeklyMaintenanceWindow.day`: Day of week. The valid values are `MON`, `TUE`, `WED`, `THU`, `FRI`, `SAT`, and `SUN`.
                * `weeklyMaintenanceWindow.hour`: Time of day (UTC). The valid values range from `1` to `24`.

            
            You can get the folder ID with the [list of folders in the cloud](../../resource-manager/operations/folder/get-id.md).


        1. Run this request:

            ```bash
            curl \
              --request POST \
              --header "Authorization: Bearer $IAM_TOKEN" \
              --header "Content-Type: application/json" \
              --url 'https://mdb.api.cloud.yandex.net/managed-clickhouse/v1/clusters' \
              --data '@body.json'
            ```

    1. View the [server response](../api-ref/Cluster/create.md#responses) to make sure your request was successful.

- gRPC API {#grpc-api}

    To create a Managed Service for ClickHouse® cluster with the built-in ClickHouse® Keeper coordination service:

    1. [Get an IAM token for API authentication](../api-ref/authentication.md) and put it into an environment variable:

        ```bash
        export IAM_TOKEN="<IAM_token>"
        ```

    1. Clone the [cloudapi](https://github.com/yandex-cloud/cloudapi) repository:
       
       ```bash
       cd ~/ && git clone --depth=1 https://github.com/yandex-cloud/cloudapi
       ```
       
       Below, we assume that the repository contents reside in the `~/cloudapi/` directory.

    1. Call the [ClusterService.Create](../api-ref/grpc/Cluster/create.md) method, e.g., via the following [gRPCurl](https://github.com/fullstorydev/grpcurl) request:

        1. Create a file named `body.json` and paste the following code into it (the example does not show all the available properties):

            
            ```json
            {
              "folder_id": "<folder_ID>",
              "name": "<cluster_name>",
              "environment": "<environment>",
              "network_id": "<network_ID>",
              "security_group_ids": [
                "<security_group_1_ID>",
                "<security_group_2_ID>",
                ...
                "<security_group_N_ID>"
              ],
              "config_spec": {
                "version": "<ClickHouse®_version>",
                "embedded_keeper": true,
                "clickhouse": {
                  "resources": {
                    "resource_preset_id": "<ClickHouse®_host_class>",
                    "disk_size": "<storage_size_in_bytes>",
                    "disk_type_id": "<disk_type>"
                  },
                  "disk_size_autoscaling": {
                    "planned_usage_threshold": "<scheduled_expansion_threshold_in_percent>",
                    "emergency_usage_threshold": "<immediate_expansion_threshold_in_percent>",
                    "disk_size_limit": "<maximum_storage_size_in_bytes>"
                  }
                },
                "access": {
                  "data_lens": <access_from_DataLens>,
                  "web_sql": <run_SQL_queries_from_management_console>,
                  "metrika": <access_from_Metrica_and_AppMetrica>,
                  "serverless": <access_from_Cloud_Functions>,
                  "data_transfer": <access_from_Data_Transfer>,
                  "yandex_query": <access_from_Yandex_Query>
                },
                "cloud_storage": {
                  "enabled": <hybrid_storage_use>,
                  "move_factor": "<share_of_free_space>",
                  "data_cache_enabled": <temporary_file_storage>,
                  "data_cache_max_size": "<maximum_memory_for_file_storage>",
                  "prefer_not_to_merge": <disabling_data_part_merging>
                },
                "admin_password": "<admin_user_password>",
                "sql_user_management": <user_management_via_SQL>,
                "sql_database_management": <database_management_via_SQL>
              },
              "database_specs": [
                {
                  "name": "<DB_name>",
                  "engine": "<database_engine>"
                },
                { <similar_settings_for_database_2> },
                { ... },
                { <similar_settings_for_database_N> }
              ],
              "user_specs": [
                {
                  "name": "<username>",
                  "password": "<user_password>",
                  "permissions": [
                    {
                      "database_name": "<DB_name>"
                    }
                  ]
                },
                { <similar_settings_for_user_2> },
                { ... },
                { <similar_settings_for_user_N> }
              ],
              "host_specs": [
                {
                  "zone_id": "<availability_zone>",
                  "type": "<host_type>",
                  "subnet_id": "<subnet_ID>",
                  "assign_public_ip": <public_access_to_host>,
                  "shard_name": "<shard_name>"
                },
                { <similar_settings_for_host_2> },
                { ... },
                { <similar_settings_for_host_N> }
              ],
              "shard_specs": [
                {
                  "name": "<shard_name>",
                  "config_spec": {
                    "clickhouse": {
                      "weight": "<shard_weight>",
                      "resources": {
                        "resource_preset_id": "<host_class>",
                        "disk_size": "<storage_size_in_bytes>",
                        "disk_type_id": "<disk_type>"
                      },
                      "disk_size_autoscaling": {
                        "planned_usage_threshold": "<scheduled_expansion_threshold_in_percent>",
                        "emergency_usage_threshold": "<immediate_expansion_threshold_in_percent>",
                        "disk_size_limit": "<maximum_storage_size_in_bytes>"
                      },
                      "config": {
                        <DBMS_settings>
                      }
                    }
                  }
                },
                { <similar_set_of_settings_for_shard_2> },
                { ... },
                { <similar_set_of_settings_for_shard_N> }
              ],
              "deletion_protection": <cluster_deletion_protection>,
              "maintenance_window": {
                "weekly_maintenance_window": {
                  "day": "<day_of_week>",
                  "hour": "<hour>"
                }
              }
            ```


            Where:

            * `name`: Cluster name.
            * `environment`: Cluster environment, `PRODUCTION` or `PRESTABLE`.

            * `network_id`: ID of the [network](../../vpc/concepts/network.md) where the cluster will be deployed.

            
            * `security_group_ids`: [Security group](../../vpc/concepts/security-groups.md) IDs as an array of strings. Each string is a security group ID.

                {% note warning %}
                
                If you specified security group IDs when creating a cluster, you may need to [configure these security groups](connect/index.md#configuring-security-groups) to enable cluster access.
                
                {% endnote %}


            * `config_spec`: Cluster configuration:

                * `version`: ClickHouse® version, 25.8.24.21 LTS, 26.3.12.3 LTS, 26.4.4.38 and 26.5.2.39.

                * `embedded_keeper`: Use of the built-in ClickHouse® Keeper [coordination service](../concepts/coordination-system.md), `true` or `false`.

                    {% note alert %}
                    
                    You cannot disable ClickHouse® Keeper after creating a cluster. You will not be able to use ZooKeeper hosts as well.
                    
                    {% endnote %}

                * `clickhouse`: ClickHouse® configuration:

                    * `resources.resource_preset_id`: [Host class](../concepts/instance-types.md) ID. You can get the list of available host classes with their IDs using the [ResourcePreset.list](../api-ref/ResourcePreset/list.md) method.
                    * `resources.disk_size`: Disk size, in bytes.
                    * `resources.disk_type_id`: [Disk type](../concepts/storage.md).

                    * `disk_size_autoscaling`: Automatic storage expansion settings for ClickHouse®:

                        * `planned_usage_threshold`: Utilization threshold for the ClickHouse® storage capacity, in percent, to trigger an expansion during the next maintenance window. The default value is `0` (auto increasing disabled).
                                              
                          The valid values range from `0` to `100`.
                                              
                        * `emergency_usage_threshold`: Utilization threshold for the ClickHouse® storage capacity, in percent, to trigger an immediate expansion. The default value is `0` (auto increasing disabled).
                                              
                          The valid values range from `0` to `100`.
                                              
                        * `disk_size_limit`: Maximum ClickHouse® storage size, in bytes.
                                              
                        {% note warning %}
                                              
                        * If you specify both thresholds, `emergency_usage_threshold` must not be less than `planned_usage_threshold`.
                                              
                        * When using `planned_usage_threshold`, make sure to set up a [maintenance window](../concepts/maintenance.md).
                                              
                        {% endnote %}
                                              
                        The automatic storage size increase settings for ClickHouse® apply to all existing shards. If you add a new shard, it will use the settings of the oldest shard. These values are not saved in the ClickHouse® configuration.
                                              
                        To view information about a specific shard, including automatic storage expansion settings, use the [ClusterService.GetShard](../api-ref/grpc/Cluster/getShard.md) method and provide the cluster ID and shard name in the request.
                                              
                        You can get the cluster ID with the [list of clusters](cluster-list.md#list-clusters) in the folder.
                        
                        You can get the shard name with the [list of shards](shards.md#list-shards) in the cluster.

                * `access`: Settings enabling cluster access from other services and [running SQL queries from the management console](web-sql-query.md) using Yandex WebSQL:

                    * `data_lens`: Enable access from DataLens, `true` or `false`. The default value is `false`. For more information about setting up a connection, see [Connecting from DataLens](datalens-connect.md).
                    
                    * `web_sql`: Enable [SQL queries](web-sql-query.md) against cluster databases from the Yandex Cloud management console using Yandex WebSQL, `true` or `false`. The default value is `false`.
                    
                    
                    * `metrika`: Enable [data import from AppMetrica to your cluster](https://appmetrica.yandex.com/docs/common/cloud/about.html), `true` or `false`. The default value is `false`.
                    
                    * `serverless`: Enable access to the cluster from [Yandex Cloud Functions](../../functions/concepts/index.md), `true` or `false`. The default value is `false`. Learn more about access setup in [this Cloud Functions guide](../../functions/operations/database-connection.md).
                    
                    * `data_transfer`: Enable access to the cluster from [Yandex Data Transfer](../../data-transfer/concepts/index.md) in Serverless mode, `true` or `false`. The default value is `false`.
                    
                        This will enable you to connect to Yandex Data Transfer running in Kubernetes via a special network to make other operations, e.g., transfer launch and deactivation, run faster.
                    
                    
                    * `yandex_query`: Enable access to the cluster from [Yandex Query](../../query/concepts/index.md), `true` or `false`. This feature is at the [Preview](../../overview/concepts/launch-stages.md) stage. The default value is `false`.

                * `cloud_storage`: [Hybrid storage](../concepts/storage.md#hybrid-storage-features) settings:

                    * `enabled`: Enable hybrid storage in the cluster if it is disabled, `true` or `false`. The default value is `false` (disabled).
                    
                        {% note info %}
                        
                        Once hybrid storage is enabled, you cannot disable it.
                        
                        {% endnote %}
                    
                    * `move_factor`: Minimum percentage of free space in the cluster storage. If your free space percentage is below this value, the data will be moved to Yandex Object Storage.
                    
                        The minimum value is `0`, the maximum value is `1`, and the default value is `0.01`.
                    
                    * `data_cache_enabled`: Enable caching files in the cluster storage, `true` or `false`.
                    
                        The default value is `true` (enabled).
                    
                    * `data_cache_max_size`: Maximum cache size, in bytes, allocated in the cluster storage.
                    
                        If no value is set, the maximum cache size defaults to half the size of the cluster storage.
                    
                    * `prefer_not_to_merge`: Disable [merging of data parts](https://clickhouse.com/docs/enen/engines/table-engines/mergetree-family/custom-partitioning-key) in the cluster and object storage, `true` or `false`.
                    
                        To disable merging, set to `true`. To leave merging enabled, set to `false`.

                * `sql...` and `admin_password`: Group of settings for user and database management via SQL:

                    * `admin_password`: `admin` password.
                    * `sql_user_management`: [User management via SQL](cluster-users.md#sql-user-management), `true` or `false`.
                    * `sql_database_management`: [Database management via SQL](databases.md#sql-database-management), `true` or `false`. For that, you also need to enable user management via SQL.


                    {% note warning %}
                    
                    You cannot disable settings for user or database management via SQL once they are enabled. You can enable them as required later when [reconfiguring your cluster](update.md#SQL-management).
                    
                    {% endnote %}

            * `database_specs`: Database settings as an array of elements, one per database. Each element has the following structure:

                * `name`: Database name.
                * `engine`: Database engine. The possible values are:

                  * `DATABASE_ENGINE_ATOMIC` (default): `Atomic` engine; supports non-blocking `DROP TABLE` and `RENAME TABLE` queries, and atomic `EXCHANGE TABLES` queries.
                  * `DATABASE_ENGINE_REPLICATED`: `Replicated` engine; supports table metadata replication across all database replicas. The set of tables and their schemas will be the same for all replicas.
                                      
                    It is only available in [replicated](../concepts/replication.md) clusters.
                  
                  * `DATABASE_ENGINE_UNSPECIFIED`: This value will set the default engine, i.e., `DATABASE_ENGINE_ATOMIC`.
                                      
                  You can only set the engine when creating a database and cannot change it later.

            * `user_specs`: User settings as an array of elements, one per user. Each element has the following structure:

                * `name`: Username. It may contain Latin letters, numbers, hyphens, and underscores, and must start with a letter or underscore. The name may be up to 32 characters long.
                * `password`: User password. The password must be from 8 to 128 characters long.
                
                  
                  You can also generate a password using Connection Manager. To do this, specify `"generate_password": true` instead of `"password": "<user_password>"`.
                
                  To view the password, select your cluster in the [management console](https://console.yandex.cloud), navigate to the **Users** tab, and click **View password** for the relevant user. This will open the page of the Yandex Lockbox secret containing the password. To view passwords, you need the `lockbox.payloadViewer` role.
                
                
                * `permissions`: List of databases the user should have access to.
                
                    The list appears as an array of `database_name` parameters. Each parameter contains the name of a separate database.

            * `host_specs`: Cluster host settings as an array of elements, one per host. Each element has the following structure:

                * `type`: Host type, `CLICKHOUSE`.
                * `zone_id`: [Availability zone](../../overview/concepts/geo-scope.md).

                
                * `subnet_id`: [Subnet](../../vpc/concepts/network.md#subnet) ID.


                * `shard_name`: [Shard](../concepts/sharding.md) name. This setting is only relevant for `CLICKHOUSE` hosts.

                
                * `assign_public_ip`: Internet access to the host via a public IP address, `true` or `false`.

                   {% note warning %}
                   
                   For a more secure cluster with public host access enabled, use only trusted IP addresses or subnets in the cluster's security group rules. Learn more in [Configuring security groups](connect/index.md#configuring-security-groups).
                   
                   {% endnote %}

                If you create a cluster of two or more ClickHouse® hosts without the coordination service and the cluster [network](../../vpc/concepts/network.md) has [subnets](../../vpc/concepts/network.md#subnet) in each [availability zone](../../overview/concepts/geo-scope.md), the system automatically adds three ZooKeeper hosts one in each subnet.
                
                If subnets are located only in some availability zones, or you want to use a different coordination service, manually specify the coordination service and its host settings.


            * `shard_specs`: Shard settings as an array of elements, one per shard. If you skip this section in the request, the new cluster will have a single shard named `shard1`. You can specify the following settings:

                * `name`: Shard name.
                * `weight`: Shard weight.
                * `config_spec.clickhouse`: Shard host configuration, i.e., including host class, storage settings, and DBMS settings. If you skip the shard host configuration, it will be inherited from the cluster configuration.

            * `deletion_protection`: Cluster deletion protection, `true` or `false`. The default value is `false`.

                Even with cluster deletion protection enabled, one can still delete a user or database or connect manually and delete the database contents.

            * `maintenance_window`: Maintenance window settings:

              * `weekly_maintenance_window.day`: Day of week. The valid values are `MON`, `TUE`, `WED`, `THU`, `FRI`, `SAT`, and `SUN`.
              * `weekly_maintenance_window.hour`: Time of day (UTC). The valid values range from `1` to `24`.

            
            You can get the folder ID with the [list of folders in the cloud](../../resource-manager/operations/folder/get-id.md).


        1. Run this query:

            ```bash
            grpcurl \
              -format json \
              -import-path ~/cloudapi/ \
              -import-path ~/cloudapi/third_party/googleapis/ \
              -proto ~/cloudapi/yandex/cloud/mdb/clickhouse/v1/cluster_service.proto \
              -rpc-header "Authorization: Bearer $IAM_TOKEN" \
              -d @ \
              mdb.api.cloud.yandex.net:443 \
              yandex.cloud.mdb.clickhouse.v1.ClusterService.Create \
              < body.json
            ```

    1. Check the [server response](../api-ref/grpc/Cluster/create.md#yandex.cloud.operation.Operation) to make sure your request was successful.

{% endlist %}

## Creating a cluster with ZooKeeper {#create-cluster-zk}

{% list tabs group=instructions %}

- Management console {#console}

  To create a Managed Service for ClickHouse® cluster with the ZooKeeper coordination service:

  1. In the [management console](https://console.yandex.cloud), select the folder where you want to create your database cluster.
  1. Navigate to **Managed Service for&nbsp;ClickHouse**.
  1. Click **Create cluster**.
  1. Enter a cluster name in the **Cluster name** field. The cluster name must be unique within the folder.
  1. Select the environment where you want to create your cluster (you cannot change the environment once the cluster is created):
      * `PRODUCTION`: For stable versions of your applications.
      * `PRESTABLE`: For testing purposes. The prestable environment is similar to the production environment and likewise covered by an SLA, but it is the first to get new features, improvements, and bug fixes. In the prestable environment, you can test new versions for compatibility with your application.
  1. Select the [ClickHouse® version](../concepts/update-policy.md) the Managed Service for ClickHouse® cluster will use from the **Version** drop-down list. For most clusters, we recommend selecting the latest LTS version.

  1. Under **Resources**:

      * Select the platform, VM type, and host class. The latter determines the technical specifications of the VMs the database hosts will be deployed on. All available options are listed under [Host classes](../concepts/instance-types.md). When you change the host class for a cluster, the specifications of all existing instances also change.

      
      * Select the [disk type](../concepts/storage.md).

        The type you select determines the increments for changing the disk size:
        
        * Network HDDs and SSDs: In increments of 1 GB.
        * Local SSDs:
            * For **Intel Broadwell** and **Intel Cascade Lake**: In 100 GB increments.
            * For **Intel Ice Lake** and **AMD Zen 4**: In 368 GB increments.
        * Non-replicated SSDs and ultra high-speed network SSDs with three replicas: In increments of 93 GB.


      * Select the size of your data and backup disk. For details on how backups consume storage space, see [Backups](../concepts/backup.md).

      * Optionally, configure [automatic increase of storage size](../concepts/storage.md#autoscaling) for ClickHouse®:

        * In the **Increase size** field, select one or both thresholds:
          * **In the maintenance window when full at more than**: Scheduled expansion threshold. When reached, the storage expands during the next [maintenance window](../concepts/maintenance.md#maintenance-window).
            
            For a scheduled expansion, you need to set up a [maintenance window](../concepts/maintenance.md#maintenance-window) schedule.
        
          * **Immediately when full at more than**: Immediate expansion threshold. When reached, the storage expands immediately.
        * Specify a threshold value (as a percentage of the total storage size). If you select both thresholds, make sure the immediate expansion threshold is not less than the scheduled one.
        * Set **Maximum storage size**.

        The automatic storage size increase settings for ClickHouse® apply to all existing shards. If you add a new shard, it will use the settings of the oldest shard.

  
  1. Under **Network settings**, select the cloud network to host your cluster and security groups for cluster network traffic. You may need to additionally [set up security groups](connect/index.md#configuring-security-groups) to be able connect to the cluster.


    1. Optionally, under **Sharding settings**:

        * Enable **Cluster sharding** to create a cluster with multiple [shards](../concepts/sharding.md) from the outset. You can also add shards after you create a cluster.

        * Set up shards created together with the cluster. To change a shard's settings, click ![pencil](../../_assets/console-icons/pencil.svg) next to its number:

            * **Shard name** and its **Weight**.

            * **Configuration** of shard hosts:

                * **Default**: Hosts will inherit the cluster configuration.

                * **Redefined**: Set the host class, storage settings, and DBMS settings for all shard hosts.

        To add shards to a cluster, click **Add shard**.

  1. Under **Hosts**:

      * Set up database hosts created together with the cluster. To change the host settings, click ![pencil](../../_assets/console-icons/pencil.svg) next to the host number:

        * **Availability zone**: Select the [availability zone](../../overview/concepts/geo-scope.md).

        
        * **Subnet**: Specify a [subnet](../../vpc/concepts/network.md#subnet) in the selected availability zone.
        * **Public access**: Allow [access](connect/index.md) to the host from the internet.


        * If cluster [sharding](../concepts/sharding.md) is enabled, select a shard.

        To add hosts to your cluster, click **Add host**.

      * Select the **ZooKeeper (on separate hosts)** [coordination service](../concepts/coordination-system.md).

  1. Under **ZooKeeper host class**, select the platform, VM type, and [host class](../concepts/instance-types.md) for your ZooKeeper hosts.

  1. Under **ZooKeeper storage size**, select the [disk type](../concepts/storage.md) and storage size. Optionally, configure [automatic increase of storage size](../concepts/storage.md#autoscaling) for ZooKeeper hosts.

  1. Under **ZooKeeper hosts**, change the settings of the automatically added ZooKeeper hosts as appropriate.

      To change the host settings, click ![pencil](../../_assets/console-icons/pencil.svg) next to the host and specify the following:

      * **Availability zone**: Select the [availability zone](../../overview/concepts/geo-scope.md).

      
      * **Subnet**: Select the [subnet](../../vpc/concepts/network.md#subnet) in the selected availability zone.


  1. Under **DBMS settings**:

      * If you want to manage cluster users via SQL, select **Enabled** from the drop-down list in the **User management via SQL** field and enter the `admin` password. This disables user management through other interfaces.

        Otherwise, select **Disabled**.


      * If you want to manage databases via SQL, select **Enabled** from the drop-down list in the **Managing databases via SQL** field. This disables database management through other interfaces. This field is inactive if user management via SQL is disabled.

        Otherwise, select **Disabled**.

        {% note warning %}
        
        You cannot disable settings for user or database management via SQL once they are enabled. You can enable them as required later when [reconfiguring your cluster](update.md#SQL-management).
        
        {% endnote %}

      * Specify a username.

        The username may contain Latin letters, numbers, hyphens, and underscores but must begin with a letter or underscore. The name may be up to 32 characters long.

      
      * Specify a user password:

        * **Enter manually**: Select this option to set your own password. It must be from 8 to 128 characters long.

        * **Generate**: Select this option to generate a password using Connection Manager.

        To view the password after creating a cluster, select the **Users** tab and click **View password** for the relevant user. This will open the page of the Yandex Lockbox secret containing the password. To view passwords, you need the `lockbox.payloadViewer` role.


      * Specify a database name. The database name may include Latin letters, numbers, and underscores. It may be up to 63 characters long. You cannot create a database named `default`.

      * Select the database engine:

        * `Atomic`, the default option, supports the non-blocking `DROP TABLE` and `RENAME TABLE` operations and atomic `EXCHANGE TABLES` operations.
        * `Replicated` supports table metadata replication across all database replicas. The set of tables and their schemas will be the same for all replicas.

          It is only available in [replicated](../concepts/replication.md) clusters.

        You can only set the engine when creating a database and cannot change it later.

      * Enable [hybrid storage](../concepts/storage.md#hybrid-storage-features) for the cluster, if required.

        {% note warning %}

        You cannot disable this option.

        {% endnote %}

      * [Configure the DBMS](../concepts/settings-list.md#server-level-settings), if required. You can do it later.

        Using the Yandex Cloud interfaces, you can manage a limited number of settings. Using SQL queries, you can [specify the ClickHouse® settings at the query level](change-query-level-settings.md).

  1. Specify the cluster service settings, if required:

      * **Backup start time (UTC)**: Time interval during which the cluster backup starts. Time is specified in 24-hour UTC format. The default time is `22:00 - 23:00` UTC.
      
      * **Retention period for automatic backups, days**: Retention period for automatic backups, in days. Backups are automatically deleted once their retention period expires. The default is 7 days. For more information, see [Backups](../concepts/backup.md#storage).
      
          Changing the retention period affects both new and existing automatic backups. For example, the initial retention period was 7 days, and the remaining lifetime of a single automatic backup is 1 day. If the retention period increases to 9 days, the remaining lifetime for this backup will now be 3 days.
      
      * **Maintenance**: [Maintenance](../concepts/maintenance.md) window settings:
      
         * To enable maintenance at any time, select **At any time** (default).
         * To specify the preferred maintenance start time, select **By schedule** and specify the day of the week and the UTC time interval. For example, you can choose a time when the cluster is least loaded.
         
         Both active and stopped clusters are subject to maintenance. Maintenance operations include DBMS updates, patches, etc.
      
      
      * **Service account**: Account user programs can use to manage the cluster. For more information, see [this guide](../security.md).
      
      * **Disk encryption**: This option enables disk encryption with a [custom KMS key](../../kms/concepts/key.md). Set a key in one of the following ways:
      
         * To [create](../../kms/operations/key.md#create) a new key, click **Create**.
      
         * To use a previously created key, select it in the **KMS key** field.
      
         Learn more about disk encryption in [Storage](../concepts/storage.md#disk-encryption).
      
      
      * **DataLens access**: This option enables you to analyze cluster data in [Yandex DataLens](../../datalens/concepts/index.md).
      
      
      * **WebSQL access**: This option enables you to [run SQL queries](web-sql-query.md) against cluster databases from the Yandex Cloud management console using Yandex WebSQL.
      
      
      
      
      * **Access from Metrica and AppMetrica**: This option enables you to [import data from AppMetrica](https://appmetrica.yandex.ru/docs/en/common/cloud) to a cluster.
      
      * **Serverless access**: Enable this option to allow cluster access from [Yandex Cloud Functions](../../functions/concepts/index.md). Learn more about access setup in [this Cloud Functions guide](../../functions/operations/database-connection.md).
      
      
      * **Yandex Query access**: Enable this option to allow cluster access from [Yandex Query](../../query/concepts/index.md). This feature is at the [Preview](../../overview/concepts/launch-stages.md) stage.
      
      * **Deletion protection**: Manages cluster protection against accidental deletion.
      
         Even with cluster deletion protection enabled, one can still delete a user or database or connect manually and delete the database contents.

  1. Click **Create cluster**.

- 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 Managed Service for ClickHouse® cluster with the ZooKeeper coordination service:

  
  1. Check whether the folder has any subnets for cluster hosts:

      ```bash
      yc vpc subnet list
      ```

     If there are no subnets in the folder, [create the right ones](../../vpc/operations/subnet-create.md) in VPC.


  1. View the description of the CLI command for creating a cluster:

      ```bash
      yc managed-clickhouse cluster create --help
      ```

  1. Specify the cluster properties in this command (the example does not show all that are available):

      
      ```bash
      yc managed-clickhouse cluster create \
        --name <cluster_name> \
        --environment <environment> \
        --network-name <network_name> \
        --shard name=<shard_name>,weight=<shard_weight> \
        --host type=<host_type>,`
              `zone-id=<availability_zone>,`
              `subnet-id=<subnet_ID>,`
              `assign-public-ip=<public_access_to_host>,`
              `shard-name=<shard_name> \
        --clickhouse-resource-preset <host_class> \
        --clickhouse-disk-type <disk type> \
        --clickhouse-disk-size <storage_size_in_GB> \
        --zookeeper-resource-preset <host_class> \
        --zookeeper-disk-type <disk type> \
        --zookeeper-disk-size <storage_size_in_GB> \
        --user name=<username>,password=<user_password> \
        --database name=<DB_name> \
        --security-group-ids <list_of_security_group_IDs> \
        --websql-access=<access_from_WebSQL> \
        --deletion-protection
      ```


      Where:

      * `--environment`: Cluster environment, `prestable` or `production`.
      * `--shard`: [Shard](../concepts/sharding.md) properties, such as name and weight.

        To create a cluster with multiple shards from the outset, specify this flag as many times as needed. If you do not specify the `--shard` flag, the new cluster will have a single shard named `shard1`.

      * `--host`: Host settings:
        * `type`: Host type, `clickhouse` or `zookeeper`.
        * `zone-id`: Availability zone.

        
        * `subnet-id`: Subnet ID. Specify if the selected availability zone has two or more subnets.
        * `assign-public-ip`: Internet access to the host via a public IP address, `true` or `false`. This setting is only relevant for `CLICKHOUSE` hosts.

          {% note warning %}
          
          For a more secure cluster with public host access enabled, use only trusted IP addresses or subnets in the cluster's security group rules. Learn more in [Configuring security groups](connect/index.md#configuring-security-groups).
          
          {% endnote %}


        * `shard-name`: Name of the shard the host will reside in.

        
        If you create a cluster of two or more ClickHouse® hosts without the coordination service and the cluster [network](../../vpc/concepts/network.md) has [subnets](../../vpc/concepts/network.md#subnet) in each [availability zone](../../overview/concepts/geo-scope.md), the system automatically adds three ZooKeeper hosts one in each subnet.
        
        If subnets are located only in some availability zones, or you want to use a different coordination service, manually specify the coordination service and its host settings.


        Specify a separate `--host` flag for each host.

      * `--clickhouse-resource-preset`: ClickHouse® [host class](../concepts/instance-types.md).
      * `--clickhouse-disk-type`: ClickHouse® [disk type](../concepts/storage.md).
      * `--clickhouse-disk-size`: ClickHouse® storage size in GB.
      * `--zookeeper-resource-preset`: ZooKeeper [host class](../concepts/instance-types.md).
      * `--zookeeper-disk-type`: ZooKeeper [disk type](../concepts/storage.md).
      * `--zookeeper-disk-size`: ZooKeeper storage size in GB.
      * `--user`: Contains the ClickHouse® user `name` and `password`.

        The username may contain Latin letters, numbers, hyphens, and underscores but must begin with a letter or underscore. The name may be up to 32 characters long.

        The password must be from 8 to 128 characters long.

        
        {% note info %}

        You can also generate a password using Connection Manager. To do this, edit the command, specifying the user properties as follows:

        ```bash
          --user name=<username>,generate-password=true
        ```

        To view the password, select your cluster in the [management console](https://console.yandex.cloud), navigate to the **Users** tab, and click **View password** for the relevant user. This will open the page of the Yandex Lockbox secret containing the password. To view passwords, you need the `lockbox.payloadViewer` role.

        {% endnote %}


      
      * `--security-group-ids`: Security group IDs, comma-separated.

          {% note warning %}
          
          If you specified security group IDs when creating a cluster, you may need to [configure these security groups](connect/index.md#configuring-security-groups) to enable cluster access.
          
          {% endnote %}


      * `--websql-access`: Enables [SQL queries](web-sql-query.md) against cluster databases from the Yandex Cloud management console using Yandex WebSQL. The default value is `false`.

      * `--deletion-protection`: Cluster protection from accidental deletion, `true` or `false`.

        Even with cluster deletion protection enabled, one can still delete a user or database or connect manually and delete the database contents.

      You can manage cluster users and databases via SQL.

      {% note warning %}
      
      You cannot disable settings for user or database management via SQL once they are enabled. You can enable them as required later when [reconfiguring your cluster](update.md#SQL-management).
      
      {% endnote %}

      1. To enable [user management via SQL](cluster-users.md#sql-user-management):

         * Set `--enable-sql-user-management` to `true`.
         * Set a password for `admin` in the `--admin-password` parameter.

         ```bash
         yc managed-clickhouse cluster create \
           ...
           --enable-sql-user-management true \
           --admin-password "<admin_password>"
         ```


      1. To enable [database management via SQL](databases.md#sql-database-management):

         * Set `--enable-sql-user-management` and `--enable-sql-database-management` to `true`.
         * Set a password for `admin` in the `--admin-password` parameter.

         ```bash
         yc managed-clickhouse cluster create \
           ...
           --enable-sql-user-management true \
           --enable-sql-database-management true \
           --admin-password "<admin_user_password>"
         ```

      
      1. To encrypt the disk with a [custom KMS key](../../kms/concepts/key.md), provide `--disk-encryption-key-id <KMS_key_ID>`.

         To learn more about disk encryption, see [Storage](../concepts/storage.md#disk-encryption).

      1. To allow access to the cluster from [Yandex Cloud Functions](../../functions/concepts/index.md), provide `--serverless-access`. For more information about access setup, see [this Cloud Functions guide](../../functions/operations/database-connection.md).


      1. To allow access to the cluster from [Yandex Query](../../query/concepts/index.md), provide the `--yandexquery-access=true` parameter. This feature is at the [Preview](../../overview/concepts/launch-stages.md) stage.


      1. To [configure hybrid storage](../concepts/storage.md#hybrid-storage-settings):

         * Set `--cloud-storage` to `true` to enable hybrid storage.

            {% note info %}
            
            Once hybrid storage is enabled, you cannot disable it.
            
            {% endnote %}

         * Provide the hybrid storage settings in the relevant parameters:

            * `--cloud-storage-data-cache`: Enables caching files in the cluster storage. The default value is `true` (enabled).
            * `--cloud-storage-data-cache-max-size`: Sets the maximum cache size, in bytes, allocated in the cluster storage. If no value is set, the maximum cache size defaults to half the size of the cluster storage.
            * `--cloud-storage-move-factor`: Sets the minimum percentage of free space in the cluster storage. If your free space percentage is below this value, the data will be moved to Yandex Object Storage. The minimum value is `0`, the maximum value is `1`, and the default value is `0.01`.
            * `--cloud-storage-prefer-not-to-merge`: Disables [merging of data parts](https://clickhouse.com/docs/enen/engines/table-engines/mergetree-family/custom-partitioning-key) in cluster and object storages. To disable merges, set the parameter to `true` or provide it with no value. To keep merges enabled, set the parameter to `false` or do not provide it in the CLI command when creating a cluster.

         ```bash
         yc managed-clickhouse cluster create \
            ...
            --cloud-storage=true \
            --cloud-storage-data-cache=<file_storage> \
            --cloud-storage-data-cache-max-size=<memory_size_in_bytes> \
            --cloud-storage-move-factor=<share_of_free_space> \
            --cloud-storage-prefer-not-to-merge=<merging_data_parts>
           ...
         ```

         Where:
         * `--cloud-storage-data-cache`: Set to store files in a cluster storage, `true` or `false`.
         * `--cloud-storage-prefer-not-to-merge`: Disables merging of data parts in a cluster and object storage, `true` or `false`.

      1. To configure automatic expansion settings for your ClickHouse® and ZooKeeper storages, use the `--disk-size-autoscaling` flag:

         ```bash
         yc managed-clickhouse cluster create \
           ...
           --disk-size-autoscaling clickhouse-disk-size-limit=<maximum_storage_size_in_GB>,`
                                  `clickhouse-planned-usage-threshold=<scheduled_expansion_threshold_in_percent>,`
                                  `clickhouse-emergency-usage-threshold=<immediate_expansion_threshold_in_percent>,`
                                  `zookeeper-disk-size-limit=<maximum_storage_size_in_GB>,`
                                  `zookeeper-planned-usage-threshold=<scheduled_expansion_threshold_in_percent>,`
                                  `zookeeper-emergency-usage-threshold=<immediate_expansion_threshold_in_percent>
           ...
         ```

         Where `--disk-size-autoscaling` defines the automatic storage size increase settings:

         * `clickhouse-disk-size-limit`: Maximum ClickHouse® storage size, in GB.
         
         * `clickhouse-planned-usage-threshold`: ClickHouse® storage utilization threshold to trigger an increase during the next maintenance window, in percent. The default value is `0` (auto increase disabled).
         
           The valid values range from `0` to `100`.
         
         * `clickhouse-emergency-usage-threshold`: Utilization threshold for the ClickHouse® storage capacity, in percent, to trigger an immediate increase. The default value is `0` (auto increase disabled).
         
           The valid values range from `0` to `100`.
         
         * `zookeeper-disk-size-limit`: Maximum ZooKeeper storage size, in GB.
         
         * `zookeeper-planned-usage-threshold`: ZooKeeper storage utilization threshold to trigger an increase during the next maintenance window, in percent. The default value is `0` (auto increase disabled).
         
           The valid values range from `0` to `100`.
         
         * `zookeeper-emergency-usage-threshold`: Utilization threshold for the ZooKeeper storage capacity, in percent, to trigger an immediate increase. The default value is `0` (auto increase disabled).
         
           The valid values range from `0` to `100`.
         
         {% note warning %}
         
         * If you specify both thresholds for ClickHouse®, `clickhouse-emergency-usage-threshold` must not be less than `clickhouse-planned-usage-threshold`.
         
         * If you specify both thresholds for ZooKeeper, `zookeeper-emergency-usage-threshold` must not be less than `zookeeper-planned-usage-threshold`.
         
         * When using `clickhouse-planned-usage-threshold` and `zookeeper-planned-usage-threshold`, make sure to set up a [maintenance window](../concepts/maintenance.md).
         
         {% endnote %}

         The automatic storage expansion settings specified for ClickHouse® apply to all shards. To use individual settings for a particular shard, provide the same parameters in the `--shard` flag.

         ```bash
         yc managed-clickhouse cluster create \
           ...
           --shard name=<shard_name>,`
                  `disk-size-limit=<maximum_storage_size_in_GB>,`
                  `planned-usage-threshold=<scheduled_expansion_threshold_in_percent>,`
                  `emergency-usage-threshold=<immediate_expansion_threshold_in_percent>
           ...
         ```

      1. To set a [maintenance window](../concepts/maintenance.md), use the `--maintenance-window` flag:

         ```bash
         yc managed-clickhouse cluster create \
           ...
           --maintenance-window type=<maintenance_type>,`
                               `hour=<hour>,`
                               `day=<day_of_week>
           ...
         ```

         Where `--maintenance-window` defines the maintenance window settings:

         * `type`: Maintenance window type. Valid values:

           * `anytime`: Any time (default).
           * `weekly`: On schedule. To use this value, you need to provide `hour` and `day`.

         * `hour`: Time of day (UTC). The valid values range from `1` to `24`.
         * `day`: Day of week. The valid values are `MON`, `TUE`, `WED`, `THU`, `FRI`, `SAT`, and `SUN`.


- Terraform {#tf}

  With [Terraform](https://www.terraform.io/), you can quickly create a cloud infrastructure in Yandex Cloud and manage it using configuration files. These files store the infrastructure description written in HashiCorp Configuration Language (HCL). If you change the configuration files, Terraform automatically detects which part of your configuration is already deployed, and what should be added or removed.
  
  Terraform is distributed under the [Business Source License](https://github.com/hashicorp/terraform/blob/main/LICENSE). The [Yandex Cloud provider for Terraform](https://github.com/yandex-cloud/terraform-provider-yandex) is distributed under the [MPL-2.0](https://www.mozilla.org/en-US/MPL/2.0/) license.
  
  For more information about the provider resources, see the guides on the [Terraform](https://www.terraform.io/docs/providers/yandex/index.html) website or [its mirror](../../terraform/index.md).

  To create a Managed Service for ClickHouse® cluster with the ZooKeeper coordination service:

    1. In the command line, navigate to the directory that will contain the Terraform configuration files describing your infrastructure. If there is no such directory, create one.

    1. 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. Create a configuration file describing the [cloud network](../../vpc/concepts/network.md#network) and [subnets](../../vpc/concepts/network.md#subnet).
        * Network: Description of the [cloud network](../../vpc/concepts/network.md#network) to host the cluster. If you already have a network in place, you do not need to describe it again.
        * Subnets: Description of the [subnets](../../vpc/concepts/network.md#network) to connect the cluster hosts to. If you already have suitable subnets, you do not need to describe them again.

       Below is an example of a configuration file describing a single-subnet cloud network:

       ```hcl
       resource "yandex_vpc_network" "<network_name_in_Terraform>" {
         name = "<network_name>"
       }

       resource "yandex_vpc_subnet" "<subnet_name_in_Terraform>" {
         name           = "<subnet_name>"
         zone           = "<availability_zone>"
         network_id     = yandex_vpc_network.<network_name_in_Terraform>.id
         v4_cidr_blocks = ["<subnet>"]
       }
       ```

    1. Create a configuration file describing the cluster resources to create:

       * Database cluster: Description of the cluster and its hosts. Optionally, here:
          * Specify the [DBMS server-level settings](../concepts/settings-list.md#server-level-settings). You can also provide them later.
          * Enable cluster protection against accidental deletion.

             Even with cluster deletion protection enabled, one can still delete a user or database or connect manually and delete the database contents.

       * Database: Cluster database description.
       * User: Cluster user description. Optionally, specify the [DBMS user-level settings](../concepts/settings-list.md#dbms-user-settings) here. You can also provide them later.

          Using the Yandex Cloud interfaces, you can manage a limited number of settings. Using SQL queries, you can [specify the ClickHouse® settings at the query level](change-query-level-settings.md).

       Below is an example structure of a configuration file describing a cluster of two ClickHouse® hosts and three ZooKeeper hosts:

       ```hcl
       resource "yandex_mdb_clickhouse_cluster_v2" "<cluster_name>" {
         name                = "<cluster_name>"
         environment         = "<environment>"
         network_id          = yandex_vpc_network.<network_name_in_Terraform>.id
         security_group_ids  = ["<list_of_security_group_IDs>"]
         deletion_protection = <cluster_deletion_protection>

         clickhouse = {
           resources = {
             resource_preset_id = "<host_class>"
             disk_type_id       = "<disk_type>"
             disk_size          = <storage_size_in_GB>
           }
         }

         zookeeper = {
           resources = {
             resource_preset_id = "<host_class>"
             disk_type_id       = "<disk_type>"
             disk_size          = <storage_size_in_GB>
           }
         }

         shards = {
           "<shard_name>" = {
             weight = <shard_weight>
           }
         }

         hosts = {
           "<host_1_name>" = {
             type             = "CLICKHOUSE"
             zone             = "<availability_zone>"
             subnet_id        = yandex_vpc_subnet.<subnet_name_in_Terraform>.id
             assign_public_ip = <public_access_to_host>
             shard_name       = "<shard_name>"
           }

           "<host_2_name>" = {
             type             = "CLICKHOUSE"
             zone             = "<availability_zone>"
             subnet_id        = yandex_vpc_subnet.<subnet_name_in_Terraform>.id
             assign_public_ip = <public_access_to_host>
             shard_name       = "<shard_name>"
           }

           "<host_3_name>" = {
             type             = "ZOOKEEPER"
             zone             = "<availability_zone>"
             subnet_id        = yandex_vpc_subnet.<subnet_name_in_Terraform>.id
           }

           "<host_4_name>" = {
             type             = "ZOOKEEPER"
             zone             = "<availability_zone>"
             subnet_id        = yandex_vpc_subnet.<subnet_name_in_Terraform>.id
           }

           "<host_5_name>" = {
             type             = "ZOOKEEPER"
             zone             = "<availability_zone>"
             subnet_id        = yandex_vpc_subnet.<subnet_name_in_Terraform>.id
           }
         }
       }

       resource "yandex_mdb_clickhouse_database" "<DB_name>" {
         cluster_id = yandex_mdb_clickhouse_cluster_v2.<cluster_name>.id
         name       = "<DB_name>"
       }

       resource "yandex_mdb_clickhouse_user" "<username>" {
         cluster_id = yandex_mdb_clickhouse_cluster_v2.<cluster_name>.id
         name       = "<username>"
         password   = "<user_password>"
         permission {
           database_name = yandex_mdb_clickhouse_database.<DB_name>.name
         }
         settings {
           <parameter_1_name> = <value_1>
           <parameter_2_name> = <value_2>
           ...
         }
       }
       ```

       Where:

       * `deletion_protection`: Cluster deletion protection, `true` or `false`.

       * `shards`: Cluster [shards](../concepts/sharding.md) as an associative array of elements. The key specifies the shard name, and the value includes the `weight` parameter, i.e., the shard weight.

       * `hosts`: Cluster hosts as an associative array of elements. The key specifies the host name, and the value, the host parameters. Each element in the array has the following structure:

          * `type`: Host type, `CLICKHOUSE` or `ZOOKEEPER`.
          * `zone`: [Availability zone](../../overview/concepts/geo-scope.md).
          * `subnet_id`: [Subnet ID](../../vpc/concepts/network.md#subnet).
          * `assign_public_ip`: Public access to the ClickHouse® host, `true` or `false`. This setting is only relevant for `CLICKHOUSE` hosts.

            {% note warning %}
            
            For a more secure cluster with public host access enabled, use only trusted IP addresses or subnets in the cluster's security group rules. Learn more in [Configuring security groups](connect/index.md#configuring-security-groups).
            
            {% endnote %}

          * `shard_name`: Shard name. This setting is only relevant for `CLICKHOUSE` hosts.

          If you create a cluster of two or more ClickHouse® hosts without the coordination service and the cluster [network](../../vpc/concepts/network.md) has [subnets](../../vpc/concepts/network.md#subnet) in each [availability zone](../../overview/concepts/geo-scope.md), the system automatically adds three ZooKeeper hosts one in each subnet.
          
          If subnets are located only in some availability zones, or you want to use a different coordination service, manually specify the coordination service and its host settings.

       For a user, specify the following:

       * `name` and `password`: ClickHouse® username and password, respectively.

          The username may contain Latin letters, numbers, hyphens, and underscores but must begin with a letter or underscore. The name may be up to 32 characters long.

          It must be from 8 to 128 characters long.

          
          {% note info %}

          You can also generate a password using Connection Manager. To do this, specify `generate_password = true` instead of `"password" = "<user_password>"`.

          To view the password, select your cluster in the [management console](https://console.yandex.cloud), navigate to the **Users** tab, and click **View password** for the relevant user. This will open the page of the Yandex Lockbox secret containing the password. To view passwords, you need the `lockbox.payloadViewer` role.

          {% endnote %}


       * `permission`: List of databases the user should have access to.

       1. To set up the [maintenance window](../concepts/maintenance.md) that will also apply to stopped clusters, add the `maintenance_window` section to the cluster description:
          
          ```hcl
          resource "yandex_mdb_clickhouse_cluster_v2" "<cluster_name>" {
            ...
            maintenance_window {
              type = "<maintenance_type>"
              day  = "<day_of_week>"
              hour = <hour>
            }
            ...
          }
          ```
          
          Where:
          
          * `type`: Maintenance type. The possible values include:
              * `ANYTIME`: Any time.
              * `WEEKLY`: On a schedule.
          * `day`: Day of week for the `WEEKLY` type, i.e., `MON`, `TUE`, `WED`, `THU`, `FRI`, `SAT`, or `SUN`.
          * `hour`: Sequence number of UTC hour interval for the `WEEKLY` type, from `1` to `24`.
          
            > For example, `1` stands for the interval from `00:00` to `01:00`, and `5`, from `04:00` to `05:00`.

       1. To enable access from other services and allow [running SQL queries from the management console](web-sql-query.md) using Yandex WebSQL, add the `access` section with the settings you need:

          ```hcl
          resource "yandex_mdb_clickhouse_cluster_v2" "<cluster_name>" {
            ...
            access = {
              data_lens    = <access_from_DataLens>
              metrika      = <access_from_Metrica_and_AppMetrica>
              serverless   = <access_from_Cloud_Functions>
              yandex_query = <access_from_Yandex_Query>
              web_sql      = <run_SQL_queries_from_management_console>
            }
            ...
          }
          ```

          Where:

          * `data_lens`: Access from DataLens, `true` or `false`.
          * `metrika`: Access from Yandex Metrica and AppMetrica, `true` or `false`.
          * `serverless`: Access from Cloud Functions, `true` or `false`.
          * `yandex_query`: Access from Yandex Query, `true` or `false`.
          * `web_sql`: Running SQL queries from the management console, `true` or `false`.

       1. You can manage cluster users and databases via SQL.

          {% note warning %}
          
          You cannot disable settings for user or database management via SQL once they are enabled. You can enable them as required later when [reconfiguring your cluster](update.md#SQL-management).
          
          {% endnote %}

          * To enable [user management via SQL](../concepts/user-access-rights.md#sql-user-management), add the `sql_user_management` field set to `true` and the `admin_password` field with the `admin` user's password to the cluster description:
            
            ```hcl
            resource "yandex_mdb_clickhouse_cluster_v2" "<cluster_name>" {
              name                = "<cluster_name>"
              ...
              admin_password      = "<admin_user_password>"
              sql_user_management = true
              ...
            }
            ```

          * To enable [database management via SQL](databases.md#sql-database-management), add to the cluster description the `sql_user_management` and `sql_database_management` fields set to `true` and the `admin_password` field with the `admin` user password:
            
            ```hcl
            resource "yandex_mdb_clickhouse_cluster_v2" "<cluster_name>" {
              name                    = "<cluster_name>"
              ...
              admin_password          = "<admin_user_password>"
              sql_database_management = true
              sql_user_management     = true
              ...
            }
            ```

       1. To encrypt the disk with a [custom KMS key](../../kms/concepts/key.md), add the `disk_encryption_key_id` parameter:

          ```hcl
          resource "yandex_mdb_clickhouse_cluster_v2" "<cluster_name>" {
            ...
            disk_encryption_key_id = <KMS_key_ID>
            ...
          }
          ```

          To learn more about disk encryption, see [Storage](../concepts/storage.md#disk-encryption).

       For more information about the resources you can create with Terraform, see [this provider guide](../../terraform/resources/mdb_clickhouse_cluster.md).

    1. Make sure the Terraform configuration files are correct:

       1. In the command line, navigate to the directory that contains the current Terraform configuration files defining the infrastructure.
       1. Run this command:
       
          ```bash
          terraform validate
          ```
       
          Terraform will show any errors found in your configuration files.

    1. Create a cluster:

       1. Run this command to view the planned changes:
       
          ```bash
          terraform plan
          ```
       
          If you described the configuration correctly, the terminal will display a list of the resources to update and their parameters. This is a verification step that does not apply changes to your resources.
       
       1. If everything looks correct, apply the changes:
          1. Run this command:
       
             ```bash
             terraform apply
             ```
       
          1. Confirm updating the resources.
          1. Wait for the operation to complete.

       All the required resources will be created in the specified folder. You can check resource availability and their settings in the [management console](https://console.yandex.cloud).

    {% note warning "Timeouts" %}
    
    The Terraform provider sets the following timeouts for Managed Service for ClickHouse® cluster operations:
    
    * Creating a cluster, including by restoring from a backup: 60 minutes.
    * Updating a cluster: 90 minutes.
    * Deleting a cluster: 30 minutes.
    
    Operations exceeding the timeout are aborted.
    
    {% cut "How to change these limits" %}
    
    Add the `timeouts` section to your cluster description, such as the following:
    
    ```hcl
    resource "yandex_mdb_clickhouse_cluster_v2" "<cluster_name>" {
      ...
      timeouts = {
        create = "1h30m" # 1 hour 30 minutes
        update = "2h"    # 2 hours
        delete = "30m"   # 30 minutes
      }
    }
    ```
    
    {% endcut %}
    
    {% endnote %}


- REST API {#api}

    To create a Managed Service for ClickHouse® cluster with the ZooKeeper coordination service:

    1. [Get an IAM token for API authentication](../api-ref/authentication.md) and put it into an environment variable:

        ```bash
        export IAM_TOKEN="<IAM_token>"
        ```

    1. Call the [Cluster.Create](../api-ref/Cluster/create.md) method, e.g., via the following [cURL](https://curl.se/) request:

        1. Create a file named `body.json` and paste the following code into it (the example does not show all the available properties):

            
            ```json
            {
              "folderId": "<folder_ID>",
              "name": "<cluster_name>",
              "environment": "<environment>",
              "networkId": "<network_ID>",
              "securityGroupIds": [
                "<security_group_1_ID>",
                "<security_group_2_ID>",
                ...
                "<security_group_N_ID>"
              ],
              "configSpec": {
                "version": "<ClickHouse®_version>",
                "clickhouse": {
                  "resources": {
                    "resourcePresetId": "<host_class>",
                    "diskSize": "<storage_size_in_bytes>",
                    "diskTypeId": "<disk_type>"
                  },
                  "diskSizeAutoscaling": {
                    "plannedUsageThreshold": "<scheduled_expansion_threshold_in_percent>",
                    "emergencyUsageThreshold": "<immediate_expansion_threshold_in_percent>",
                    "diskSizeLimit": "<maximum_storage_size_in_bytes>"
                  }
                },
                "zookeeper": {
                  "resources": {
                    "resourcePresetId": "<host_class>",
                    "diskSize": "<storage_size_in_bytes>",
                    "diskTypeId": "<disk_type>"
                  },
                  "diskSizeAutoscaling": {
                    "plannedUsageThreshold": "<scheduled_expansion_threshold_in_percent>",
                    "emergencyUsageThreshold": "<immediate_expansion_threshold_in_percent>",
                    "diskSizeLimit": "<maximum_storage_size_in_bytes>"
                  }
                },
                "access": {
                  "dataLens": <access_from_DataLens>,
                  "webSql": <run_SQL_queries_from_management_console>,
                  "metrika": <access_from_Metrica_and_AppMetrica>,
                  "serverless": <access_from_Cloud_Functions>,
                  "dataTransfer": <access_from_Data_Transfer>,
                  "yandexQuery": <access_from_Yandex_Query>
                },
                "cloudStorage": {
                  "enabled": <hybrid_storage_use>,
                  "moveFactor": "<share_of_free_space>",
                  "dataCacheEnabled": <temporary_file_storage>,
                  "dataCacheMaxSize": "<maximum_memory_for_file_storage>",
                  "preferNotToMerge": <disabling_data_part_merging>
                },
                "adminPassword": "<admin_user_password>",
                "sqlUserManagement": <user_management_via_SQL>,
                "sqlDatabaseManagement": <database_management_via_SQL>
              },
              "databaseSpecs": [
                {
                  "name": "<DB_name>",
                  "engine": "<database_engine>"
                },
                { <similar_settings_for_database_2> },
                { ... },
                { <similar_settings_for_database_N> }
              ],
              "userSpecs": [
                {
                  "name": "<username>",
                  "password": "<user_password>",
                  "permissions": [
                    {
                      "databaseName": "<DB_name>"
                    }
                  ]
                },
                { <similar_settings_for_user_2> },
                { ... },
                { <similar_settings_for_user_N> }
              ],
              "hostSpecs": [
                {
                  "zoneId": "<availability_zone>",
                  "type": "<host_type>",
                  "subnetId": "<subnet_ID>",
                  "assignPublicIp": <public_access_to_host>,
                  "shardName": "<shard_name>"
                },
                { <similar_settings_for_host_2> },
                { ... },
                { <similar_settings_for_host_N> }
              ],
              "shardSpecs": [
                {
                  "name": "<shard_name>",
                  "configSpec": {
                    "clickhouse": {
                      "weight": "<shard_weight>", 
                      "resources": {
                        "resourcePresetId": "<host_class_in_shard>",
                        "diskSize": "<storage_size_in_bytes>",
                        "diskTypeId": "<disk_type>"
                      },
                      "diskSizeAutoscaling": {
                        "plannedUsageThreshold": "<scheduled_expansion_threshold_in_percent>",
                        "emergencyUsageThreshold": "<immediate_expansion_threshold_in_percent>",
                        "diskSizeLimit": "<maximum_storage_size_in_bytes>"
                      },
                      "config": {
                        <DBMS_settings>
                      }
                    }
                  }
                },
                { <similar_set_of_settings_for_shard_2> },
                { ... },
                { <similar_set_of_settings_for_shard_N> }
              ],
              "deletionProtection": <cluster_deletion_protection>,
              "maintenanceWindow": {
                "weeklyMaintenanceWindow": {
                  "day": "<day_of_week>",
                  "hour": "<hour>"
                }
              }
            }
            ```


            Where:

            * `name`: Cluster name.
            * `environment`: Cluster environment, `PRODUCTION` or `PRESTABLE`.
            * `networkId`: ID of the [network](../../vpc/concepts/network.md) where the cluster will be deployed.

            
            * `securityGroupIds`: [Security group](../../vpc/concepts/security-groups.md) IDs as an array of strings. Each string is a security group ID.

                {% note warning %}
                
                If you specified security group IDs when creating a cluster, you may need to [configure these security groups](connect/index.md#configuring-security-groups) to enable cluster access.
                
                {% endnote %}


            * `configSpec`: Cluster configuration:

                * `version`: ClickHouse® version, 25.8.24.21 LTS, 26.3.12.3 LTS, 26.4.4.38 and 26.5.2.39.
                * `clickhouse`: ClickHouse® configuration:

                    * `resources.resourcePresetId`: [Host class](../concepts/instance-types.md) ID. You can get the list of available host classes with their IDs by calling the [ResourcePreset.list](../api-ref/ResourcePreset/list.md) method.
                    * `resources.diskSize`: Disk size, in bytes.
                    * `resources.diskTypeId`: [Disk type](../concepts/storage.md).

                    * `diskSizeAutoscaling`: Automatic storage expansion settings for ClickHouse®:

                      * `plannedUsageThreshold`: Utilization threshold for the ClickHouse® storage capacity, in percent, to trigger an increase during the next maintenance window. The default value is `0` (auto increase disabled).
                      
                        The valid values range from `0` to `100`.
                      
                      * `emergencyUsageThreshold`: Utilization threshold for the ClickHouse® storage capacity, in percent, to trigger an immediate increase. The default value is `0` (auto increase disabled).
                      
                        The valid values range from `0` to `100`.
                      
                      * `diskSizeLimit`: Maximum ClickHouse® storage size, in bytes.
                      
                      {% note warning %}
                      
                      * If you specify both thresholds, `emergencyUsageThreshold` must not be less than `plannedUsageThreshold`.
                      
                      * When using `plannedUsageThreshold`, make sure to set up a [maintenance window](../concepts/maintenance.md).
                      
                      {% endnote %}
                      
                      The automatic storage expansion settings for ClickHouse® apply to all existing shards. If you add a new shard, it will use the settings of the oldest shard. These values are not saved in the ClickHouse® configuration.
                      
                      To view information about a specific shard, including automatic storage size increase settings, use the [Cluster.GetShard](../api-ref/Cluster/getShard.md) method and provide the cluster ID and shard name in the request.
                      
                      You can get the cluster ID with the [list of clusters](cluster-list.md#list-clusters) in the folder.
                      
                      You can get the shard name with the [list of shards](shards.md#list-shards) in the cluster.

                * `zookeeper`: [ZooKeeper](../concepts/coordination-system.md#zk) configuration:

                    * `resources.resourcePresetId`: Host class ID. You can get the list of available host classes with their IDs using the [ResourcePreset.list](../api-ref/ResourcePreset/list.md) method.
                    * `resources.diskSize`: Disk size, in bytes.
                    * `resources.diskTypeId`: [Disk type](../concepts/storage.md).

                    * `diskSizeAutoscaling`: Automatic storage expansion settings for ZooKeeper:

                      * `plannedUsageThreshold`: Utilization threshold for the ZooKeeper storage capacity, in percent, to trigger an increase during the next maintenance window. The default value is `0` (auto increase disabled).
                                            
                        The valid values range from `0` to `100`.
                                            
                      * `emergencyUsageThreshold`: Utilization threshold for the ZooKeeper storage capacity, in percent, to trigger an immediate increase. The default value is `0` (auto increase disabled).
                                            
                        The valid values range from `0` to `100`.
                                            
                      * `diskSizeLimit`: Maximum ZooKeeper storage size, in bytes.
                                            
                      {% note warning %}
                                            
                      * If you specify both thresholds, `emergencyUsageThreshold` must not be less than `plannedUsageThreshold`.
                                            
                      * When using `plannedUsageThreshold`, make sure to set up a [maintenance window](../concepts/maintenance.md).
                                            
                      {% endnote %}

                * `access`: Settings enabling cluster access from other services and [running SQL queries from the management console](web-sql-query.md) using Yandex WebSQL:

                    * `dataLens`: Enable access from DataLens, `true` or `false`. The default value is `false`. For more information about setting up a connection, see [Connecting from DataLens](datalens-connect.md).
                    
                    * `webSql`: Enable [SQL queries](web-sql-query.md) against cluster databases from the Yandex Cloud management console using Yandex WebSQL, `true` or `false`. The default value is `false`.
                    
                    
                    * `metrika`: Enable [data import from AppMetrica to your cluster](https://appmetrica.yandex.com/docs/common/cloud/about.html), `true` or `false`. The default value is `false`.
                    
                    * `serverless`: Enable access to the cluster from [Yandex Cloud Functions](../../functions/concepts/index.md), `true` or `false`. The default value is `false`. Learn more about access setup in [this Cloud Functions guide](../../functions/operations/database-connection.md).
                    
                    * `dataTransfer`: Enable access to the cluster from [Yandex Data Transfer](../../data-transfer/concepts/index.md) in Serverless mode, `true` or `false`. The default value is `false`.
                    
                        This will enable you to connect to Yandex Data Transfer running in Kubernetes via a special network to make other operations, e.g., transfer launch and deactivation, run faster.
                    
                    
                    * `yandexQuery`: Enable access to the cluster from [Yandex Query](../../query/concepts/index.md), `true` or `false`. This feature is at the [Preview](../../overview/concepts/launch-stages.md) stage. The default value is `false`.

                * `cloudStorage`: [Hybrid storage](../concepts/storage.md#hybrid-storage-features) settings:

                    * `enabled`: Enable hybrid storage in the cluster if it is disabled, `true` or `false`. The default value is `false` (disabled).
                    
                        {% note info %}
                        
                        Once hybrid storage is enabled, you cannot disable it.
                        
                        {% endnote %}
                    
                    * `moveFactor`: Minimum percentage of free space in the cluster storage. If your free space percentage is below this value, the data will be moved to Yandex Object Storage.
                    
                        The minimum value is `0`, the maximum value is `1`, and the default value is `0.01`.
                    
                    * `dataCacheEnabled`: Enable caching files in the cluster storage, `true` or `false`.
                    
                        The default value is `true` (enabled).
                    
                    * `dataCacheMaxSize`: Maximum cache size, in bytes, allocated in the cluster storage.
                        
                        If no value is set, the maximum cache size defaults to half the size of the cluster storage.
                    
                    * `preferNotToMerge`: Disable [merging of data parts](https://clickhouse.com/docs/enen/engines/table-engines/mergetree-family/custom-partitioning-key) in the cluster and object storage, `true` or `false`.
                    
                        To disable merging, set to `true`. To leave merging enabled, set to `false`.

                * `sql...` and `adminPassword`: Group of settings for user and database management via SQL:

                    * `adminPassword`: `admin` password.
                    * `sqlUserManagement`: [User management via SQL](cluster-users.md#sql-user-management), `true` or `false`.
                    * `sqlDatabaseManagement`: [Database management via SQL](databases.md#sql-database-management), `true` or `false`. For that, you also need to enable user management via SQL.


                    {% note warning %}
                    
                    You cannot disable settings for user or database management via SQL once they are enabled. You can enable them as required later when [reconfiguring your cluster](update.md#SQL-management).
                    
                    {% endnote %}

            * `databaseSpecs`: Database settings as an array of elements, one per database. Each element has the following structure:

                * `name`: Database name.
                * `engine`: Database engine. The possible values are:

                  * `DATABASE_ENGINE_ATOMIC` (default): `Atomic` engine; supports non-blocking `DROP TABLE` and `RENAME TABLE` queries, and atomic `EXCHANGE TABLES` queries.
                  * `DATABASE_ENGINE_REPLICATED`: `Replicated` engine; supports table metadata replication across all database replicas. The set of tables and their schemas will be the same for all replicas.
                                      
                    It is only available in [replicated](../concepts/replication.md) clusters.
                  
                  * `DATABASE_ENGINE_UNSPECIFIED`: This value will set the default engine, i.e., `DATABASE_ENGINE_ATOMIC`.
                                      
                  You can only set the engine when creating a database and cannot change it later.

            * `userSpecs`: User settings as an array of elements, one per user. Each element has the following structure:

                * `name`: Username. It may contain Latin letters, numbers, hyphens, and underscores, and must start with a letter or underscore. The name may be up to 32 characters long.
                * `password`: User password. The password must be from 8 to 128 characters long.
                
                    
                    You can also generate a password using Connection Manager. To do this, specify `"generatePassword": true` instead of `"password": "<user_password>"`.
                
                    To view the password, select your cluster in the [management console](https://console.yandex.cloud), navigate to the **Users** tab, and click **View password** for the relevant user. This will open the page of the Yandex Lockbox secret containing the password. To view passwords, you need the `lockbox.payloadViewer` role.
                
                
                * `permissions`: List of databases the user should have access to.
                
                    The list appears as an array of `databaseName` parameters. Each parameter contains the name of a separate database.

            * `hostSpecs`: Cluster host settings as an array of elements, one per host. Each element has the following structure:

                * `type`: Host type, `CLICKHOUSE` or `ZOOKEEPER`.
                * `zoneId`: [Availability zone](../../overview/concepts/geo-scope.md).

                
                * `subnetId`: [Subnet](../../vpc/concepts/network.md#subnet) ID.


                * `shardName`: [Shard](../concepts/sharding.md) name. This setting is only relevant for `CLICKHOUSE` hosts.

                
                * `assignPublicIp`: Internet access to the host via a public IP address, `true` or `false`. This setting is only relevant for `CLICKHOUSE` hosts.

                   {% note warning %}
                   
                   For a more secure cluster with public host access enabled, use only trusted IP addresses or subnets in the cluster's security group rules. Learn more in [Configuring security groups](connect/index.md#configuring-security-groups).
                   
                   {% endnote %}

                If you create a cluster of two or more ClickHouse® hosts without the coordination service and the cluster [network](../../vpc/concepts/network.md) has [subnets](../../vpc/concepts/network.md#subnet) in each [availability zone](../../overview/concepts/geo-scope.md), the system automatically adds three ZooKeeper hosts one in each subnet.
                
                If subnets are located only in some availability zones, or you want to use a different coordination service, manually specify the coordination service and its host settings.


            * `shardSpecs`: Shard settings as an array of elements, one per shard. If you skip this section in the request, the new cluster will have a single shard named `shard1`. You can specify the following settings:

                * `name`: Shard name.
                * `weight`: Shard weight.
                * `configSpec.clickhouse`: Shard host configuration, i.e., including host class, storage settings, and DBMS settings. If you skip the shard host configuration, it will be inherited from the cluster configuration.

            * `deletionProtection`: Cluster deletion protection, `true` or `false`. The default value is `false`.

                Even with cluster deletion protection enabled, one can still delete a user or database or connect manually and delete the database contents.

            * `maintenanceWindow`: Maintenance window settings:

                * `weeklyMaintenanceWindow.day`: Day of week. The valid values are `MON`, `TUE`, `WED`, `THU`, `FRI`, `SAT`, and `SUN`.
                * `weeklyMaintenanceWindow.hour`: Time of day (UTC). The valid values range from `1` to `24`.

            
            You can get the folder ID with the [list of folders in the cloud](../../resource-manager/operations/folder/get-id.md).


        1. Run this request:

            ```bash
            curl \
              --request POST \
              --header "Authorization: Bearer $IAM_TOKEN" \
              --header "Content-Type: application/json" \
              --url 'https://mdb.api.cloud.yandex.net/managed-clickhouse/v1/clusters' \
              --data '@body.json'
            ```

    1. View the [server response](../api-ref/Cluster/create.md#responses) to make sure your request was successful.

- gRPC API {#grpc-api}

    To create a Managed Service for ClickHouse® cluster with the ZooKeeper coordination service:

    1. [Get an IAM token for API authentication](../api-ref/authentication.md) and put it into an environment variable:

        ```bash
        export IAM_TOKEN="<IAM_token>"
        ```

    1. Clone the [cloudapi](https://github.com/yandex-cloud/cloudapi) repository:
       
       ```bash
       cd ~/ && git clone --depth=1 https://github.com/yandex-cloud/cloudapi
       ```
       
       Below, we assume that the repository contents reside in the `~/cloudapi/` directory.

    1. Call the [ClusterService.Create](../api-ref/grpc/Cluster/create.md) method, e.g., via the following [gRPCurl](https://github.com/fullstorydev/grpcurl) request:

        1. Create a file named `body.json` and paste the following code into it (the example does not show all the available properties):

            
            ```json
            {
              "folder_id": "<folder_ID>",
              "name": "<cluster_name>",
              "environment": "<environment>",
              "network_id": "<network_ID>",
              "security_group_ids": [
                "<security_group_1_ID>",
                "<security_group_2_ID>",
                ...
                "<security_group_N_ID>"
              ],
              "config_spec": {
                "version": "<ClickHouse®_version>",
                "clickhouse": {
                  "resources": {
                    "resource_preset_id": "<host_class>",
                    "disk_size": "<storage_size_in_bytes>",
                    "disk_type_id": "<disk_type>"
                  },
                  "disk_size_autoscaling": {
                    "planned_usage_threshold": "<scheduled_expansion_threshold_in_percent>",
                    "emergency_usage_threshold": "<immediate_expansion_threshold_in_percent>",
                    "disk_size_limit": "<maximum_storage_size_in_bytes>"
                  }
                },
                "zookeeper": {
                  "resources": {
                    "resource_preset_id": "<host_class>",
                    "disk_size": "<storage_size_in_bytes>",
                    "disk_type_id": "<disk_type>"
                  },
                  "disk_size_autoscaling": {
                    "planned_usage_threshold": "<scheduled_expansion_threshold_in_percent>",
                    "emergency_usage_threshold": "<immediate_expansion_threshold_in_percent>",
                    "disk_size_limit": "<maximum_storage_size_in_bytes>"
                  }
                },
                "access": {
                  "data_lens": <access_from_DataLens>,
                  "web_sql": <run_SQL_queries_from_management_console>,
                  "metrika": <access_from_Metrica_and_AppMetrica>,
                  "serverless": <access_from_Cloud_Functions>,
                  "data_transfer": <access_from_Data_Transfer>,
                  "yandex_query": <access_from_Yandex_Query>
                },
                "cloud_storage": {
                  "enabled": <hybrid_storage_use>,
                  "move_factor": "<share_of_free_space>",
                  "data_cache_enabled": <temporary_file_storage>,
                  "data_cache_max_size": "<maximum_memory_for_file_storage>",
                  "prefer_not_to_merge": <disabling_data_part_merging>
                },
                "admin_password": "<admin_user_password>",
                "sql_user_management": <user_management_via_SQL>,
                "sql_database_management": <database_management_via_SQL>
              },
              "database_specs": [
                {
                  "name": "<DB_name>",
                  "engine": "<database_engine>"
                },
                { <similar_settings_for_database_2> },
                { ... },
                { <similar_settings_for_database_N> }
              ],
              "user_specs": [
                {
                  "name": "<username>",
                  "password": "<user_password>",
                  "permissions": [
                    {
                      "database_name": "<DB_name>"
                    }
                  ]
                },
                { <similar_settings_for_user_2> },
                { ... },
                { <similar_settings_for_user_N> }
              ],
              "host_specs": [
                {
                  "zone_id": "<availability_zone>",
                  "type": "<host_type>",
                  "subnet_id": "<subnet_ID>",
                  "assign_public_ip": <public_access_to_host>,
                  "shard_name": "<shard_name>"
                },
                { <similar_settings_for_host_2> },
                { ... },
                { <similar_settings_for_host_N> }
              ],
              "shard_specs": [
                {
                  "name": "<shard_name>",
                  "config_spec": {
                    "clickhouse": {
                      "weight": "<shard_weight>",
                      "resources": {
                        "resource_preset_id": "<host_class>",
                        "disk_size": "<storage_size_in_bytes>",
                        "disk_type_id": "<disk_type>"
                      },
                      "disk_size_autoscaling": {
                        "planned_usage_threshold": "<scheduled_expansion_threshold_in_percent>",
                        "emergency_usage_threshold": "<immediate_expansion_threshold_in_percent>",
                        "disk_size_limit": "<maximum_storage_size_in_bytes>"
                      },
                      "config": {
                        <DBMS_settings>
                      }
                    }
                  }
                },
                { <similar_set_of_settings_for_shard_2> },
                { ... },
                { <similar_set_of_settings_for_shard_N> }
              ],
              "deletion_protection": <cluster_deletion_protection>,
              "maintenance_window": {
                "weekly_maintenance_window": {
                  "day": "<day_of_week>",
                  "hour": "<hour>"
                }
              }
            ```


            Where:

            * `name`: Cluster name.
            * `environment`: Cluster environment, `PRODUCTION` or `PRESTABLE`.

            * `network_id`: ID of the [network](../../vpc/concepts/network.md) where the cluster will be deployed.

            
            * `security_group_ids`: [Security group](../../vpc/concepts/security-groups.md) IDs as an array of strings. Each string is a security group ID.

                {% note warning %}
                
                If you specified security group IDs when creating a cluster, you may need to [configure these security groups](connect/index.md#configuring-security-groups) to enable cluster access.
                
                {% endnote %}


            * `config_spec`: Cluster configuration:

                * `version`: ClickHouse® version, 25.8.24.21 LTS, 26.3.12.3 LTS, 26.4.4.38 and 26.5.2.39.

                * `clickhouse`: ClickHouse® configuration:

                    * `resources.resource_preset_id`: [Host class](../concepts/instance-types.md) ID. You can get the list of available host classes with their IDs using the [ResourcePreset.list](../api-ref/ResourcePreset/list.md) method.
                    * `resources.disk_size`: Disk size, in bytes.
                    * `resources.disk_type_id`: [Disk type](../concepts/storage.md).

                    * `disk_size_autoscaling`: Automatic storage expansion settings for ClickHouse®:

                        * `planned_usage_threshold`: Utilization threshold for the ClickHouse® storage capacity, in percent, to trigger an expansion during the next maintenance window. The default value is `0` (auto increasing disabled).
                                              
                          The valid values range from `0` to `100`.
                                              
                        * `emergency_usage_threshold`: Utilization threshold for the ClickHouse® storage capacity, in percent, to trigger an immediate expansion. The default value is `0` (auto increasing disabled).
                                              
                          The valid values range from `0` to `100`.
                                              
                        * `disk_size_limit`: Maximum ClickHouse® storage size, in bytes.
                                              
                        {% note warning %}
                                              
                        * If you specify both thresholds, `emergency_usage_threshold` must not be less than `planned_usage_threshold`.
                                              
                        * When using `planned_usage_threshold`, make sure to set up a [maintenance window](../concepts/maintenance.md).
                                              
                        {% endnote %}
                                              
                        The automatic storage size increase settings for ClickHouse® apply to all existing shards. If you add a new shard, it will use the settings of the oldest shard. These values are not saved in the ClickHouse® configuration.
                                              
                        To view information about a specific shard, including automatic storage expansion settings, use the [ClusterService.GetShard](../api-ref/grpc/Cluster/getShard.md) method and provide the cluster ID and shard name in the request.
                                              
                        You can get the cluster ID with the [list of clusters](cluster-list.md#list-clusters) in the folder.
                        
                        You can get the shard name with the [list of shards](shards.md#list-shards) in the cluster.

                * `zookeeper`: [ZooKeeper](../concepts/coordination-system.md#zk) configuration:

                    * `resources.resource_preset_id`: Host class ID. You can get the list of available host classes with their IDs using the [ResourcePreset.list](../api-ref/ResourcePreset/list.md) method.
                    * `resources.disk_size`: Disk size, in bytes.
                    * `resources.disk_type_id`: [Disk type](../concepts/storage.md).

                    * `disk_size_autoscaling`: Automatic storage expansion settings for ZooKeeper:

                        * `planned_usage_threshold`: Utilization threshold for the ZooKeeper storage capacity, in percent, to trigger an increase during the next maintenance window. The default value is `0` (auto increase disabled).
                                              
                          The valid values range from `0` to `100`.
                                              
                        * `emergency_usage_threshold`: Utilization threshold for the ZooKeeper storage capacity, in percent, to trigger an immediate increase. The default value is `0` (auto increase disabled).
                                              
                          The valid values range from `0` to `100`.
                                              
                        * `disk_size_limit`: Maximum ZooKeeper storage size, in bytes.
                                              
                        {% note warning %}
                                              
                        * If you specify both thresholds, `emergency_usage_threshold` must not be less than `planned_usage_threshold`.
                                              
                        * When using `planned_usage_threshold`, make sure to set up a [maintenance window](../concepts/maintenance.md).
                                              
                        {% endnote %}

                * `access`: Settings enabling cluster access from other services and [running SQL queries from the management console](web-sql-query.md) using Yandex WebSQL:

                    * `data_lens`: Enable access from DataLens, `true` or `false`. The default value is `false`. For more information about setting up a connection, see [Connecting from DataLens](datalens-connect.md).
                    
                    * `web_sql`: Enable [SQL queries](web-sql-query.md) against cluster databases from the Yandex Cloud management console using Yandex WebSQL, `true` or `false`. The default value is `false`.
                    
                    
                    * `metrika`: Enable [data import from AppMetrica to your cluster](https://appmetrica.yandex.com/docs/common/cloud/about.html), `true` or `false`. The default value is `false`.
                    
                    * `serverless`: Enable access to the cluster from [Yandex Cloud Functions](../../functions/concepts/index.md), `true` or `false`. The default value is `false`. Learn more about access setup in [this Cloud Functions guide](../../functions/operations/database-connection.md).
                    
                    * `data_transfer`: Enable access to the cluster from [Yandex Data Transfer](../../data-transfer/concepts/index.md) in Serverless mode, `true` or `false`. The default value is `false`.
                    
                        This will enable you to connect to Yandex Data Transfer running in Kubernetes via a special network to make other operations, e.g., transfer launch and deactivation, run faster.
                    
                    
                    * `yandex_query`: Enable access to the cluster from [Yandex Query](../../query/concepts/index.md), `true` or `false`. This feature is at the [Preview](../../overview/concepts/launch-stages.md) stage. The default value is `false`.

                * `cloud_storage`: [Hybrid storage](../concepts/storage.md#hybrid-storage-features) settings:

                    * `enabled`: Enable hybrid storage in the cluster if it is disabled, `true` or `false`. The default value is `false` (disabled).
                    
                        {% note info %}
                        
                        Once hybrid storage is enabled, you cannot disable it.
                        
                        {% endnote %}
                    
                    * `move_factor`: Minimum percentage of free space in the cluster storage. If your free space percentage is below this value, the data will be moved to Yandex Object Storage.
                    
                        The minimum value is `0`, the maximum value is `1`, and the default value is `0.01`.
                    
                    * `data_cache_enabled`: Enable caching files in the cluster storage, `true` or `false`.
                    
                        The default value is `true` (enabled).
                    
                    * `data_cache_max_size`: Maximum cache size, in bytes, allocated in the cluster storage.
                    
                        If no value is set, the maximum cache size defaults to half the size of the cluster storage.
                    
                    * `prefer_not_to_merge`: Disable [merging of data parts](https://clickhouse.com/docs/enen/engines/table-engines/mergetree-family/custom-partitioning-key) in the cluster and object storage, `true` or `false`.
                    
                        To disable merging, set to `true`. To leave merging enabled, set to `false`.

                * `sql...` and `admin_password`: Group of settings for user and database management via SQL:

                    * `admin_password`: `admin` password.
                    * `sql_user_management`: [User management via SQL](cluster-users.md#sql-user-management), `true` or `false`.
                    * `sql_database_management`: [Database management via SQL](databases.md#sql-database-management), `true` or `false`. For that, you also need to enable user management via SQL.


                    {% note warning %}
                    
                    You cannot disable settings for user or database management via SQL once they are enabled. You can enable them as required later when [reconfiguring your cluster](update.md#SQL-management).
                    
                    {% endnote %}

            * `database_specs`: Database settings as an array of elements, one per database. Each element has the following structure:

                * `name`: Database name.
                * `engine`: Database engine. The possible values are:

                  * `DATABASE_ENGINE_ATOMIC` (default): `Atomic` engine; supports non-blocking `DROP TABLE` and `RENAME TABLE` queries, and atomic `EXCHANGE TABLES` queries.
                  * `DATABASE_ENGINE_REPLICATED`: `Replicated` engine; supports table metadata replication across all database replicas. The set of tables and their schemas will be the same for all replicas.
                                      
                    It is only available in [replicated](../concepts/replication.md) clusters.
                  
                  * `DATABASE_ENGINE_UNSPECIFIED`: This value will set the default engine, i.e., `DATABASE_ENGINE_ATOMIC`.
                                      
                  You can only set the engine when creating a database and cannot change it later.

            * `user_specs`: User settings as an array of elements, one per user. Each element has the following structure:

                * `name`: Username. It may contain Latin letters, numbers, hyphens, and underscores, and must start with a letter or underscore. The name may be up to 32 characters long.
                * `password`: User password. The password must be from 8 to 128 characters long.
                
                  
                  You can also generate a password using Connection Manager. To do this, specify `"generate_password": true` instead of `"password": "<user_password>"`.
                
                  To view the password, select your cluster in the [management console](https://console.yandex.cloud), navigate to the **Users** tab, and click **View password** for the relevant user. This will open the page of the Yandex Lockbox secret containing the password. To view passwords, you need the `lockbox.payloadViewer` role.
                
                
                * `permissions`: List of databases the user should have access to.
                
                    The list appears as an array of `database_name` parameters. Each parameter contains the name of a separate database.

            * `host_specs`: Cluster host settings as an array of elements, one per host. Each element has the following structure:

                * `type`: Host type, `CLICKHOUSE` or `ZOOKEEPER`.
                * `zone_id`: [Availability zone](../../overview/concepts/geo-scope.md).

                
                * `subnet_id`: [Subnet](../../vpc/concepts/network.md#subnet) ID.


                * `shard_name`: [Shard](../concepts/sharding.md) name. This setting is only relevant for `CLICKHOUSE` hosts.

                
                * `assign_public_ip`: Internet access to the host via a public IP address, `true` or `false`. This setting is only relevant for `CLICKHOUSE` hosts.

                   {% note warning %}
                   
                   For a more secure cluster with public host access enabled, use only trusted IP addresses or subnets in the cluster's security group rules. Learn more in [Configuring security groups](connect/index.md#configuring-security-groups).
                   
                   {% endnote %}

                If you create a cluster of two or more ClickHouse® hosts without the coordination service and the cluster [network](../../vpc/concepts/network.md) has [subnets](../../vpc/concepts/network.md#subnet) in each [availability zone](../../overview/concepts/geo-scope.md), the system automatically adds three ZooKeeper hosts one in each subnet.
                
                If subnets are located only in some availability zones, or you want to use a different coordination service, manually specify the coordination service and its host settings.


            * `shard_specs`: Shard settings as an array of elements, one per shard. If you skip this section in the request, the new cluster will have a single shard named `shard1`. You can specify the following settings:

                * `name`: Shard name.
                * `weight`: Shard weight.
                * `config_spec.clickhouse`: Shard host configuration, i.e., including host class, storage settings, and DBMS settings. If you skip the shard host configuration, it will be inherited from the cluster configuration.

            * `deletion_protection`: Cluster deletion protection, `true` or `false`. The default value is `false`.

                Even with cluster deletion protection enabled, one can still delete a user or database or connect manually and delete the database contents.

            * `maintenance_window`: Maintenance window settings:

              * `weekly_maintenance_window.day`: Day of week. The valid values are `MON`, `TUE`, `WED`, `THU`, `FRI`, `SAT`, and `SUN`.
              * `weekly_maintenance_window.hour`: Time of day (UTC). The valid values range from `1` to `24`.

            
            You can get the folder ID with the [list of folders in the cloud](../../resource-manager/operations/folder/get-id.md).


        1. Run this query:

            ```bash
            grpcurl \
              -format json \
              -import-path ~/cloudapi/ \
              -import-path ~/cloudapi/third_party/googleapis/ \
              -proto ~/cloudapi/yandex/cloud/mdb/clickhouse/v1/cluster_service.proto \
              -rpc-header "Authorization: Bearer $IAM_TOKEN" \
              -d @ \
              mdb.api.cloud.yandex.net:443 \
              yandex.cloud.mdb.clickhouse.v1.ClusterService.Create \
              < body.json
            ```

    1. View the [server response](../api-ref/grpc/Cluster/create.md#yandex.cloud.operation.Operation) to make sure your request was successful.

{% endlist %}


## Creating a cluster copy {#duplicate}

You can create a ClickHouse® cluster with the settings of another one created earlier. Do this by importing the original ClickHouse® cluster configuration into Terraform. This way, you can either create an identical copy or use the imported configuration as the baseline and modify it as needed. The import feature is handy when the original ClickHouse® cluster has a lot of settings and you need to create a similar one.

To create a ClickHouse® cluster copy:

{% list tabs group=instructions %}

- Terraform {#tf}

    1. If you do not have Terraform yet, [install it](../../tutorials/infrastructure-management/terraform-quickstart.md#install-terraform).
    1. [Get the authentication credentials](../../tutorials/infrastructure-management/terraform-quickstart.md#get-credentials). You can add them to environment variables or specify them later in the provider configuration file.
    1. [Configure and initialize a provider](../../tutorials/infrastructure-management/terraform-quickstart.md#configure-provider). There is no need to create a provider configuration file manually, you can [download it](https://github.com/yandex-cloud-examples/yc-terraform-provider-settings/blob/main/provider.tf).
    1. Place the configuration file in a separate working directory and [specify the parameter values](../../tutorials/infrastructure-management/terraform-quickstart.md#configure-provider). If you did not add the authentication credentials to environment variables, specify them in the configuration file.

    1. In your current working directory, create a `.tf` file with the following contents:

        ```hcl
        resource "yandex_mdb_clickhouse_cluster_v2" "old" { }
        ```

    1. Save the ID of the original ClickHouse® cluster to an environment variable:

        ```bash
        export CLICKHOUSE_CLUSTER_ID=<cluster_ID>
        ```

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

    1. Import the original ClickHouse® cluster settings to the Terraform configuration:

        ```bash
        terraform import yandex_mdb_clickhouse_cluster_v2.old ${CLICKHOUSE_CLUSTER_ID}
        ```

    1. Get the imported configuration:

        ```bash
        terraform show
        ```

    1. Copy it from your terminal and paste it into the `.tf` file.
    1. Create a new directory `imported-cluster` and move your configuration file there.
    1. Modify the configuration so that you can use it to create a new cluster:

        * Specify the new cluster name in the `resource` string and in the `name` argument.
        * Delete the `created_at`, `cluster_id`, and `id` arguments.
        * In the host descriptions, delete `fqdn`.
        * Under `clickhouse.config.merge_tree`, if the `max_bytes_to_merge_at_max_space_in_pool`, `max_parts_in_total`, and `number_of_free_entries_in_pool_to_execute_mutation` parameters are set to `0`, delete them.
        * Under `clickhouse.config.kafka`, set `sasl_password` or delete this parameter.
        * Under `clickhouse.config.rabbitmq`, set `password` or delete this parameter.
        * If the `maintenance_window` section has `type = "ANYTIME"`, delete the `hour` parameter.
        * Delete all `user` sections (if any). Use `yandex_mdb_clickhouse_user` resource to add database users.
        * Optionally, make further changes if you need a customized configuration.

    1. In the `imported-cluster` directory, [get the authentication credentials](../../tutorials/infrastructure-management/terraform-quickstart.md#get-credentials).

    1. In the same directory, [configure and initialize the provider](../../tutorials/infrastructure-management/terraform-quickstart.md#configure-provider). Instead of manually creating the provider configuration file, you can [download it](https://github.com/yandex-cloud-examples/yc-terraform-provider-settings/blob/main/provider.tf).

    1. Move the configuration file to the `imported-cluster` directory and [specify the arguments](../../tutorials/infrastructure-management/terraform-quickstart.md#configure-provider). If you have not added the authentication credentials to environment variables, specify them in the configuration file.

    1. Validate your Terraform configuration:

        ```bash
        terraform validate
        ```

        Terraform will display any configuration errors detected in your files.

    1. Create the required infrastructure:

        1. Run this command to view the planned changes:
        
           ```bash
           terraform plan
           ```
        
           If you described the configuration correctly, the terminal will display a list of the resources to update and their parameters. This is a verification step that does not apply changes to your resources.
        
        1. If everything looks correct, apply the changes:
           1. Run this command:
        
              ```bash
              terraform apply
              ```
        
           1. Confirm updating the resources.
           1. Wait for the operation to complete.

        All the required resources will be created in the specified folder. You can check resource availability and their settings in the [management console](https://console.yandex.cloud).

    {% note warning "Timeouts" %}
    
    The Terraform provider sets the following timeouts for Managed Service for ClickHouse® cluster operations:
    
    * Creating a cluster, including by restoring from a backup: 60 minutes.
    * Updating a cluster: 90 minutes.
    * Deleting a cluster: 30 minutes.
    
    Operations exceeding the timeout are aborted.
    
    {% cut "How to change these limits" %}
    
    Add the `timeouts` section to your cluster description, such as the following:
    
    ```hcl
    resource "yandex_mdb_clickhouse_cluster_v2" "<cluster_name>" {
      ...
      timeouts = {
        create = "1h30m" # 1 hour 30 minutes
        update = "2h"    # 2 hours
        delete = "30m"   # 30 minutes
      }
    }
    ```
    
    {% endcut %}
    
    {% endnote %}

{% endlist %}


## Examples {#examples}

### Creating a single-host cluster {#creating-a-single-host-cluster}

{% list tabs group=instructions %}

- CLI {#cli}

  Create a Managed Service for ClickHouse® cluster with the following test specifications:

  
  * Name: `mych`.
  * Environment: `production`.
  * Network: `default`.
  * Security group: `enp6saqnq4ie244g67sb`.
  * One ClickHouse® `s2.micro` host in the `b0rcctk2rvtr8efcch64` subnet, in the `ru-central1-a` availability zone.
  * Network SSD storage (`network-ssd`): 20 GB.
  * User: `user1`, password: `user1user1`.
  * Database: `db1`.
  * Cluster protection against accidental deletion: Enabled.


  Run this command:

  
  ```bash
  yc managed-clickhouse cluster create \
    --name mych \
    --environment=production \
    --network-name default \
    --clickhouse-resource-preset s2.micro \
    --host type=clickhouse,zone-id=ru-central1-a,subnet-id=b0rcctk2rvtr8efcch64 \
    --clickhouse-disk-size 20 \
    --clickhouse-disk-type network-ssd \
    --user name=user1,password=user1user1 \
    --database name=db1 \
    --security-group-ids enp6saqnq4ie244g67sb \
    --deletion-protection
  ```



- Terraform {#tf}

  Create a Managed Service for ClickHouse® cluster and its network with the following test specifications:

  * Name: `mych`.
  * Environment: `PRESTABLE`.
  * Cloud ID: `b1gq90dgh25bebiu75o`.
  * Folder ID: `b1gia87mbaomkfvsleds`.
  * New cloud network: `cluster-net`.
  * New [default security group](connect/index.md#configuring-security-groups) named `cluster-sg` in the `cluster-net` network. The group must allow connections to any cluster host from any network (including the internet) on ports `8443` and `9440`.
  * One shard, `shard1`.
  * One `s2.micro` host in `shard1`. The host resides in the new subnet, `cluster-subnet-ru-central1-a`.

    Subnet parameters:
    * Address range: `172.16.1.0/24`.
    * Network: `cluster-net`.
    * Availability zone: `ru-central1-a`.

  * Network SSD storage (`network-ssd`): 32 GB.
  * Database name: `db1`.
  * User: `user1`, password: `user1user1`.
  * Maintenance takes place at any time.

  The configuration files for this cluster are as follows:

  1. Configuration file with a description of the provider settings:

      `provider.tf`
      
      ```hcl
      terraform {
        required_providers {
          yandex = {
            source = "yandex-cloud/yandex"
          }
        }
      }
      
      provider "yandex" {
        cloud_id  = "b1gq90dgh25bebiu75o"
        folder_id = "b1gia87mbaomkfvsleds"
      }
      ```

  1. Configuration file with a description of the cloud network and subnet:

      {% cut "networks.tf" %} 
      
      ```hcl
      resource "yandex_vpc_network" "cluster-net" { name = "cluster-net" }
      
      resource "yandex_vpc_subnet" "cluster-subnet-a" {
        name           = "cluster-subnet-ru-central1-a"
        zone           = "ru-central1-a"
        network_id     = yandex_vpc_network.cluster-net.id
        v4_cidr_blocks = ["172.16.1.0/24"]
      }
      ```
      
      {% endcut %}

  1. Configuration file with a description of the security group:

      {% cut "security-groups.tf" %}
      
      ```hcl
      resource "yandex_vpc_default_security_group" "cluster-sg" {
        network_id = yandex_vpc_network.cluster-net.id
      
        ingress {
          description    = "HTTPS (secure)"
          port           = 8443
          protocol       = "TCP"
          v4_cidr_blocks = ["0.0.0.0/0"]
        }
      
        ingress {
          description    = "clickhouse-client (secure)"
          port           = 9440
          protocol       = "TCP"
          v4_cidr_blocks = ["0.0.0.0/0"]
        }
      
        egress {
          description    = "Allow all egress cluster traffic"
          protocol       = "TCP"
          v4_cidr_blocks = ["0.0.0.0/0"]
        }
      }
      ```
      
      {% endcut %}

  1. Configuration file with a description of the cluster and its host:

      {% cut "cluster.tf" %}
      
      ```hcl
      resource "yandex_mdb_clickhouse_cluster_v2" "mych" {
        name               = "mych"
        environment        = "PRESTABLE"
        network_id         = yandex_vpc_network.cluster-net.id
        security_group_ids = [yandex_vpc_default_security_group.cluster-sg.id]
      
        clickhouse = {
          resources = {
            resource_preset_id = "s2.micro"
            disk_type_id       = "network-ssd"
            disk_size          = 32
          }
        }
      
        shards = {
          "shard1" = {
            weight = 1
          }
        }
      
        hosts = {
          "h1" = {
            type       = "CLICKHOUSE"
            zone       = "ru-central1-a"
            subnet_id  = yandex_vpc_subnet.cluster-subnet-a.id
            shard_name = "shard1"
          }
        }
      
        maintenance_window {
          type = "ANYTIME"
        }
      }
      
      resource "yandex_mdb_clickhouse_database" "db1" {
        cluster_id = yandex_mdb_clickhouse_cluster_v2.mych.id
        name       = "db1"
      }
      
      resource "yandex_mdb_clickhouse_user" "user1" {
        cluster_id = yandex_mdb_clickhouse_cluster_v2.mych.id
        name       = "user1"
        password   = "user1user1"
        permission {
          database_name = yandex_mdb_clickhouse_database.db1.name
        }
      }
      ```
      
      {% endcut %}


{% endlist %}

### Creating a sharded cluster {#creating-a-sharded-cluster}

{% list tabs group=instructions %}

- CLI {#cli}

  Create a Managed Service for ClickHouse® cluster with the following test specifications:

  
  * Name: `mych`.
  * Environment: `production`.
  * Network: `default`.
  * Security group: `enp6saqnq4ie244g67sb`.
  * Three `s2.micro` class ClickHouse® hosts residing in different shards and different subnets:

      * In `shard1`, subnet ID `e9bhbia2scnk********`, availability zone `ru-central1-a`.
      * In `shard2`, subnet ID `e2lfqbm5nt9r********`, availability zone `ru-central1-b`.
      * In `shard3`, subnet ID `fl8beqmjckv8********`, availability zone `ru-central1-d`.

  * Network SSD storage (`network-ssd`): 20 GB.
  * User: `user1`, password: `user1user1`.
  * Database: `db1`.
  * Cluster protection against accidental deletion: Enabled.


  Run this command:

  
  ```bash
  yc managed-clickhouse cluster create \
    --name mych \
    --environment=production \
    --network-name default \
    --shard name=shard1,weight=1 \
    --shard name=shard2,weight=1 \
    --shard name=shard3,weight=1 \
    --host type=clickhouse,zone-id=ru-central1-a,subnet-id=e9bhbia2scnk********,shard-name=shard1 \
    --host type=clickhouse,zone-id=ru-central1-b,subnet-id=e2lfqbm5nt9r********,shard-name=shard2 \
    --host type=clickhouse,zone-id=ru-central1-d,subnet-id=fl8beqmjckv8********,shard-name=shard3 \
    --clickhouse-resource-preset s2.micro \
    --clickhouse-disk-type network-ssd \
    --clickhouse-disk-size 20 \
    --user name=user1,password=user1user1 \
    --database name=db1 \
    --security-group-ids enp6saqnq4ie244g67sb \
    --deletion-protection
  ```



- Terraform {#tf}

  Create a Managed Service for ClickHouse® cluster and its network with the following test specifications:

  * Name: `mych`.
  * Environment: `PRESTABLE`.
  * Cloud ID: `b1gq90dgh25bebiu75o`.
  * Folder ID: `b1gia87mbaomkfvsleds`.
  * New cloud network: `cluster-net`.

  * Three `s2.micro` class ClickHouse® hosts residing in different shards and in new subnets belonging to the `cluster-net` network:

      * In `shard1`, subnet `cluster-subnet-ru-central1-a` (range `172.16.1.0/24`, availability zone `ru-central1-a`).
      * In `shard2`, subnet `cluster-subnet-ru-central1-b` (range `172.16.2.0/24`, availability zone `ru-central1-b`).
      * In `shard3`, subnet `cluster-subnet-ru-central1-d` (range `172.16.3.0/24`, availability zone `ru-central1-d`).

  * New [default security group](connect/index.md#configuring-security-groups) named `cluster-sg` in the `cluster-net` network. The group must allow connections to any cluster host from any network (including the internet) on ports `8443` and `9440`.
  * Network SSD storage (`network-ssd`) for each of the ClickHouse® hosts: 20 GB.
  * Database name: `db1`.
  * User: `user1`, password: `user1user1`.
  * Maintenance takes place at any time.

  The configuration files for this cluster are as follows:

  1. Configuration file with a description of the provider settings:

      `provider.tf`
      
      ```hcl
      terraform {
        required_providers {
          yandex = {
            source = "yandex-cloud/yandex"
          }
        }
      }
      
      provider "yandex" {
        cloud_id  = "b1gq90dgh25bebiu75o"
        folder_id = "b1gia87mbaomkfvsleds"
      }
      ```

  1. Configuration file with a description of the cloud network and subnets:

      {% cut "networks.tf" %} 
      
      ```hcl
      resource "yandex_vpc_network" "cluster-net" { name = "cluster-net" }
      
      resource "yandex_vpc_subnet" "cluster-subnet-a" {
        name           = "cluster-subnet-ru-central1-a"
        zone           = "ru-central1-a"
        network_id     = yandex_vpc_network.cluster-net.id
        v4_cidr_blocks = ["172.16.1.0/24"]
      }
      
      resource "yandex_vpc_subnet" "cluster-subnet-b" {
        name           = "cluster-subnet-ru-central1-b"
        zone           = "ru-central1-b"
        network_id     = yandex_vpc_network.cluster-net.id
        v4_cidr_blocks = ["172.16.2.0/24"]
      }
      
      resource "yandex_vpc_subnet" "cluster-subnet-d" {
        name           = "cluster-subnet-ru-central1-d"
        zone           = "ru-central1-d"
        network_id     = yandex_vpc_network.cluster-net.id
        v4_cidr_blocks = ["172.16.3.0/24"]
      }
      ```
      
      {% endcut %}

  1. Configuration file with a description of the security group:

      {% cut "security-groups.tf" %}
      
      ```hcl
      resource "yandex_vpc_default_security_group" "cluster-sg" {
        network_id = yandex_vpc_network.cluster-net.id
      
        ingress {
          description    = "HTTPS (secure)"
          port           = 8443
          protocol       = "TCP"
          v4_cidr_blocks = ["0.0.0.0/0"]
        }
      
        ingress {
          description    = "clickhouse-client (secure)"
          port           = 9440
          protocol       = "TCP"
          v4_cidr_blocks = ["0.0.0.0/0"]
        }
      
        egress {
          description    = "Allow all egress cluster traffic"
          protocol       = "TCP"
          v4_cidr_blocks = ["0.0.0.0/0"]
        }
      }
      ```
      
      {% endcut %}

  1. Configuration file with a description of the cluster and its hosts:

      {% cut "cluster.tf" %}
      
      ```hcl
      resource "yandex_mdb_clickhouse_cluster_v2" "mych" {
        name               = "mych"
        environment        = "PRESTABLE"
        network_id         = yandex_vpc_network.cluster-net.id
        security_group_ids = [yandex_vpc_default_security_group.cluster-sg.id]
      
        clickhouse = {
          resources = {
            resource_preset_id = "s2.micro"
            disk_type_id       = "network-ssd"
            disk_size          = 20
          }
        }
      
        shards = {
      
          "shard1" = {
            weight = 1
          }
      
          "shard2" = {
            weight = 1
          }
      
          "shard3" = {
            weight = 1
          }
      
        }
      
        hosts = {
      
          "host1" = {
            type       = "CLICKHOUSE"
            zone       = "ru-central1-a"
            subnet_id  = yandex_vpc_subnet.cluster-subnet-a.id
            shard_name = "shard1"
          }
      
          "host2" = {
            type       = "CLICKHOUSE"
            zone       = "ru-central1-b"
            subnet_id  = yandex_vpc_subnet.cluster-subnet-b.id
            shard_name = "shard2"
          }
      
          "host3" = {
            type       = "CLICKHOUSE"
            zone       = "ru-central1-d"
            subnet_id  = yandex_vpc_subnet.cluster-subnet-d.id
            shard_name = "shard3"
          }
      
        }
      
        maintenance_window {
          type = "ANYTIME"
        }
      }
      
      resource "yandex_mdb_clickhouse_database" "db1" {
        cluster_id = yandex_mdb_clickhouse_cluster_v2.mych.id
        name       = "db1"
      }
      
      resource "yandex_mdb_clickhouse_user" "user1" {
        cluster_id = yandex_mdb_clickhouse_cluster_v2.mych.id
        name       = "user1"
        password   = "user1user1"
        permission {
          database_name = yandex_mdb_clickhouse_database.db1.name
        }
      }
      ```
      
      {% endcut %}


{% endlist %}

### Creating a cluster with the ZooKeeper coordination service {#creating-a-multi-host-cluster}


{% list tabs group=instructions %}

- CLI {#cli}

  Create a Managed Service for ClickHouse® cluster with the following test specifications:

  
  * Name: `ch-zk`.
  * Environment: `production`.
  * Network: `default`.
  * Security group: `enp6saqnq4ie244g67sb`.
  * Three ClickHouse® hosts of class `s2.micro` residing in subnets across three different availability zones:

    * In subnet with ID `e9bhbia2scnk********` in the `ru-central1-a` availability zone
    * In subnet with ID `e2lfqbm5nt9r********` in the `ru-central1-b` availability zone
    * In subnet with ID `fl8beqmjckv8********` in the `ru-central1-d` availability zone

  * Three ZooKeeper hosts of class `b2.medium` residing in subnets across three different availability zones:

    * In subnet with ID `e9bhbia2scnk********` in the `ru-central1-a` availability zone
    * In subnet with ID `e2lfqbm5nt9r********` in the `ru-central1-b` availability zone
    * In subnet with ID `fl8beqmjckv8********` in the `ru-central1-d` availability zone

  * Network SSD storage (`network-ssd`) for each of the ClickHouse® cluster hosts: 32 GB.
  * Network SSD storage (`network-ssd`) for each of the ZooKeeper cluster hosts: 10 GB.
  * User: `user1`, password: `user1user1`.
  * Database: `db1`.
  * Accidental deletion protection enabled.


  Run this command:

  
  ```bash
  yc managed-clickhouse cluster create \
    --name ch-zk \
    --environment=production \
    --network-name default \
    --host type=clickhouse,zone-id=ru-central1-a,subnet-id=e9bhbia2scnk******** \
    --host type=clickhouse,zone-id=ru-central1-b,subnet-id=e2lfqbm5nt9r******** \
    --host type=clickhouse,zone-id=ru-central1-d,subnet-id=fl8beqmjckv8******** \
    --host type=zookeeper,zone-id=ru-central1-a,subnet-id=e9bhbia2scnk******** \
    --host type=zookeeper,zone-id=ru-central1-b,subnet-id=e2lfqbm5nt9r******** \
    --host type=zookeeper,zone-id=ru-central1-d,subnet-id=fl8beqmjckv8******** \
    --clickhouse-resource-preset s2.micro \
    --clickhouse-disk-size 32 \
    --clickhouse-disk-type network-ssd \
    --zookeeper-resource-preset b2.medium \
    --zookeeper-disk-size 10 \
    --zookeeper-disk-type network-ssd \
    --user name=user1,password=user1user1 \
    --database name=db1 \
    --security-group-ids enp6saqnq4ie244g67sb \
    --deletion-protection
  ```



- Terraform {#tf}

  Create a Managed Service for ClickHouse® cluster with the following test specifications:

  * Name: `mych`.
  * Environment: `PRESTABLE`.
  * Cloud ID: `b1gq90dgh25bebiu75o`.
  * Folder ID: `b1gia87mbaomkfvsleds`.
  * New cloud network: `cluster-net`.

  * One shard, `shard1`, to house all ClickHouse® hosts.
  * Three ClickHouse® `s2.micro` hosts and three ZooKeeper `b2.medium` hosts (for [replication](../concepts/replication.md)).

    One ClickHouse® and one ZooKeeper host will be added to each new subnet:

    * `cluster-subnet-ru-central1-a`: `172.16.1.0/24`, availability zone: `ru-central1-a`.
    * `cluster-subnet-ru-central1-b`: `172.16.2.0/24`, availability zone: `ru-central1-b`.
    * `cluster-subnet-ru-central1-d`: `172.16.3.0/24`, availability zone: `ru-central1-d`.

    These subnets will belong to the `cluster-net` network.

  * New [default security group](connect/index.md#configuring-security-groups) named `cluster-sg` in the `cluster-net` network. The group must allow connections to any cluster host from any network (including the internet) on ports `8443` and `9440`.
  * Network SSD storage (`network-ssd`) for each of the ClickHouse® cluster hosts: 32 GB.
  * Network SSD storage (`network-ssd`) for each of the ZooKeeper cluster hosts: 10 GB.
  * Database name: `db1`.
  * User: `user1`, password: `user1user1`.
  * Maintenance takes place at any time.

  The configuration files for this cluster are as follows:

  1. Configuration file with a description of the provider settings:

      `provider.tf`
      
      ```hcl
      terraform {
        required_providers {
          yandex = {
            source = "yandex-cloud/yandex"
          }
        }
      }
      
      provider "yandex" {
        cloud_id  = "b1gq90dgh25bebiu75o"
        folder_id = "b1gia87mbaomkfvsleds"
      }
      ```

  1. Configuration file with a description of the cloud network and subnets:

      {% cut "networks.tf" %} 
      
      ```hcl
      resource "yandex_vpc_network" "cluster-net" { name = "cluster-net" }
      
      resource "yandex_vpc_subnet" "cluster-subnet-a" {
        name           = "cluster-subnet-ru-central1-a"
        zone           = "ru-central1-a"
        network_id     = yandex_vpc_network.cluster-net.id
        v4_cidr_blocks = ["172.16.1.0/24"]
      }
      
      resource "yandex_vpc_subnet" "cluster-subnet-b" {
        name           = "cluster-subnet-ru-central1-b"
        zone           = "ru-central1-b"
        network_id     = yandex_vpc_network.cluster-net.id
        v4_cidr_blocks = ["172.16.2.0/24"]
      }
      
      resource "yandex_vpc_subnet" "cluster-subnet-d" {
        name           = "cluster-subnet-ru-central1-d"
        zone           = "ru-central1-d"
        network_id     = yandex_vpc_network.cluster-net.id
        v4_cidr_blocks = ["172.16.3.0/24"]
      }
      ```
      
      {% endcut %}

  1. Configuration file with a description of the security group:

      {% cut "security-groups.tf" %}
      
      ```hcl
      resource "yandex_vpc_default_security_group" "cluster-sg" {
        network_id = yandex_vpc_network.cluster-net.id
      
        ingress {
          description    = "HTTPS (secure)"
          port           = 8443
          protocol       = "TCP"
          v4_cidr_blocks = ["0.0.0.0/0"]
        }
      
        ingress {
          description    = "clickhouse-client (secure)"
          port           = 9440
          protocol       = "TCP"
          v4_cidr_blocks = ["0.0.0.0/0"]
        }
      
        egress {
          description    = "Allow all egress cluster traffic"
          protocol       = "TCP"
          v4_cidr_blocks = ["0.0.0.0/0"]
        }
      }
      ```
      
      {% endcut %}

  1. Configuration file with a description of the cluster and its hosts:

      {% cut "cluster.tf" %}
      
      ```hcl
      resource "yandex_mdb_clickhouse_cluster_v2" "mych" {
        name               = "mych"
        environment        = "PRESTABLE"
        network_id         = yandex_vpc_network.cluster-net.id
        security_group_ids = [yandex_vpc_default_security_group.cluster-sg.id]
      
        clickhouse = {
          resources = {
            resource_preset_id = "s2.micro"
            disk_type_id       = "network-ssd"
            disk_size          = 32
          }
        }
      
        zookeeper = {
          resources = {
            resource_preset_id = "b2.medium"
            disk_type_id       = "network-ssd"
            disk_size          = 10
          }
        }
      
        shards = {
          "shard1" = {
            weight = 1
          }
        }
      
        hosts = {
      
          "h1" = {
            type       = "CLICKHOUSE"
            zone       = "ru-central1-a"
            subnet_id  = yandex_vpc_subnet.cluster-subnet-a.id
            shard_name = "shard1"
          }
      
          "h2" = {
            type       = "CLICKHOUSE"
            zone       = "ru-central1-b"
            subnet_id  = yandex_vpc_subnet.cluster-subnet-b.id
            shard_name = "shard1"
          }
      
          "h3" = {
            type       = "CLICKHOUSE"
            zone       = "ru-central1-d"
            subnet_id  = yandex_vpc_subnet.cluster-subnet-d.id
            shard_name = "shard1"
          }
      
          "h4" = {
            type      = "ZOOKEEPER"
            zone      = "ru-central1-a"
            subnet_id = yandex_vpc_subnet.cluster-subnet-a.id
          }
      
          "h5" = {
            type      = "ZOOKEEPER"
            zone      = "ru-central1-b"
            subnet_id = yandex_vpc_subnet.cluster-subnet-b.id
          }
      
          "h6" = {
            type      = "ZOOKEEPER"
            zone      = "ru-central1-d"
            subnet_id = yandex_vpc_subnet.cluster-subnet-d.id
          }
        }
      
        maintenance_window {
          type = "ANYTIME"
        }
      }
      
      resource "yandex_mdb_clickhouse_database" "db1" {
        cluster_id = yandex_mdb_clickhouse_cluster_v2.mych.id
        name       = "db1"
      }
      
      resource "yandex_mdb_clickhouse_user" "user1" {
        cluster_id = yandex_mdb_clickhouse_cluster_v2.mych.id
        name       = "user1"
        password   = "user1user1"
        permission {
          database_name = yandex_mdb_clickhouse_database.db1.name
        }
      }
      ```
      
      {% endcut %}


{% endlist %}

_ClickHouse® is a registered trademark of [ClickHouse, Inc](https://clickhouse.com)._