All Products
Search
Document Center

ApsaraDB RDS:Use Terraform to restore the data of an ApsaraDB RDS for PostgreSQL instance

Last Updated:Feb 10, 2025

This topic describes how to use Terraform to restore an ApsaraDB RDS for PostgreSQL instance.

Note

You can run the sample code in this topic with a few clicks. For more information, visit Terraform Explorer.

Prerequisites

  • An RDS instance is created. For more information, see Create an RDS instance.

  • The RDS instance is in the Running state. You can use one of the following methods to check whether the RDS instance is in the Running state:

    • Check the value of the status parameter by following the instructions provided in Query instance details. If the value is Running, the RDS instance is in the Running state.

    • Log on to the ApsaraDB RDS console, switch to the required region, find the RDS instance, and then check the instance status.

  • An Alibaba Cloud account has all permissions on resources within the account. If an Alibaba Cloud account is leaked, the resources are exposed to major risks. We recommend that you use a Resource Access Management (RAM) user and create an AccessKey pair for the RAM user. For more information, see Create a RAM user and Create an AccessKey pair.

  • You must use RAM to manage access permissions on cloud resources in an efficient manner. This helps meet the requirements for multi-user collaboration and allows you to grant permissions to users based on the principle of least privilege (PoLP) to prevent security vulnerabilities caused by excessive permissions. For more information, see Grant permissions to RAM users.

    {
        "Version": "1",
        "Statement": [
            {
                "Effect": "Allow",
                "Action": [
                    "vpc:DescribeVpcAttribute",
                    "vpc:DescribeRouteTableList",
                    "vpc:DescribeVSwitchAttributes",
                    "vpc:DeleteVpc",
                    "vpc:DeleteVSwitch",
                    "vpc:CreateVpc",
                    "vpc:CreateVSwitch"
                ],
                "Resource": "*"
            },
            {
                "Action": "rds:*",
                "Resource": "*",
                "Effect": "Allow"
            },
            {
                "Action": "dbs:*",
                "Resource": "acs:rds:*:*:*",
                "Effect": "Allow"
            },
            {
                "Action": "hdm:*",
                "Resource": "acs:rds:*:*:*",
                "Effect": "Allow"
            },
            {
                "Action": "dms:LoginDatabase",
                "Resource": "acs:rds:*:*:*",
                "Effect": "Allow"
            },
            {
                "Effect": "Allow",
                "Action": "ram:CreateServiceLinkedRole",
                "Resource": "*",
                "Condition": {
                    "StringEquals": {
                        "ram:ServiceName": [
                            "backupencryption.rds.aliyuncs.com"
                        ]
                    }
                }
            },
            {
                "Effect": "Allow",
                "Action": "bss:ModifyAgreementRecord",
                "Resource": "*"
            },
            {
                "Effect": "Allow",
                "Action": [
                    "bss:DescribeOrderList",
                    "bss:DescribeOrderDetail",
                    "bss:PayOrder",
                    "bss:CancelOrder"
                ],
                "Resource": "*"
            }
        ]
    }
  • The runtime environment for Terraform is prepared by using one of the following methods:

    • Use Terraform in Cloud Shell: Terraform is preinstalled in Cloud Shell and identity credentials are configured. You can run Terraform commands in Cloud Shell. For more information, see Use Terraform in Cloud Shell. This method is suitable for scenarios in which you want to use and debug Terraform in a fast and convenient manner at low costs.

    • Install and configure Terraform on your on-premises machine: This method is suitable for scenarios in which network conditions are poor or a custom development environment is used. For more information, see Install and configure Terraform in the local PC.

Resources

Note

In this example, fees may be generated for specific resources. You must release or unsubscribe from the resources when you no longer require them.

