All Products
Search
Document Center

ApsaraDB RDS:Use Terraform to manage backup files

Last Updated:Jan 26, 2025

This topic describes how to use Terraform to create backup files, view backup files, and delete backup files of an ApsaraDB RDS for PostgreSQL instance. This topic also describes how to modify the backup settings of 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": "*"
            }
        ]
    }
  • Prepare the Terraform environment. You can use one of the following methods to use Terraform:

    • Use Terraform in Terraform Explorer: Alibaba Cloud provides Terraform Explorer, an online runtime environment for Terraform. You can use Terraform after you log on to Terraform Explorer without the need to install Terraform. For more information, see Use Terraform in Terraform Explorer. This method is suitable for scenarios in which you want to use and debug Terraform in a fast and convenient manner at no additional cost.

    • Use Terraform in Cloud Shell: Terraform is preinstalled in Cloud Shell and identity credentials are configured. You can directly 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 cost.

    • 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

You are charged for specific resources. If you no longer require the resources, you must release or unsubscribe from the resources at the earliest opportunity.

Create a backup file

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

    • Create the required resources.

      variable "region" {
        default = "cn-shenzhen"
      }
      
      variable "zone_id" {
        default = "cn-shenzhen-c"
      }
      
      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
      }
    • In the main.tf file, add the resource "alicloud_rds_backup" "instance" {} configuration item and configure the configuration item based on the following code snippet:

      ...
      resource "alicloud_rds_backup" "instance" {
        db_instance_id = alicloud_db_instance.instance.id
        remove_from_state = true
      } 
  2. Run the following command to initialize the runtime environment for 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 successfully executed. If the following information appears, the operation is successful:

    alicloud_rds_backup.instance: Creating...
    alicloud_rds_backup.instance: Still creating... [10s elapsed]
    alicloud_rds_backup.instance: Still creating... [20s elapsed]
    ...
    alicloud_rds_backup.instance: Still creating... [4m30s elapsed]
    alicloud_rds_backup.instance: Creation complete after 4m33s [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 created backup file:

    terraform show
    ...
    # alicloud_rds_backup.instance:
    resource "alicloud_rds_backup" "instance" {
        backup_id         = "149xxxxxx"
        backup_method     = "Snapshot"
        backup_type       = "FullBackup"
        db_instance_id    = "pgm-****"
        id                = "pgm-****:****"
        remove_from_state = true
        store_status      = "Enabled"
    }

    Log on to the ApsaraDB RDS console

    Log on to the ApsaraDB RDS console to view the created backup file.备份

View backup files

  1. In the main.tf file, add the data "alicloud_rds_backups" "querybackups" {} configuration item and configure the configuration item based on the following code snippet:

    ...
    data "alicloud_rds_backups" "querybackups" {
      db_instance_id = alicloud_db_instance.instance.id
    }  
  2. Run the following command:

    terraform apply

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

    alicloud_db_instance.instance: Refreshing state... [id=pgm-****]
    alicloud_rds_backup.instance: Refreshing state... [id=pgm-****:14985****]
    data.alicloud_rds_backups.querybackups: Reading...
    data.alicloud_rds_backups.querybackups: Read complete after 0s [id=52064****]
    
    No changes. Your infrastructure matches the configuration.
    
    Terraform has compared your real infrastructure against your configuration and found no differences, so no changes are
    needed.
    
    Apply complete!  Resources: 0 added, 0 changed, 0 destroyed.
  3. Verify the result.

    Run the terraform show command

    Run the following command to view the backup files:

    terraform show
    # data.alicloud_rds_backups.querybackups:
    data "alicloud_rds_backups" "querybackups" {
        backups        = [
            {
                backup_download_url          = ""
                backup_end_time              = "2022-09-29T04:10:15Z"
                backup_id                    = "1498535549"
                backup_initiator             = "User"
                backup_intranet_download_url = ""
                backup_method                = "Snapshot"
                backup_mode                  = "Manual"
                backup_size                  = "53687091200"
                backup_start_time            = "2022-09-29T04:08:34Z"
                backup_status                = "Success"
                backup_type                  = "FullBackup"
                consistent_time              = "1664424514"
                copy_only_backup             = ""
                db_instance_id               = "pgm-****"
                encryption                   = jsonencode({})
                host_instance_id             = "22839235"
                id                           = "pgm-****:1498535549"
                is_avail                     = 1
                meta_status                  = ""
                storage_class                = "0"
                store_status                 = "Enabled"
            },
            {
                backup_download_url          = ""
                backup_end_time              = "2022-09-29T02:55:24Z"
                backup_id                    = "1498486764"
                backup_initiator             = "User"
                backup_intranet_download_url = ""
                backup_method                = "Snapshot"
                backup_mode                  = "Manual"
                backup_size                  = "53687091200"
                backup_start_time            = "2022-09-29T02:50:24Z"
                backup_status                = "Success"
                backup_type                  = "FullBackup"
                consistent_time              = "0"
                copy_only_backup             = ""
                db_instance_id               = "pgm-****"
                encryption                   = jsonencode({})
                host_instance_id             = "22839234"
                id                           = "pgm-****:1498486764"
                is_avail                     = 1
                meta_status                  = ""
                storage_class                = "0"
                store_status                 = "Enabled"
            },
        ]
        db_instance_id = "pgm-****"
        id             = "520646901"
        ids            = [
            "pgm-****:1498535549",
            "pgm-****:1498486764",
        ]
    }

Modify backup settings

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

    ...
    resource "alicloud_db_backup_policy" "instance" {
      instance_id = alicloud_db_instance.instance.id
      preferred_backup_time = "00:00Z-01:00Z"
    }        
  2. Run the following command:

    terraform apply

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

    alicloud_db_backup_policy.instance: Creating...
    alicloud_db_backup_policy.instance: Creation complete after 2s [id=pgm-****]
    
    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 backup settings:

    terraform show
    # alicloud_db_backup_policy.instance:
    resource "alicloud_db_backup_policy" "instance" {
        archive_backup_keep_count       = 1
        archive_backup_keep_policy      = "ByMonth"
        archive_backup_retention_period = 0
        backup_period                   = [
            "Friday",
            "Monday",
            "Saturday",
            "Sunday",
            "Thursday",
            "Tuesday",
            "Wednesday",
        ]
        backup_retention_period         = 7
        backup_time                     = "00:00Z-01:00Z"
        compress_type                   = "1"
        enable_backup_log               = true
        high_space_usage_protection     = "Enable"
        id                              = "pgm-****"
        instance_id                     = "pgm-****"
        local_log_retention_hours       = 0
        local_log_retention_space       = 30
        log_backup                      = true
        log_backup_retention_period     = 7
        log_retention_period            = 7
        preferred_backup_period         = [
            "Friday",
            "Monday",
            "Saturday",
            "Sunday",
            "Thursday",
            "Tuesday",
            "Wednesday",
        ]
        preferred_backup_time           = "00:00Z-01:00Z"
        released_keep_policy            = "None"
        retention_period                = 7
    }
    ...

    Log on to the ApsaraDB RDS console

    Log on to the ApsaraDB RDS console to view the backup settings.备份设置

Delete backup files

  1. In the main.tf file, delete the resource "alicloud_rds_backup" "instance" {} configuration item. In this example, the following information is deleted:

    ...
    resource "alicloud_rds_backup" "instance" {
      db_instance_id = alicloud_db_instance.instance.id
      remove_from_state = true
    } 
  2. Run the following command:

    terraform apply

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

    alicloud_rds_backup.instance: Destroying... [id=pgm-****:1498535549]
    alicloud_rds_backup.instance: Destruction complete after 0s
    
    Apply complete!  Resources: 0 added, 0 changed, 1 destroyed.
  3. Verify the result.

    Run the terraform show command

    Run the following command to check whether backup files are deleted:

    terraform show
    ...
    # data.alicloud_rds_backups.querybackups:
    data "alicloud_rds_backups" "querybackups" {
        backups        = []
        db_instance_id = "pgm-****"
        id             = "0"
        ids            = []
    }

    Log on to the ApsaraDB RDS console

    Log on to the RDS console.删除备份

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

Complete 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-shenzhen"
}

variable "zone_id" {
  default = "cn-shenzhen-c"
}

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

variable "target_minor_version" {
  default = "rds_postgres_1300_20240830"
}

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
}

resource "alicloud_security_group" "example" {
  name   = "terraform-example"
  vpc_id = alicloud_vpc.main.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
}

# Modify backup settings.
#resource "alicloud_db_backup_policy" "instance" {
#  instance_id           = alicloud_db_instance.instance.id
#  preferred_backup_time = "00:00Z-01:00Z"
#}

# View the backup file.
#data "alicloud_rds_backups" "example" {
#  db_instance_id    = alicloud_db_instance.instance.id
#}

If you want to experience more examples, go to the quickstarts page and view the examples in the folder of the corresponding service.

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.