[Yandex Cloud documentation](../../index.md) > [Yandex Data Transfer](../index.md) > [Tutorials](index.md) > Migration > Migrating data from AWS RDS for PostgreSQL

# Migrating data from AWS RDS for PostgreSQL to Yandex Managed Service for PostgreSQL

To set up data transfers from [Amazon RDS for PostgreSQL](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/CHAP_PostgreSQL.html) to Managed Service for PostgreSQL databases using Data Transfer:

1. [Prepare your test data](#prepare-data).
1. [Prepare and activate the transfer](#prepare-transfer).
1. [Test the transfer](#verify-transfer).

If you no longer need the resources you created, [delete them](#clear-out).

Data transfers are supported for PostgreSQL starting with version 9.4. Make sure the PostgreSQL version in Managed Service for PostgreSQL is not older than the PostgreSQL version in Amazon RDS.

{% note info %}

Use of Amazon services is not part of the [Yandex Cloud Terms of Use](https://yandex.ru/legal/cloud_termsofuse/?lang=en) and is governed by a separate arrangement between the client and Amazon. Yandex is not responsible for the relationship between Amazon and the client arising in connection with the client's use of Amazon products or services.

{% endnote %}


## Required paid resources {#paid-resources}

* Managed Service for PostgreSQL cluster: computing resources allocated to hosts along with storage and backup capacity (see [Managed Service for PostgreSQL pricing](../../managed-postgresql/pricing.md)).
* Public IP addresses if public access is enabled for cluster hosts (see [Virtual Private Cloud pricing](../../vpc/pricing.md)).
* Each transfer: use of computing resources and the number of transferred data rows (see [Data Transfer pricing](../pricing.md)).
* NAT gateway: hourly use of the gateway and its outgoing traffic (see [Virtual Private Cloud pricing](../../vpc/pricing.md#nat-gateways)).


## Getting started {#before-you-begin}

Set up your infrastructure:

{% list tabs group=instructions %}

- Manually {#manual}

    1. If you do not have an AWS account, [create](https://aws.amazon.com) one.
    1. In Amazon RDS, [create a group of parameters](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_WorkingWithDBInstanceParamGroups.html) and set its `rds.logical_replication` parameter to `1`. You can leave the other parameters at their defaults.
    1. [Create an instance of Amazon RDS for PostgreSQL](https://aws.amazon.com/ru/getting-started/hands-on/create-connect-postgresql-db/) (source cluster).

        When creating an instance, configure it as required:

        * Enable public access for the instance.
        * In the instance's security group, add a rule which allows incoming TCP traffic from any IP address to the PostgreSQL instance port (`5432` by default).
        * Assign the instance the parameter group you created earlier.

        {% note info %}

        If you changed the parameter group of the created instance, restart the instance for the changes to take effect. While restarting, the instance will be unavailable.

        {% endnote %}

    1. [Create a Managed Service for PostgreSQL target cluster](../../managed-postgresql/operations/cluster-create.md#create-cluster) in any suitable configuration with publicly available hosts and the following settings:

        * **DB name**: `mpg_db`.
        * **Username**: `mpg_user`.
        * **Password**: `<target_password>`.

        {% note info %}
        
        Public access to cluster hosts is required if you plan to connect to the cluster via the internet. This connection option is simpler and is recommended for the purposes of this guide. You can connect to non-public hosts as well but only from Yandex Cloud virtual machines located in the same cloud network as the cluster.
        
        {% endnote %}

    1. Make sure that the Managed Service for PostgreSQL cluster's security group has been [set up correctly](../../managed-postgresql/operations/connect/index.md#configuring-security-groups) and allows connecting to the cluster from the internet.
    1. Set up an egress [NAT gateway](../../vpc/operations/create-nat-gateway.md) for the subnet that hosts the target cluster.
    1. [Download an AWS certificate](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.SSL.html#UsingWithRDS.SSL.RegionCertificates) for the region where the Amazon RDS for PostgreSQL instance resides.

- 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. Set up the [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html). The AWS provider for Terraform uses the AWS CLI configuration to access the service.
    1. [Configure the Terraform provider](../../tutorials/infrastructure-management/terraform-quickstart.md#configure-provider). There is no need to create a provider configuration file manually, you can [download](https://github.com/yandex-cloud-examples/yc-terraform-provider-settings/blob/main/provider.tf) and save it to a separate working directory.
    1. Edit the `provider.tf` file:

        * [Specify the parameter values](../../tutorials/infrastructure-management/terraform-quickstart.md#configure-provider) for the `yandex` provider. If you have not added the authentication credentials to environment variables, specify them in the configuration file.
        * Add the `aws` provider to `required_providers`:

            ```hcl
            required_providers {
              ...
              aws = {
                source  = "hashicorp/aws"
                version = ">= 3.70"
              }
            }
            ```

        * Add a description for the `aws` provider. In the parameters, specify the region where the Amazon RDS for PostgreSQL instance will reside (`eu-north-1` in this example):

            ```hcl
            provider "aws" {
              region = "eu-north-1"
            }
            ```

    1. Download the [rds-pg-mpg.tf](https://github.com/yandex-cloud-examples/yc-data-transfer-postgresql-from-aws-rds/blob/main/rds-pg-mpg.tf) configuration file to the same working directory.

        This file describes:

        * Infrastructure required for the Amazon RDS for PostgreSQL instance to run:

            * Subnet group
            * Security group rule
            * Parameter group

            The instance will use the default network, subnets, and security group.

        * Amazon RDS for PostgreSQL instance (source cluster).
        * Infrastructure required for the Managed Service for PostgreSQL target cluster to run:

            * [Network](../../vpc/concepts/network.md#network) and [subnet](../../vpc/concepts/network.md#subnet)
            * Egress [NAT gateway](../../vpc/operations/create-nat-gateway.md) for the cluster
            * [Security group](../../vpc/concepts/security-groups.md)

        * Managed Service for PostgreSQL target cluster.
        * Source and target endpoints.
        * Transfer.

    1. [Download an AWS certificate](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.SSL.html#UsingWithRDS.SSL.RegionCertificates) for the region where the Amazon RDS for PostgreSQL instance will reside.
    1. In `rds-pg-mpg.tf`, specify the following:

        * PostgreSQL versions for Amazon RDS for PostgreSQL and Managed Service for PostgreSQL.
        * Parameter family for the Amazon RDS [parameter group](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_WorkingWithDBInstanceParamGroups.html).
        * Path to the previously downloaded AWS certificate.
        * Amazon RDS for PostgreSQL and Managed Service for PostgreSQL user passwords.

    1. Run the `terraform init` command in the directory with the configuration file. This command initializes the provider specified in the configuration files and enables you to use its resources and data sources.
    1. Validate your Terraform configuration files using this command:

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

{% endlist %}

## Prepare your test data {#prepare-data}

1. Install `psql`:

    ```bash
    sudo apt update && sudo apt install --yes postgresql-client
    ```

1. Connect to the database in the Amazon RDS for PostgreSQL source cluster:

    ```bash
    psql "host=<host_URL> \
    port=<PostgreSQL_port> \
    sslmode=verify-full \
    sslrootcert=<path_to_certificate_file> \
    dbname=<DB_name> \
    user=<username>"
    ```

    The default PostgreSQL port is `5432`.

    {% note info %}

    It may take up to an hour after creating the instance for a connection to the instance over the internet to be available.

    {% endnote %}

1. Populate the database with test data. In this example, we will use a simple table with car sensor information.

    Create a table:

    ```sql
    CREATE TABLE measurements (
        device_id varchar(200) NOT NULL,
        datetime timestamp NOT NULL,
        latitude real NOT NULL,
        longitude real NOT NULL,
        altitude real NOT NULL,
        speed real NOT NULL,
        battery_voltage real,
        cabin_temperature real NOT NULL,
        fuel_level real,
        PRIMARY KEY (device_id)
    );
    ```

    Populate the table with data:

    ```sql
    INSERT INTO measurements VALUES
    ('iv9a94th6rztooxh5ur2', '2022-06-05 17:27:00', 55.70329032, 37.65472196,  427.5,    0, 23.5, 17, NULL),
    ('rhibbh3y08qmz3sdbrbu', '2022-06-06 09:49:54', 55.71294467, 37.66542005, 429.13, 55.5, NULL, 18, 32);
    ```

## Prepare and activate a transfer {#prepare-transfer}

{% list tabs group=instructions %}

- Manually {#manual}

    1. [Create a `PostgreSQL`-type source endpoint](../operations/endpoint/source/mysql.md) and configure it using the following settings:

        * **Installation type**: `Custom installation`.
        * **Host**: Host URL.
        * **Port**: `5432`.
        * **CA certificate**: Select the AWS certificate file.
        * **Database**: `postgres`.
        * **User**: `postgres`.
        * **Password**: `<user_password>`.

    1. [Create a `PostgreSQL` target endpoint](../operations/endpoint/target/postgresql.md) with these cluster connection settings:

        * **Installation type**: `Managed Service for PostgreSQL cluster`.
        * **Managed Service for PostgreSQL cluster**: `<target_cluster_name>` from the drop-down list.
        * **Database**: `mpg_db`.
        * **User**: `mpg_user`.
        * **Password**: `<user_password>`.

    1. [Create a transfer](../operations/transfer.md#create) of the **_Snapshot and replication_**-type that will use the endpoints you created.
    1. [Activate the transfer](../operations/transfer.md#activate) and wait for its status to change to **Replicating**.

- Terraform {#tf}

    1. In the `rds-pg-mpg.tf` file, set `transfer_enabled` to `1`.

    1. Validate your Terraform configuration files using this command:

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

    1. The transfer will be activated automatically. Wait for its status to change to **Replicating**.

{% endlist %}

## Test the transfer {#verify-transfer}

Make sure the transfer works correctly by testing copying and replication.

### Test copying {#verify-copy}

1. [Connect to the Managed Service for PostgreSQL target cluster database](../../managed-postgresql/operations/connect/index.md).
1. Run this query:

    ```sql
    SELECT * FROM measurements;
    ```

### Test replication {#verify-replication}

1. Connect to the database in the Amazon RDS for PostgreSQL source cluster:

    ```bash
    psql "host=<host_URL> \
    port=<PostgreSQL_port> \
    sslmode=verify-full \
    sslrootcert=<path_to_certificate_file> \
    dbname=<DB_name> \
    user=<username>"
    ```

    The default PostgreSQL port is `5432`.

1. Populate the `measurements` table with data:

    ```sql
    INSERT INTO measurements VALUES
    ('iv7b74th678tooxdagrf', '2020-06-08 17:45:00', 53.70987913, 36.62549834, 378.0, 20.5, 5.3, 20, NULL);
    ```

1. Check that the added row appears in the target database:

    1. [Connect to the Managed Service for PostgreSQL target cluster database](../../managed-postgresql/operations/connect/index.md).
    1. Run this query:

        ```sql
        SELECT * FROM measurements;
        ```

    {% note info %}

    It may take a few minutes to replicate the data.

    {% endnote %}

## Delete the resources you created {#clear-out}

{% note info %}

Before deleting any resources, [deactivate the transfer](../operations/transfer.md#deactivate).

{% endnote %}

To reduce the consumption of resources, delete those you do not need:

{% list tabs group=instructions %}

- Manually {#manual}

    1. [Delete the transfer](../operations/transfer.md#delete).
    1. [Delete the endpoints](../operations/endpoint/index.md#delete).
    1. [Delete the Amazon RDS for PostgreSQL instance](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_DeleteInstance.html).
    1. [Delete the Managed Service for PostgreSQL cluster](../../managed-postgresql/operations/cluster-delete.md).
    1. [Delete the route table](../../vpc/operations/delete-route-table.md).
    1. [Delete the NAT gateway](../../vpc/operations/delete-nat-gateway.md).

- Terraform {#tf}

    1. In the terminal window, go to the directory containing the infrastructure plan.
    
        {% note warning %}
    
        Make sure the directory has no Terraform manifests with the resources you want to keep. Terraform deletes all resources that were created using the manifests in the current directory.
    
        {% endnote %}
    
    1. Delete resources:
    
        1. Run this command:
    
            ```bash
            terraform destroy
            ```
    
        1. Confirm deleting the resources and wait for the operation to complete.
    
        All the resources described in the Terraform manifests will be deleted.

{% endlist %}