Restore an RDS instance by point in time

  1. Create a working directory and a file named main.tf in the directory. Copy the following content to the main.tf file:

    • Create the required resources.

      variable "region" {
        default = "cn-heyuan"
      }
      
      provider "alicloud" {
        region = var.region
      }
      
      variable "zone_id" {
        default = "cn-heyuan-b"
      }
      
      variable "instance_type" {
        default = "pg.n2.2c.2m"
      }
      
      # Create a VPC.
      resource "alicloud_vpc" "main" {
        vpc_name   = "alicloud"
        cidr_block = "172.16.0.0/16"
      }
      
      # Create a vSwitch.
      resource "alicloud_vswitch" "main" {
        vpc_id     = alicloud_vpc.main.id
        cidr_block = "172.16.192.0/20"
        zone_id    = var.zone_id
      }
      
      # Create an RDS instance.
      resource "alicloud_db_instance" "instance" {
        engine               = "PostgreSQL"
        engine_version       = "13.0"
        instance_type        = var.instance_type
        instance_storage     = "30"
        instance_charge_type = "Postpaid"
        vswitch_id           = alicloud_vswitch.main.id
      }
      
      # Create a backup file.
      resource "alicloud_rds_backup" "instance" {
        db_instance_id    = alicloud_db_instance.instance.id
        remove_from_state = true
      }
      
      # Query backup files.
      data "alicloud_rds_backups" "example" {
        db_instance_id = alicloud_db_instance.instance.id
        depends_on     = [alicloud_rds_backup.instance]
      }
    • In the main.tf file, add the resource "alicloud_rds_clone_db_instance" "clone_time" {} configuration item and configure the configuration item based on the following code snippet:

      # Restore an instance by point in time.
      resource "alicloud_rds_clone_db_instance" "clone_time" {
        source_db_instance_id    = alicloud_db_instance.instance.id
        db_instance_description  = "terraform-test-clone"
        db_instance_storage_type = "cloud_essd"
        payment_type             = "PayAsYouGo"
        # Obtain the value of the backup_end_time parameter in the query result. 
        restore_time             = data.alicloud_rds_backups.example.backups.0.backup_end_time
        db_instance_storage      = "50"
      }
    Note

    To obtain the value of the restore_time field, perform the following steps:

    1. In the terraform.tf file, add the data "alicloud_rds_backups" "example" { db_instance_id = alicloud_db_instance.instance.id} configuration item to query backup files.

    2. Run the terraform apply command.

    3. Run the terraform show command to query information about backup files and obtain the value of the backup_end_time parameter in the query result.

    For more information, see Use Terraform to manage the backup files of an ApsaraDB RDS for PostgreSQL instance.

  2. Run the following command to initialize Terraform:

    terraform init

    If the following information is returned, Terraform is initialized:

    Initializing the backend...
    
    Initializing provider plugins...
    - Checking for available provider plugins...
    - Downloading plugin for provider "alicloud" (hashicorp/alicloud) 1.90.1...
    ...
    
    You may now begin working with Terraform. Try running "terraform plan" to see
    any changes that are required for your infrastructure. All Terraform commands
    should now work.
    
    If you ever set or change modules or backend configuration for Terraform,
    rerun this command to reinitialize your working directory. If you forget, other
    commands will detect it and remind you to do so if necessary.
  3. Create an execution plan and preview the changes.

    terraform plan
  4. Run the following command to create the resources:

    terraform apply

    During the execution, enter yes as prompted and press the Enter key. Wait until the command is executed. If the following information appears, the operation is successful.

    alicloud_rds_clone_db_instance.example: Creating...
    alicloud_rds_clone_db_instance.example: Still creating... [10s elapsed]
    ...
    alicloud_rds_clone_db_instance.example: Still creating... [24m11s elapsed]
    alicloud_rds_clone_db_instance.example: Creation complete after 24m34s [id=pgm-****]
    
    Apply complete!  Resources: 1 added, 0 changed, 0 destroyed.
  5. Verify the result.

    Run the terraform show command

    Run the following command to view the restoration of the RDS instance:

    terraform show
    ...
    # alicloud_rds_clone_db_instance.example:
    resource "alicloud_rds_clone_db_instance" "example" {
        category                 = "HighAvailability"
        connection_string        = "pgm-****.pg.rds.aliyuncs.com"
        db_instance_class        = "pg.n2.2c.2m"
        db_instance_storage      = 50
        db_instance_storage_type = "cloud_essd"
        deletion_protection      = false
        engine                   = "PostgreSQL"
        engine_version           = "13.0"
        ha_mode                  = "RPO"
        id                       = "pgm-****"
        instance_network_type    = "VPC"
        maintain_time            = "18:00Z-22:00Z"
        payment_type             = "PayAsYouGo"
        port                     = "5432"
        private_ip_address       = "192.168.XX.XX"
        restore_time             = "2022-09-29T04:32:59Z"
        security_ips             = [
            "0.0.0.0/0",
        ]
        source_db_instance_id    = "pgm-****"
        sync_mode                = "Async"
        tcp_connection_type      = "LONG"
        vswitch_id               = "vsw-****"
        zone_id                  = "cn-hangzhou-j"
    }

    Log on to the ApsaraDB RDS console

    Log on to the ApsaraDB RDS console to view the restoration of the RDS instance.恢复实例

