# Updating PostgreSQL cluster settings

After creating a cluster, you can:

* [Change the host class](#change-resource-preset).

* [Configure servers](#change-postgresql-config) as described in the [PostgreSQL guides](https://www.postgresql.org/docs/current/runtime-config.html).

* [Change additional cluster settings](#change-additional-settings).

* [Manually switch the master host](#start-manual-failover).

* [Move the cluster](#move-cluster) to another folder.


* [Change cluster security groups](#change-sg-set).


{% note info %}

All configuration changes require the cluster to be running.

{% endnote %}

Learn more about other cluster updates:

* [PostgreSQL version upgrade](cluster-version-update.md).

* [Managing disk space](storage-space.md).

* [Migrating cluster hosts to a different availability zone](host-migration.md).

## Changing the host class {#change-resource-preset}

{% note info %}

Some PostgreSQL settings [depend on the selected host class](../concepts/settings-list.md#settings-instance-dependent).

{% endnote %}

When changing the host class:

* A single-host cluster will be unavailable for a few minutes and all database connections will be dropped.
* A multi-host cluster will switch to a new master host The hosts will undergo a rolling update, with each host unavailable for a few minutes while it is stopped and updated.
* A cluster with local SSD storage may be unavailable for an extended period if data migration to another physical server is required.
* Using a [special FQDN](connect/fqdn.md#special-fqdns) does not guarantee a stable database connection: user sessions may be terminated.

We recommend changing the host class only when the cluster is idle.

{% list tabs group=instructions %}

- Management console {#console}

  1. Navigate to **Managed Service for&nbsp;PostgreSQL**.
  1. Select the cluster and click ![image](../../_assets/console-icons/pencil.svg) **Edit** in the top panel.
  1. Under **Host class**, select the PostgreSQL host class.
  1. Click **Save changes**.

- 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 change the cluster’s [host class](../concepts/instance-types.md):

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

      ```bash
      yc managed-postgresql cluster update --help
      ```

  1. Request a list of available host classes. The `ZONE IDS` column lists the availability zones where the relevant class can be selected:

     
     ```bash
     yc managed-postgresql resource-preset list
     ```

     ```text
     +-----------+--------------------------------+-------+----------+
     |    ID     |            ZONE IDS            | CORES |  MEMORY  |
     +-----------+--------------------------------+-------+----------+
     | s1.micro  | ru-central1-a, ru-central1-b,  |     2 | 8.0 GB   |
     |           | ru-central1-d                  |       |          |
     | ...                                                           |
     +-----------+--------------------------------+-------+----------+
     ```


  1. Specify the relevant class in the cluster update command:

      ```bash
      yc managed-postgresql cluster update <cluster_name_or_ID> \
          --resource-preset <host_class_ID>
      ```

      Managed Service for PostgreSQL will start updating the host class for your cluster.

- Terraform {#tf}

  1. Open the current Terraform configuration file describing your infrastructure.

      For more on how to create this file, see [Creating a cluster](cluster-create.md).

      For a complete list of configurable Managed Service for PostgreSQL cluster fields, see [this Terraform provider guide](../../terraform/resources/mdb_postgresql_cluster.md).

  1. In the Managed Service for PostgreSQL cluster description, update the `resource_preset_id` attribute value under `config.resources`:

      ```hcl
      resource "yandex_mdb_postgresql_cluster" "<cluster_name>" {
        ...
        config {
          resources {
            resource_preset_id = "<host_class>"
            ...
          }
        }
      }
      ```

  1. Make sure the settings 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. Confirm updating the resources.

      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.

      {% note warning "Timeouts" %}
      
      The Terraform provider sets the following timeouts for Managed Service for PostgreSQL cluster operations:
      
      * Creating a cluster, including restoration from a backup: 30 minutes.
      * Updating a cluster: 60 minutes.
      * Deleting a cluster: 15 minutes.
      
      Operations exceeding the timeout are aborted.
      
      {% cut "How can I change these timeouts?" %}
      
      Add a `timeouts` section to the cluster description, e.g.:
      
      ```hcl
      resource "yandex_mdb_postgresql_cluster" "<cluster_name>" {
        ...
        timeouts {
          create = "1h30m" # 1 hour 30 minutes
          update = "2h"    # 2 hours
          delete = "30m"   # 30 minutes
        }
      }
      ```
      
      {% endcut %}
      
      {% endnote %}

- REST API {#api}

  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.Update](../api-ref/Cluster/update.md) method, e.g., via the following [cURL](https://curl.se/) request:

     {% note warning %}
     
     The API method will assign default values to all the parameters of the object you are modifying unless you explicitly provide them in your request. To avoid this, list the settings you want to change in the `updateMask` parameter as a single comma-separated string.
     
     {% endnote %}

     ```bash
     curl \
       --request PATCH \
       --header "Authorization: Bearer $IAM_TOKEN" \
       --header "Content-Type: application/json" \
       --url 'https://mdb.api.cloud.yandex.net/managed-postgresql/v1/clusters/<cluster_ID>' \
       --data '{
                 "updateMask": "configSpec.resources.resourcePresetId",
                 "configSpec": {
                   "resources": {
                     "resourcePresetId": "<host_class>"
                   }
                 }
               }'
     ```

     Where:

     * `updateMask`: Comma-separated string of settings to update.

       Here, we provide only one setting.

     * `configSpec.resources.resourcePresetId`: New [host class](../concepts/instance-types.md).

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

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

- gRPC API {#grpc-api}

  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.Update](../api-ref/grpc/Cluster/update.md) method, e.g., via the following [gRPCurl](https://github.com/fullstorydev/grpcurl) request:

     {% note warning %}
     
     The API method will assign default values to all the parameters of the object you are modifying unless you explicitly provide them in your request. To avoid this, list the settings you want to change in the `update_mask` parameter as an array of `paths[]` strings.
     
     {% cut "Format for listing settings" %}
     
     ```yaml
     "update_mask": {
         "paths": [
             "<setting_1>",
             "<setting_2>",
             ...
             "<setting_N>"
         ]
     }
     ```
     
     {% endcut %}
     
     {% endnote %}

     ```bash
     grpcurl \
       -format json \
       -import-path ~/cloudapi/ \
       -import-path ~/cloudapi/third_party/googleapis/ \
       -proto ~/cloudapi/yandex/cloud/mdb/postgresql/v1/cluster_service.proto \
       -rpc-header "Authorization: Bearer $IAM_TOKEN" \
       -d '{
             "cluster_id": "<cluster_ID>",
             "update_mask": {
               "paths": [
                 "config_spec.resources.resource_preset_id"
               ]
             },
             "config_spec": {
               "resources": {
                 "resource_preset_id": "<host_class>"
               }
             }
           }' \
       mdb.api.cloud.yandex.net:443 \
       yandex.cloud.mdb.postgresql.v1.ClusterService.Update
     ```

     Where:

     * `update_mask`: List of settings you want to update as an array of strings (`paths[]`).

       Here, we provide only one setting.

     * `config_spec.resources.resource_preset_id`: New [host class](../concepts/instance-types.md).

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

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

{% endlist %}

## Updating PostgreSQL settings {#change-postgresql-config}

You can change the DBMS settings for the hosts in your cluster.

{% note warning %}

* You cannot change PostgreSQL settings using SQL commands.
* Some PostgreSQL settings [depend on the selected host class or storage size](../concepts/settings-list.md#settings-instance-dependent).

{% endnote %}

{% list tabs group=instructions %}

- Management console {#console}

  1. Navigate to **Managed Service for&nbsp;PostgreSQL**.
  1. Select the cluster and click ![image](../../_assets/console-icons/pencil.svg) **Edit** in the top panel.
  1. Change the [PostgreSQL settings](../concepts/settings-list.md) by clicking **Settings** under **DBMS settings**.
  1. Click **Save**.
  1. Click **Save changes**.

- 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 update the [PostgreSQL settings](../concepts/settings-list.md):

  1. View the full list of cluster settings:

     ```bash
     yc managed-postgresql cluster get <cluster_name_or_ID> --full
     ```

  1. View the description of the CLI command for updating the cluster configuration:

      ```bash
      yc managed-postgresql cluster update-config --help
      ```

  1. Set the parameter values as needed:

      All supported arguments are listed in the `postgresqlConfig_<PostgreSQL_version>` field of the [ `update` method’s request format](../api-ref/Cluster/update.md). To specify an argument name in the CLI call, convert its name from <q>lowerCamelCase</q> to <q>snake_case</q>. For example, the `maxPreparedTransactions` argument from the API request becomes `max_prepared_transactions` for the CLI command:

      ```bash
      yc managed-postgresql cluster update-config <cluster_name_or_ID> \
         --set <parameter_1_name>=<value_1>,<parameter_2_name>=<value_2>,...
      ```

      Managed Service for PostgreSQL will start updating the cluster settings.

- Terraform {#tf}

    1. Open the current Terraform configuration file describing your infrastructure.

        For more on how to create this file, see [Creating a cluster](cluster-create.md).

        For a complete list of configurable Managed Service for PostgreSQL cluster fields, see [this Terraform provider guide](../../terraform/resources/mdb_postgresql_cluster.md).

    1. Update the settings in the `config.postgresql_config` section of your Managed Service for PostgreSQL cluster description. If there is no such section, create one.

        ```hcl
        resource "yandex_mdb_postgresql_cluster" "<cluster_name>" {
          ...
          config {
            ...
            postgresql_config = {
              max_connections                   = <maximum_number_of_connections>
              enable_parallel_hash              = <true_or_false>
              vacuum_cleanup_index_scale_factor = <number_between_0_and_1>
              ...
            }
          }
        }
        ```

    1. Make sure the settings 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. Confirm updating the resources.

        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.

        {% note warning "Timeouts" %}
        
        The Terraform provider sets the following timeouts for Managed Service for PostgreSQL cluster operations:
        
        * Creating a cluster, including restoration from a backup: 30 minutes.
        * Updating a cluster: 60 minutes.
        * Deleting a cluster: 15 minutes.
        
        Operations exceeding the timeout are aborted.
        
        {% cut "How can I change these timeouts?" %}
        
        Add a `timeouts` section to the cluster description, e.g.:
        
        ```hcl
        resource "yandex_mdb_postgresql_cluster" "<cluster_name>" {
          ...
          timeouts {
            create = "1h30m" # 1 hour 30 minutes
            update = "2h"    # 2 hours
            delete = "30m"   # 30 minutes
          }
        }
        ```
        
        {% endcut %}
        
        {% endnote %}

- REST API {#api}

  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.Update](../api-ref/Cluster/update.md) method, e.g., via the following [cURL](https://curl.se/) request:

     {% note warning %}
     
     The API method will assign default values to all the parameters of the object you are modifying unless you explicitly provide them in your request. To avoid this, list the settings you want to change in the `updateMask` parameter as a single comma-separated string.
     
     {% endnote %}

     ```bash
     curl \
       --request PATCH \
       --header "Authorization: Bearer $IAM_TOKEN" \
       --header "Content-Type: application/json" \
       --url 'https://mdb.api.cloud.yandex.net/managed-postgresql/v1/clusters/<cluster_ID>' \
       --data '{
                 "updateMask": "configSpec.postgresqlConfig_<PostgreSQL_version>.<setting_1>,...,configSpec.postgresqlConfig_<PostgreSQL_version>.<setting_N>",
                 "configSpec": {
                   "postgresqlConfig_<PostgreSQL_version>": {
                     "<setting_1>": "<value_1>",
                     "<setting_2>": "<value_2>",
                     ...
                     "<setting_N>": "<value_N>"
                   }
                 }
               }'
     ```

     Where:

     * `updateMask`: Comma-separated string of settings to update.

       List all PostgreSQL settings you want to update.

     * `configSpec.postgresqlConfig_<PostgreSQL_version>`: PostgreSQL settings. Enter each setting on a new line, separated by commas.

       See the [method description](../api-ref/Cluster/update.md#yandex.cloud.mdb.postgresql.v1.UpdateClusterRequest) for the list of PostgreSQL versions available for this parameter. See [Cluster-level settings](../concepts/settings-list.md#dbms-cluster-settings) for the descriptions and possible values of the settings.

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

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

- gRPC API {#grpc-api}

  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.Update](../api-ref/grpc/Cluster/update.md) method, e.g., via the following [gRPCurl](https://github.com/fullstorydev/grpcurl) request:

     {% note warning %}
     
     The API method will assign default values to all the parameters of the object you are modifying unless you explicitly provide them in your request. To avoid this, list the settings you want to change in the `update_mask` parameter as an array of `paths[]` strings.
     
     {% cut "Format for listing settings" %}
     
     ```yaml
     "update_mask": {
         "paths": [
             "<setting_1>",
             "<setting_2>",
             ...
             "<setting_N>"
         ]
     }
     ```
     
     {% endcut %}
     
     {% endnote %}

     ```bash
     grpcurl \
       -format json \
       -import-path ~/cloudapi/ \
       -import-path ~/cloudapi/third_party/googleapis/ \
       -proto ~/cloudapi/yandex/cloud/mdb/postgresql/v1/cluster_service.proto \
       -rpc-header "Authorization: Bearer $IAM_TOKEN" \
       -d '{
             "cluster_id": "<cluster_ID>",
             "update_mask": {
               "paths": [
                 "config_spec.postgresql_config_<PostgreSQL_version>.<setting_1>",
                 "config_spec.postgresql_config_<PostgreSQL_version>.<setting_2>",
                 ...,
                 "config_spec.postgresql_config_<PostgreSQL_version>.<setting_N>"
               ]
             },
             "config_spec": {
               "postgresql_config_<PostgreSQL_version>": {
                 "<setting_1>": "<value_1>",
                 "<setting_2>": "<value_2>",
                 ...
                 "<setting_N>": "<value_N>"
               }
             }
           }' \
       mdb.api.cloud.yandex.net:443 \
       yandex.cloud.mdb.postgresql.v1.ClusterService.Update
     ```

     Where:

     * `update_mask`: List of parameters to update as an array of strings (`paths[]`).

       List all PostgreSQL settings you want to update.

     * `config_spec.postgresql_config_<PostgreSQL_version>`: PostgreSQL settings. Enter each setting on a new line, separated by commas.

       See the [method description](../api-ref/grpc/Cluster/create.md#yandex.cloud.mdb.postgresql.v1.ConfigSpec) for the list of PostgreSQL versions available for this parameter. See [Cluster-level settings](../concepts/settings-list.md#dbms-cluster-settings) for the descriptions and possible values of the settings.

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

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

{% endlist %}

## Changing additional cluster settings {#change-additional-settings}

{% note warning %}

Changing additional settings will restart the cluster. The only exceptions are the maintenance window and deletion protection settings.

{% endnote %}

{% list tabs group=instructions %}

- Management console {#console}

  1. Navigate to **Managed Service for&nbsp;PostgreSQL**.
  1. Select the cluster and click ![image](../../_assets/console-icons/pencil.svg) **Edit** in the top panel.
  
  
  1. Under **Performance diagnostics**, enable standard or advanced diagnostics. The advanced mode also includes collecting and analyzing query plans.
         
     To use the [Performance diagnostics](performance-diagnostics.md) tool, select **Statistics sampling** and set up **Sessions sampling interval** and **Statements sampling interval**. Both settings are measured in seconds.
  

  1. Update additional cluster settings:

     - **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. Backups are automatically deleted once their retention period expires. The default is 7 days. For more information, see [Backups](../concepts/backup.md).
     
         Changing the retention period affects both new and existing automatic backups. For example, the initial retention period was 7 days. A specific automatic backup has 1 day of remaining lifetime. If you increase the retention period to 9 days, that backup’s remaining lifetime becomes 3 days.
     
         Automatic cluster backups are stored for a specified number of days, while manually created ones are stored indefinitely. After a cluster is deleted, all its backups are retained for 7 days.
     
     - **Maintenance**: [Maintenance window](../concepts/maintenance.md) 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.
     
     - **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.
     
     
     
     
     - **Yandex Query access**: Enables you to run YQL queries against cluster databases from [Yandex Query](../../query/concepts/index.md).
     
     - **Serverless access**: Enable this option to allow cluster access from [Yandex Cloud Functions](../../functions/concepts/index.md). For more information about setting up access, see [Cloud Functions](../../functions/operations/database-connection.md) this guide.
     
     
     
     - **Pooling mode**: Select one of the [connection pooler modes](../concepts/pooling.md).
     
     - **Deletion protection**: Deletion protection for the cluster, its databases, and users.
     
         By default, when users and databases are created, this setting’s value is inherited from the cluster. You can also specify this setting manually. See [User management](cluster-users.md) and [Database management](databases.md) for details.
         
         If the setting is changed on a running cluster, the new value will only be inherited by users and databases with the **Same as cluster** protection level.
     
         Even with deletion protection enabled, one can still connect to the cluster manually and delete the data.

- 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 change advanced cluster settings:

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

        ```bash
        yc managed-postgresql cluster update --help
        ```

    1. Run the following command with the list of settings you want to update:

        ```bash
        yc managed-postgresql cluster update <cluster_name_or_ID> \
            --backup-window-start <backup_start_time> \
            --backup-retain-period-days=<automatic_backup_retention_period_in_days> \
            --datalens-access=<allow_access_from_DataLens> \
            --maintenance-window type=<maintenance_type>,`
                                `day=<day_of_week>,`
                                `hour=<hour> \
            --websql-access=<allow_access_from_WebSQL> \
            --deletion-protection \
            --connection-pooling-mode=<connection_pooler_mode> \
            --serverless-access=<allow_access_from_Serverless_Containers> \
            --yandexquery-access=<allow_access_from_Yandex_Query> \
            --performance-diagnostics enabled=<enable_statistics_collection>,`
                                     `sessions-sampling-interval=<session_sampling_interval>,`
                                     `statements-sampling-interval=<statement_sampling_interval>
        ```

    You can update the following settings:

    * `--backup-window-start`: The cluster backup start time, set in UTC format `HH:MM:SS`. If the time is not set, the backup will start at 22:00 UTC.

    * `--backup-retain-period-days`: Automatic backup retention period, in days.

    * `--datalens-access`: Enables access from DataLens. The default value is `false`. To learn more about configuring a connection, see [Connecting to a cluster from DataLens](datalens-connect.md).

    * `--maintenance-window`: [Maintenance window](../concepts/maintenance.md) settings that apply to both running and stopped clusters. The `type` setting defines the maintenance type:

        * `anytime`: Any time (default).
        * `weekly`: On a schedule. For this value, also specify the following:
            * `day`: Day of week, i.e., `MON`, `TUE`, `WED`, `THU`, `FRI`, `SAT`, or `SUN`.
            * `hour`: Sequence number of UTC hour interval, 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`.

    * `--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`.
    
    
    * `--serverless-access`: Enables access to the cluster from [Yandex Cloud Functions](../../functions/concepts/index.md). The default value is `false`. For more information about setting up access, see [this Cloud Functions guide](../../functions/operations/database-connection.md).

    * `--yandexquery-access`: Enables access to the cluster from [Yandex Query](../../query/concepts/index.md). This feature is in the [Preview](../../overview/concepts/launch-stages.md) stage and can be enabled upon request.


    * `--connection-pooling-mode`: Specifies the [connection pooler mode](../concepts/pooling.md) (`SESSION`, `TRANSACTION`, or `STATEMENT`).

    * `--deletion-protection`: Deletion protection for the cluster, its databases, and users.

        By default, when users and databases are created, this setting’s value is inherited from the cluster. You can also specify this setting manually. See [User management](cluster-users.md) and [Database management](databases.md) for details.

        If the setting is changed on a running cluster, the new value will only be inherited by users and databases with the **Same as cluster** protection level.

        Even with deletion protection enabled, one can still connect to the cluster manually and delete the data.

    
    * `--performance-diagnostics`: [Statistics collection](performance-diagnostics.md#activate-stats-collector) settings:

        * `enabled`: The value of `true` enables statistics collection. The default value is `false`.
        * `sessions-sampling-interval`: Session sampling interval in seconds. The valid values range from `1` to `86400`.
        * `statements-sampling-interval`: Statement sampling interval in seconds. The valid values range from `60` to `86400`.


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

- Terraform {#tf}

  1. Open the current Terraform configuration file describing your infrastructure.

      For more on how to create this file, see [Creating a cluster](cluster-create.md).

      For a complete list of configurable Managed Service for PostgreSQL cluster fields, see [this Terraform provider guide](../../terraform/resources/mdb_postgresql_cluster.md).

  1. To change the backup start time, add the `config.backup_window_start` section to the Managed Service for PostgreSQL cluster description:

      ```hcl
      resource "yandex_mdb_postgresql_cluster" "<cluster_name>" {
        ...
        config {
          backup_window_start {
            hours   = <backup_start_hour>
            minutes = <backup_start_minute>
          }
          ...
        }
      }
      ```

  1. To allow access to the cluster from Yandex DataLens and to enable [running SQL queries from the management console](web-sql-query.md) using Yandex WebSQL, update the relevant fields in the `config.access` section:

      ```hcl
      resource "yandex_mdb_postgresql_cluster" "<cluster_name>" {
        ...
        config {
          access {
            data_lens = <allow_access_from_DataLens>
            web_sql   = <allow_access_from_WebSQL>
            ...
        }
        ...
      }
      ```

      Where:

      * `data_lens`: Access from DataLens, `true` or `false`.
      * `web_sql`: Execution of SQL queries from the management console using Yandex WebSQL (`true` or `false`).

  1. To change the [connection pooler mode](../concepts/pooling.md), add a `config.pooler_config` section to the Managed Service for PostgreSQL cluster description:

      ```hcl
      resource "yandex_mdb_postgresql_cluster" "<cluster_name>" {
        ...
        config {
          pooler_config {
            pool_discard = <clear_client_states_after_each_transaction>
            pooling_mode = "<operation_mode>"
          }
          ...
        }
      }
      ```

      Where:

      * `pool_discard`: Defines whether clients should discard their state after each transaction, `true` or `false`.
      * `pooling_mode`: Operation mode, `SESSION`, `TRANSACTION`, or `STATEMENT`.

  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_postgresql_cluster" "<cluster_name>" {
       ...
       maintenance_window {
         type = "<maintenance_type>"
         day  = "<day_of_week>"
         hour = <sequence_number_of_hour_interval>
       }
       ...
     }
     ```
     
     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 set up statistics collection, add the `performance_diagnostics` block to the `config` section:
     
     ```hcl
     resource "yandex_mdb_postgresql_cluster" "<cluster_name>" {
       ...
       config {
         ...
         performance_diagnostics {
           enabled                      = <activate_statistics_collection>
           sessions_sampling_interval   = <session_sampling_interval>
           statements_sampling_interval = <statement_sampling_interval>
         }
         ...
       }
       ...
     }
     ```
     
     Where:
     
     * `enabled`: Enables statistics collection, `true` or `false`.
     * `sessions_sampling_interval`: Session sampling interval, from `5` to `86400` seconds.
     * `statements_sampling_interval`: Statement sampling interval, from `60` to `86400` seconds.


  1. To protect your cluster, its databases, and users against accidental deletion, add the `deletion_protection` field set to `true` to your cluster description:

      ```hcl
      resource "yandex_mdb_postgresql_cluster" "<cluster_name>" {
        ...
        deletion_protection = <protect_cluster_from_deletion>
      }
      ```

      `deletion_protection`: Protection of the cluster, its databases, and users against deletion (`true` or `false`).

      By default, when users and databases are created, this setting’s value is inherited from the cluster. You can also specify this setting manually. See [User management](cluster-users.md) and [Database management](databases.md) for details.

      If the setting is changed on a running cluster, the new value will only be inherited by users and databases with the **Same as cluster** protection level.

      Even with deletion protection enabled, one can still connect to the cluster manually and delete the data.

  1. Make sure the settings 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. Confirm updating the resources.

      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.

      {% note warning "Timeouts" %}
      
      The Terraform provider sets the following timeouts for Managed Service for PostgreSQL cluster operations:
      
      * Creating a cluster, including restoration from a backup: 30 minutes.
      * Updating a cluster: 60 minutes.
      * Deleting a cluster: 15 minutes.
      
      Operations exceeding the timeout are aborted.
      
      {% cut "How can I change these timeouts?" %}
      
      Add a `timeouts` section to the cluster description, e.g.:
      
      ```hcl
      resource "yandex_mdb_postgresql_cluster" "<cluster_name>" {
        ...
        timeouts {
          create = "1h30m" # 1 hour 30 minutes
          update = "2h"    # 2 hours
          delete = "30m"   # 30 minutes
        }
      }
      ```
      
      {% endcut %}
      
      {% endnote %}

- REST API {#api}

  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. Create a file named `body.json` and paste the following code into it:

     {% note warning %}
     
     The API method will assign default values to all the parameters of the object you are modifying unless you explicitly provide them in your request. To avoid this, list the settings you want to change in the `updateMask` parameter as a single comma-separated string.
     
     {% endnote %}

     
     ```json
     {
       "updateMask": "configSpec.poolerConfig,configSpec.backupWindowStart,configSpec.backupRetainPeriodDays,configSpec.access,configSpec.performanceDiagnostics.sessionsSamplingInterval,configSpec.performanceDiagnostics.statementsSamplingInterval,maintenanceWindow,deletionProtection",
       "configSpec": {
         "poolerConfig": {
           "poolingMode": "<connection_pooling_mode>",
           "poolDiscard": <clear_client_states_after_each_transaction>
         },
         "backupWindowStart": {
           "hours": "<hours>",
           "minutes": "<minutes>",
           "seconds": "<seconds>",
           "nanos": "<nanoseconds>"
         },
         "backupRetainPeriodDays": "<number_of_days>",
         "access": {
           "dataLens": <allow_access_from_DataLens>,
           "webSql": <allow_access_from_WebSQL>,
           "serverless": <allow_access_from_Cloud_Functions>,
           "dataTransfer": <allow_access_from_Data_Transfer>,
           "yandexQuery": <allow_access_from_Query>
         },
         "performanceDiagnostics": {
           "enabled": <enable_statistics_collection>,
           "sessionsSamplingInterval": "<session_sampling_interval>",
           "statementsSamplingInterval": "<statement_sampling_interval>"
         }
       },
       "maintenanceWindow": {
         "weeklyMaintenanceWindow": {
           "day": "<day_of_week>",
           "hour": "<hour>"
         }
       },
       "deletionProtection": <protect_cluster_from_deletion>
     }
     ```


     Where:

     * `updateMask`: Comma-separated string of settings to update.
     * `configSpec`: Cluster settings:

       * `poolerConfig`: Connection pooler settings:

         * `poolingMode`: Connection pooler's operation mode. Possible values: `SESSION`, `TRANSACTION`, and `STATEMENT`. To learn more about each mode, see [Managing PostgreSQL connections](../concepts/pooling.md).
         * `poolDiscard`: Defines whether clients should discard their state after each transaction, `true` or `false`. Corresponds to the [server_reset_query_always](https://www.pgbouncer.org/config.html) option for the [PgBouncer](https://www.pgbouncer.org/usage) connection pooler.

       * `backupWindowStart`: [Backup](../concepts/backup.md) window settings.

         Here, specify the backup start time. Allowed values:

         * `hours`: Between `0` and `23` hours.
         * `minutes`: Between `0` and `59` minutes.
         * `seconds`: Between `0` and `59` seconds.
         * `nanos`: Between `0` and `999999999` nanoseconds.

       * `backupRetainPeriodDays`: Number of days to retain the cluster backup. Possible values: between `7` and `60` days.

       
       * `access`: Cluster access settings for the following Yandex Cloud services:

         * `dataLens`: [Yandex DataLens](../../datalens/index.md)
         * `webSql`: [Yandex WebSQL](../../websql/index.md)
         * `serverless`: [Yandex Cloud Functions](../../functions/index.md)
         * `dataTransfer`: [Yandex Data Transfer](../../data-transfer/index.md)
         * `yandexQuery`: [Yandex Query](../../query/index.md)

         The possible values are `true` or `false`.


       
       * `performanceDiagnostics`: [Statistics collection](performance-diagnostics.md#activate-stats-collector) settings:

         * `enabled`: Enables statistics collection, `true` or `false`.
         * `sessionsSamplingInterval`: Session sampling interval. The values range from `1` to `86400` seconds.
         * `statementsSamplingInterval`: Statement sampling interval. The values range from `60` to `86400` seconds.


     * `maintenanceWindow`: [Maintenance](../concepts/maintenance.md) window settings, applying to both running and stopped clusters. Provide one of these two parameters:

       * `anytime`: Maintenance takes place at any time.
       * `weeklyMaintenanceWindow`: Maintenance takes place once a week at the specified time:

         * `day`: Day of week, i.e., `MON`, `TUE`, `WED`, `THU`, `FRI`, `SAT`, or `SUN`.
         * `hour`: UTC hour, 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`.

     * `deletionProtection`: Protection of the cluster, its databases, and users against deletion, `true` or `false` value.

        By default, when users and databases are created, this setting’s value is inherited from the cluster. You can also specify this setting manually. See [User management](cluster-users.md) and [Database management](databases.md) for details.

        If the setting is changed on a running cluster, the new value will only be inherited by users and databases with the **Same as cluster** protection level.

        Even with deletion protection enabled, one can still connect to the cluster manually and delete the data.

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

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

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

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

- gRPC API {#grpc-api}

  1. [Get an IAM token for API authentication](../api-ref/authentication.md) and place it in 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. Create a file named `body.json` and paste the following code into it:

     {% note warning %}
     
     The API method will assign default values to all the parameters of the object you are modifying unless you explicitly provide them in your request. To avoid this, list the settings you want to change in the `update_mask` parameter as an array of `paths[]` strings.
     
     {% cut "Format for listing settings" %}
     
     ```yaml
     "update_mask": {
         "paths": [
             "<setting_1>",
             "<setting_2>",
             ...
             "<setting_N>"
         ]
     }
     ```
     
     {% endcut %}
     
     {% endnote %}

     
     ```json
     {
       "cluster_id": "<cluster_ID>",
       "update_mask": {
         "paths": [
           "config_spec.pooler_config",
           "config_spec.backup_window_start",
           "config_spec.backup_retain_period_days",
           "config_spec.access",
           "config_spec.performance_diagnostics.sessions_sampling_interval",
           "config_spec.performance_diagnostics.statements_sampling_interval",
           "maintenance_window",
           "deletion_protection"
         ]
       },
       "config_spec": {
         "pooler_config": {
           "pooling_mode": "<connection_pooling_mode>",
           "pool_discard": <clear_client_states_after_each_transaction>
         },
         "backup_window_start": {
           "hours": "<hours>",
           "minutes": "<minutes>",
           "seconds": "<seconds>",
           "nanos": "<nanoseconds>"
         },
         "backup_retain_period_days": "<number_of_days>",
         "access": {
           "data_lens": <allow_access_from_DataLens>,
           "web_sql": <allow_access_from_WebSQL>,
           "serverless": <allow_access_from_Cloud_Functions>,
           "data_transfer": <allow_access_from_Data_Transfer>,
           "yandex_query": <allow_access_from_Query>
         },
         "performance_diagnostics": {
           "enabled": <enable_statistics_collection>,
           "sessions_sampling_interval": "<session_sampling_interval>",
           "statements_sampling_interval": "<statement_sampling_interval>"
         }
       },
       "maintenance_window": {
         "weekly_maintenance_window": {
           "day": "<day_of_week>",
           "hour": "<hour>"
         }
       },
       "deletion_protection": <protect_cluster_from_deletion>
     }
     ```


     Where:

     * `update_mask`: List of parameters to update as an array of strings (`paths[]`).
     * `config_spec`: Cluster settings:

       * `pooler_config`: Connection pooler settings:

         * `pooling_mode`: Connection pooler's operation mode. Possible values: `SESSION`, `TRANSACTION`, and `STATEMENT`. To learn more about each mode, see [Managing PostgreSQL connections](../concepts/pooling.md).
         * `pool_discard`: Defines whether clients should discard their state after each transaction, `true` or `false`. Corresponds to the [server_reset_query_always](https://www.pgbouncer.org/config.html) option for the [PgBouncer](https://www.pgbouncer.org/usage) connection pooler.

       * `backup_window_start`: [Backup](../concepts/backup.md) window settings.

         Here, specify the backup start time. Allowed values:

         * `hours`: Between `0` and `23` hours.
         * `minutes`: Between `0` and `59` minutes.
         * `seconds`: Between `0` and `59` seconds.
         * `nanos`: Between `0` and `999999999` nanoseconds.

       * `backup_retain_period_days`: Number of days to retain the cluster backup. Possible values: between `7` and `60` days.

       
       * `access`: Cluster settings for access to the following Yandex Cloud services:

         * `data_lens`: [Yandex DataLens](../../datalens/index.md)
         * `web_sql`: [Yandex WebSQL](../../websql/index.md)
         * `serverless`: [Yandex Cloud Functions](../../functions/index.md)
         * `data_transfer`: [Yandex Data Transfer](../../data-transfer/index.md)
         * `yandex_query`: [Yandex Query](../../query/index.md)

         The possible values are `true` or `false`.


       
       * `performance_diagnostics`: [Statistics collection](performance-diagnostics.md#activate-stats-collector) settings:

         * `enabled`: Enables statistics collection, `true` or `false`.
         * `sessions_sampling_interval`: Session sampling interval. The values range from `1` to `86400` seconds.
         * `statements_sampling_interval`: Statement sampling interval. The values range from `60` to `86400` seconds.


     * `maintenance_window`: [Maintenance window](../concepts/maintenance.md) settings, applying to both running and stopped clusters. Provide one of these two parameters:

       * `anytime`: Maintenance takes place at any time.
       * `weekly_maintenance_window`: Maintenance takes place once a week at the specified time:

         * `day`: Day of week, i.e., `MON`, `TUE`, `WED`, `THU`, `FRI`, `SAT`, or `SUN`.
         * `hour`: UTC hour, 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`.

     * `deletion_protection`: Protection of the cluster, its databases, and users against deletion, `true` or `false` value.

        By default, when users and databases are created, this setting’s value is inherited from the cluster. You can also specify this setting manually. See [User management](cluster-users.md) and [Database management](databases.md) for details.

        If the setting is changed on a running cluster, the new value will only be inherited by users and databases with the **Same as cluster** protection level.

        Even with deletion protection enabled, one can still connect to the cluster manually and delete the data.

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

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

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

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

{% endlist %}


### Connection Manager {#conn-man}

If you cluster has no integration with Connection Manager, enable **Use Connection Manager**. You can only do it in the [management console](https://console.yandex.cloud).

The following resources will be created for each database user:

* [Connection Manager connection](../../metadata-hub/concepts/connection-manager.md) containing database connection details.

* [Yandex Lockbox secret](../../metadata-hub/concepts/secret.md) containing the user password. Yandex Lockbox provides secure storage for passwords.

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. You can [use Connection Manager to configure access to connections](../../metadata-hub/operations/connection-access.md).

{% note info %}

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

{% endnote %}


## Manual master failover {#start-manual-failover}

In a fault-tolerant multi-host Managed Service for PostgreSQL cluster, you can perform a manual failover from the current master host to one of the replicas. Once this operation is complete, the former master host will act as a replica to the new master.

Master failover specifics in Managed Service for PostgreSQL

* A replica with an explicitly defined replication source cannot be promoted to master.
* Unless the replica name for promotion is explicitly specified, the master will fail over to one of the quorum replicas.

To learn more, see [Replication](../concepts/replication.md).

To perform a master failover:

{% list tabs group=instructions %}

- Management console {#console}

  1. Navigate to **Managed Service for&nbsp;PostgreSQL**.
  1. Click the name of your cluster and select the ![icon-hosts.svg](../../_assets/console-icons/cube.svg) **Hosts** tab.
  1. Click ![icon-autofailover.svg](../../_assets/console-icons/shuffle.svg) **Switch master**.
      * To switch the master to one of the quorum replicas, leave the **Choose master host automatically** option enabled.
      * To switch the master to a specific replica, disable the **Choose master host automatically** option and select the required replica from the drop-down list.
  1. Click **Switch**.

- 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.

  Run this command:

  ```bash
  yc managed-postgresql cluster start-failover <cluster_name_or_ID> \
      --host <replica_host_name>
  ```

  You can get the replica name from the [cluster’s host list](hosts.md#list) and the cluster name from the [folder’s cluster list](cluster-list.md#list-clusters).

- Terraform {#tf}

    1. Open the current Terraform configuration file describing your infrastructure.

        For more on how to create this file, see [Creating a cluster](cluster-create.md).

        For a complete list of configurable Managed Service for PostgreSQL cluster fields, see [this Terraform provider guide](../../terraform/resources/mdb_postgresql_cluster.md).

    1. In the `host_master_name` argument, specify the name of the replica you want to promote.

        ```hcl
        resource "yandex_mdb_postgresql_cluster" "<cluster_name>" {
          ...
          host_master_name = "<replica_host_name>"
        }
        ```

        Where `host_master_name` is the name of the replica host, i.e., the `name` attribute of the appropriate `host` section.

    1. Make sure the settings 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. Confirm updating the resources.

        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.

        {% note warning "Timeouts" %}
        
        The Terraform provider sets the following timeouts for Managed Service for PostgreSQL cluster operations:
        
        * Creating a cluster, including restoration from a backup: 30 minutes.
        * Updating a cluster: 60 minutes.
        * Deleting a cluster: 15 minutes.
        
        Operations exceeding the timeout are aborted.
        
        {% cut "How can I change these timeouts?" %}
        
        Add a `timeouts` section to the cluster description, e.g.:
        
        ```hcl
        resource "yandex_mdb_postgresql_cluster" "<cluster_name>" {
          ...
          timeouts {
            create = "1h30m" # 1 hour 30 minutes
            update = "2h"    # 2 hours
            delete = "30m"   # 30 minutes
          }
        }
        ```
        
        {% endcut %}
        
        {% endnote %}

- REST API {#api}

  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.StartFailover](../api-ref/Cluster/startFailover.md) method, e.g., via the following [cURL](https://curl.se/) request:

     ```bash
     curl \
       --request POST \
       --header "Authorization: Bearer $IAM_TOKEN" \
       --header "Content-Type: application/json" \
       --url 'https://mdb.api.cloud.yandex.net/managed-postgresql/v1/clusters/<cluster_ID>:startFailover' \
       --data '{
                 "hostName": "<host_FQDN>"
               }'
     ```

     Where `hostName` is the [FQDN of the replica](connect/fqdn.md) promoted to master.

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

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

- gRPC API {#grpc-api}

  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.StartFailover](../api-ref/grpc/Cluster/startFailover.md) method, e.g., via the following [gRPCurl](https://github.com/fullstorydev/grpcurl) request:

     ```bash
     grpcurl \
       -format json \
       -import-path ~/cloudapi/ \
       -import-path ~/cloudapi/third_party/googleapis/ \
       -proto ~/cloudapi/yandex/cloud/mdb/postgresql/v1/cluster_service.proto \
       -rpc-header "Authorization: Bearer $IAM_TOKEN" \
       -d '{
             "cluster_id": "<cluster_ID>",
             "host_name": "<host_FQDN>"
           }' \
       mdb.api.cloud.yandex.net:443 \
       yandex.cloud.mdb.postgresql.v1.ClusterService.StartFailover
     ```

     Where `host_name` is the [FQDN of the replica](connect/fqdn.md) promoted to master.

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

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

{% endlist %}

## Moving a cluster {#move-cluster}

{% list tabs group=instructions %}

- Management console {#console}

    1. Navigate to **Managed Service for&nbsp;PostgreSQL**.
    1. Click ![image](../../_assets/console-icons/ellipsis.svg) next to the cluster you want to move.
    1. Select **Move**.
    1. Select the destination folder for your cluster.
    1. Click **Move**.

- 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 move a cluster:

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

        ```bash
        yc managed-postgresql cluster move --help
        ```

    1. Specify the destination folder in the cluster move command:

        ```bash
        yc managed-postgresql cluster move <cluster_ID> \
           --destination-folder-name=<destination_folder_name>
        ```

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

- Terraform {#tf}

    1. Open the current Terraform configuration file describing your infrastructure.

        For more on how to create this file, see [Creating a cluster](cluster-create.md).

    1. In the Managed Service for PostgreSQL cluster description, add or update the `folder_id` argument:

        ```hcl
        resource "yandex_mdb_postgresql_cluster" "<cluster_name>" {
          ...
          folder_id = "<destination_folder_ID>"
        }
        ```

    1. Make sure the settings 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. Confirm resource changes.

        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.

    For more information, see [this Terraform provider guide](../../terraform/resources/mdb_postgresql_cluster.md).

    {% note warning "Timeouts" %}
    
    The Terraform provider sets the following timeouts for Managed Service for PostgreSQL cluster operations:
    
    * Creating a cluster, including restoration from a backup: 30 minutes.
    * Updating a cluster: 60 minutes.
    * Deleting a cluster: 15 minutes.
    
    Operations exceeding the timeout are aborted.
    
    {% cut "How can I change these timeouts?" %}
    
    Add a `timeouts` section to the cluster description, e.g.:
    
    ```hcl
    resource "yandex_mdb_postgresql_cluster" "<cluster_name>" {
      ...
      timeouts {
        create = "1h30m" # 1 hour 30 minutes
        update = "2h"    # 2 hours
        delete = "30m"   # 30 minutes
      }
    }
    ```
    
    {% endcut %}
    
    {% endnote %}

- REST API {#api}

  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.Move](../api-ref/Cluster/move.md) method, e.g., via the following [cURL](https://curl.se/) request:

     ```bash
     curl \
       --request POST \
       --header "Authorization: Bearer $IAM_TOKEN" \
       --header "Content-Type: application/json" \
       --url 'https://mdb.api.cloud.yandex.net/managed-postgresql/v1/clusters/<cluster_ID>:move' \
       --data '{
                 "destinationFolderId": "<folder_ID>"
               }'
     ```

     Where `destinationFolderId` is the ID of the target folder for your cluster. You can get it from the [list of your cloud folders](../../resource-manager/operations/folder/get-id.md)

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

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

- gRPC API {#grpc-api}

  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.Move](../api-ref/grpc/Cluster/move.md) method, e.g., via the following [gRPCurl](https://github.com/fullstorydev/grpcurl) request:

     ```bash
     grpcurl \
       -format json \
       -import-path ~/cloudapi/ \
       -import-path ~/cloudapi/third_party/googleapis/ \
       -proto ~/cloudapi/yandex/cloud/mdb/postgresql/v1/cluster_service.proto \
       -rpc-header "Authorization: Bearer $IAM_TOKEN" \
       -d '{
             "cluster_id": "<cluster_ID>",
             "destination_folder_id": "<folder_ID>"
           }' \
       mdb.api.cloud.yandex.net:443 \
       yandex.cloud.mdb.postgresql.v1.ClusterService.Move
     ```

     Where `destination_folder_id` is the ID of the target folder for your cluster. You can get it from the [list of your cloud folders](../../resource-manager/operations/folder/get-id.md)

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

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

{% endlist %}

After the move, the cluster will still use the cloud network from the original folder. To host the cluster in another cloud network, use the [restore from a backup](cluster-backups.md) feature, specifying the target network for the restored cluster.

To move a cluster to a different availability zone, follow [this guide](host-migration.md). Following this procedure, you will move the cluster hosts.


## Updating security groups {#change-sg-set}

{% list tabs group=instructions %}

- Management console {#console}

  1. Navigate to **Managed Service for&nbsp;PostgreSQL**.
  1. Select the cluster and click ![image](../../_assets/console-icons/pencil.svg) **Edit** in the top panel.
  1. Under **Network settings**, select the security groups for cluster network traffic.

- 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 change the list of [security groups](../concepts/network.md#security-groups) for your cluster:

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

      ```bash
      yc managed-postgresql cluster update --help
      ```

  1. Specify the security groups in the cluster update command:

      ```bash
      yc managed-postgresql cluster update <cluster_name_or_ID> \
          --security-group-ids <list_of_security_group_IDs>
      ```

- Terraform {#tf}

  1. Open the current Terraform configuration file describing your infrastructure.

      For more on how to create this file, see [Creating a cluster](cluster-create.md).

      For a complete list of configurable Managed Service for PostgreSQL cluster fields, see [this Terraform provider guide](../../terraform/resources/mdb_postgresql_cluster.md).

  1. Edit the `security_group_ids` value in the cluster description:

      ```hcl
      resource "yandex_mdb_postgresql_cluster" "<cluster_name>" {
        ...
        security_group_ids = [ <list_of_security_group_IDs> ]
      }
      ```

  1. Make sure the settings 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. Confirm updating the resources.

      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.

      {% note warning "Timeouts" %}
      
      The Terraform provider sets the following timeouts for Managed Service for PostgreSQL cluster operations:
      
      * Creating a cluster, including restoration from a backup: 30 minutes.
      * Updating a cluster: 60 minutes.
      * Deleting a cluster: 15 minutes.
      
      Operations exceeding the timeout are aborted.
      
      {% cut "How can I change these timeouts?" %}
      
      Add a `timeouts` section to the cluster description, e.g.:
      
      ```hcl
      resource "yandex_mdb_postgresql_cluster" "<cluster_name>" {
        ...
        timeouts {
          create = "1h30m" # 1 hour 30 minutes
          update = "2h"    # 2 hours
          delete = "30m"   # 30 minutes
        }
      }
      ```
      
      {% endcut %}
      
      {% endnote %}

- REST API {#api}

  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.Update](../api-ref/Cluster/update.md) method, e.g., via the following [cURL](https://curl.se/) request:

     {% note warning %}
     
     The API method will assign default values to all the parameters of the object you are modifying unless you explicitly provide them in your request. To avoid this, list the settings you want to change in the `updateMask` parameter as a single comma-separated string.
     
     {% endnote %}

     ```bash
     curl \
       --request PATCH \
       --header "Authorization: Bearer $IAM_TOKEN" \
       --header "Content-Type: application/json" \
       --url 'https://mdb.api.cloud.yandex.net/managed-postgresql/v1/clusters/<cluster_ID>' \
       --data '{
                 "updateMask": "securityGroupIds",
                 "securityGroupIds": [
                   "<security_group_1_ID>",
                   "<security_group_2_ID>",
                   ...
                   "<security_group_N_ID>"
                 ]
               }'
     ```

     Where:

     * `updateMask`: Comma-separated string of settings to update.

       Here, we provide only one setting.

     * `securityGroupIds`: New [security groups](../concepts/network.md#security-groups), formatted as an array.

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

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

- gRPC API {#grpc-api}

  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.Update](../api-ref/grpc/Cluster/update.md) method, e.g., via the following [gRPCurl](https://github.com/fullstorydev/grpcurl) request:

     {% note warning %}
     
     The API method will assign default values to all the parameters of the object you are modifying unless you explicitly provide them in your request. To avoid this, list the settings you want to change in the `update_mask` parameter as an array of `paths[]` strings.
     
     {% cut "Format for listing settings" %}
     
     ```yaml
     "update_mask": {
         "paths": [
             "<setting_1>",
             "<setting_2>",
             ...
             "<setting_N>"
         ]
     }
     ```
     
     {% endcut %}
     
     {% endnote %}

     ```bash
     grpcurl \
       -format json \
       -import-path ~/cloudapi/ \
       -import-path ~/cloudapi/third_party/googleapis/ \
       -proto ~/cloudapi/yandex/cloud/mdb/postgresql/v1/cluster_service.proto \
       -rpc-header "Authorization: Bearer $IAM_TOKEN" \
       -d '{
             "cluster_id": "<cluster_ID>",
             "update_mask": {
               "paths": [
                 "security_group_ids"
               ]
             },
             "security_group_ids": [
               "<security_group_1_ID>",
               "<security_group_2_ID>",
               ...
               "<security_group_N_ID>"
             ]
           }' \
       mdb.api.cloud.yandex.net:443 \
       yandex.cloud.mdb.postgresql.v1.ClusterService.Update
     ```

     Where:

     * `update_mask`: List of settings you want to update as an array of strings (`paths[]`).

       Here, we provide only one setting.

     * `security_group_ids`: New [security groups](../concepts/network.md#security-groups), formatted as an array.

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

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

{% endlist %}

{% note warning %}

You may need to additionally [configure security groups](connect/index.md#configuring-security-groups) to connect to the cluster.

{% endnote %}