Restore an RDS instance by backup file

  1. In the main.tf file, add the resource "alicloud_rds_clone_db_instance" "clone_id" {} configuration item and configure the configuration item based on the following code snippet:

    ...
    resource "alicloud_rds_clone_db_instance" "clone_id" {
      db_instance_description  = "terraform-test-clone-1"
      source_db_instance_id    = alicloud_db_instance.instance.id
      db_instance_storage_type = "cloud_essd"
      payment_type             = "PayAsYouGo"
      # Obtain the value of the backup_id parameter in the query result. 
      backup_id                = data.alicloud_rds_backups.example.backups.0.backup_id
      db_instance_storage      = "50"
    }         
    Note

    To obtain the value of the backup_id field, perform the following steps:

    • In the terraform.tf file, add the data "alicloud_rds_backups" "querybackups" {db_instance_id = alicloud_db_instance.instance.id} configuration item to query backup files.

    • Run the terraform apply command.

    • Run the terraform show command to query information about backup files and obtain the value of the backup_id parameter in the query result.

    For more information, see Use Terraform to manage the backup files of an ApsaraDB RDS for PostgreSQL instance.

  2. Run the following command:

    terraform apply

    During the execution, enter yes as prompted and press the Enter key. Wait until the command is executed. If the following information appears, the operation is successful.

    alicloud_rds_clone_db_instance.example: Creating...
    alicloud_rds_clone_db_instance.example: Still creating... [10s elapsed]
    ...
    alicloud_rds_clone_db_instance.example: Still creating... [19m31s elapsed]
    alicloud_rds_clone_db_instance.example: Creation complete after 19m39s [id=pgm-bp1sox718o31j940]
    
    Apply complete!  Resources: 1 added, 0 changed, 0 destroyed.
  3. Verify the result.

    Run the terraform show command

    Run the following command to view the restoration of the RDS instance:

    terraform show
    ...
    # alicloud_rds_clone_db_instance.example:
    resource "alicloud_rds_clone_db_instance" "example" {
        backup_id                = "1499356764"
        category                 = "HighAvailability"
        connection_string        = "pgm-****.pg.rds.aliyuncs.com"
        db_instance_class        = "pg.n2.2c.2m"
        db_instance_storage      = 50
        db_instance_storage_type = "cloud_essd"
        deletion_protection      = false
        engine                   = "PostgreSQL"
        engine_version           = "13.0"
        ha_mode                  = "RPO"
        id                       = "pgm-****"
        instance_network_type    = "VPC"
        maintain_time            = "18:00Z-22:00Z"
        payment_type             = "PayAsYouGo"
        port                     = "5432"
        private_ip_address       = "192.168.XX.XX"
        security_ips             = [
            "0.0.0.0/0",
        ]
        source_db_instance_id    = "pgm-****"
        sync_mode                = "Async"
        tcp_connection_type      = "LONG"
        vswitch_id               = "vsw-****"
        zone_id                  = "cn-hangzhou-j"
    }

    Log on to the ApsaraDB RDS console

    Log on to the ApsaraDB RDS console to view the restoration of the RDS instance.按备份集恢复

Clear resources

If you no longer require the preceding resources that are created or managed by using Terraform, run the following command to release the resources. For more information about the terraform destroy command, see Common commands.

terraform destroy

Sample code

Note

You can run the sample code in this topic with a few clicks. For more information, visit Terraform Explorer.

Sample code

variable "region" {
  default = "cn-heyuan"
}

variable "zone_id" {
  default = "cn-heyuan-b"
}

variable "instance_type" {
  default = "pg.n2.2c.2m"
}

provider "alicloud" {
  region = var.region
}

# Create a VPC.
resource "alicloud_vpc" "main" {
  vpc_name   = "alicloud"
  cidr_block = "172.16.0.0/16"
}

# Create a vSwitch.
resource "alicloud_vswitch" "main" {
  vpc_id     = alicloud_vpc.main.id
  cidr_block = "172.16.192.0/20"
  zone_id    = var.zone_id
}

# Create an RDS instance.
resource "alicloud_db_instance" "instance" {
  engine               = "PostgreSQL"
  engine_version       = "13.0"
  instance_type        = var.instance_type
  instance_storage     = "30"
  instance_charge_type = "Postpaid"
  vswitch_id           = alicloud_vswitch.main.id
}

# Create a backup file.
resource "alicloud_rds_backup" "instance" {
  db_instance_id    = alicloud_db_instance.instance.id
  remove_from_state = true
}

# Query backup files.
data "alicloud_rds_backups" "example" {
  db_instance_id = alicloud_db_instance.instance.id
  depends_on     = [alicloud_rds_backup.instance]
}

# Restore an instance by point in time.
resource "alicloud_rds_clone_db_instance" "clone_time" {
  source_db_instance_id    = alicloud_db_instance.instance.id
  db_instance_description  = "terraform-test-clone"
  db_instance_storage_type = "cloud_essd"
  payment_type             = "PayAsYouGo"
  # Obtain the value of the backup_end_time parameter in the query result. 
  restore_time             = data.alicloud_rds_backups.example.backups.0.backup_end_time
  db_instance_storage      = "50"
}

# Restore an RDS instance by backup file.
resource "alicloud_rds_clone_db_instance" "clone_id" {
  db_instance_description  = "terraform-test-clone-1"
  source_db_instance_id    = alicloud_db_instance.instance.id
  db_instance_storage_type = "cloud_essd"
  payment_type             = "PayAsYouGo"
  # Obtain the value of the backup_id parameter in the query result. 
  backup_id                = data.alicloud_rds_backups.example.backups.0.backup_id
  db_instance_storage      = "50"
}

To view more examples, visit GitHub.

References

  • For more information about Terraform, see What is Terraform?

  • Terraform is available as a managed service in Resource Orchestration Service (ROS). You can create Terraform templates to define ApsaraDB RDS resources, specify resource parameters, and configure dependency relationships for resources. For more information, see Create a Terraform template.