All Products
Search
Document Center

ApsaraDB RDS:Use Terraform to query the configurations of an RDS PostgreSQL instance

Last Updated:Sep 17, 2026

This topic describes how to use Terraform to query configurations of an ApsaraDB RDS for PostgreSQL instance.

Note

The sample code in this tutorial can be run with a single click. One-click Run

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 lets you 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 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 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 locally: Recommended for scenarios with poor network connectivity or for customizing your development environment.

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.

Query available zones

This section describes how to query available zones for an RDS instance.

  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-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
      }
    • Add the data "alicloud_db_zones" "queryzones" {} configuration item to the main.tf file.

      ...
      data "alicloud_db_zones" "queryzones" {
        instance_charge_type     = "PostPaid"
        engine                   = "PostgreSQL"
        db_instance_storage_type = "cloud_essd"
      }
  2. Run the following command to initialize the Terraform environment.

    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

    When prompted, enter yes and press Enter. Wait for the command to complete. The following output indicates that the operation is successful.

    data.alicloud_db_zones.queryzones: Reading...
    data.alicloud_db_zones.queryzones: Read complete after 1s [id=262******]
    
    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.
  5. Validation results

    You can run the following command to view the result:

    terraform show
    # data.alicloud_db_zones.queryzones:
    data "alicloud_db_zones" "queryzones" {
        db_instance_storage_type = "cloud_essd"
        engine                   = "PostgreSQL"
        id                       = "262******"
        ids                      = [
            "cn-heyuan-b",
        ]
        instance_charge_type     = "PostPaid"
        multi                    = false
        multi_zone               = false
        zones                    = [
            {
                id             = "cn-hangzhou-b"
                multi_zone_ids = []
            },
        ]
    }

Query available instance types

  1. In the main.tf file, add the following content:

    ...
    data "alicloud_db_instance_classes" "queryclasses" {
      instance_charge_type= "PostPaid"
      engine = "PostgreSQL"
      db_instance_storage_type = "cloud_essd"
    }
  2. Run the following command:

    terraform apply

    When prompted, enter yes and press Enter. Wait for the command to complete. If the following information is displayed, the operation is successful.

    data.alicloud_db_instance_classes.queryclasses: Reading...
    alicloud_vpc.main: Refreshing state... [id=vpc-****]
    alicloud_vswitch.main: Refreshing state... [id=vsw-****]
    alicloud_db_instance.instance: Refreshing state... [id=pgm-****]
    data.alicloud_db_instance_classes.queryclasses: Still reading... [10s elapsed]
    data.alicloud_db_instance_classes.queryclasses: Still reading... [20s elapsed]
    data.alicloud_db_instance_classes.queryclasses: Still reading... [30s elapsed]
    data.alicloud_db_instance_classes.queryclasses: Still reading... [40s elapsed]
    data.alicloud_db_instance_classes.queryclasses: Still reading... [50s elapsed]
    data.alicloud_db_instance_classes.queryclasses: Still reading... [1m0s elapsed]
    ...
    data.alicloud_db_instance_classes.queryclasses: Still reading... [6m50s elapsed]
    data.alicloud_db_instance_classes.queryclasses: Still reading... [7m0s elapsed]
    data.alicloud_db_instance_classes.queryclasses: Read complete after 7m9s [id=130302****]
    
    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.

    You can run the following command to view the result:

    terraform show
    {
                instance_class = "pg.n8.8xlarge.1"
                price          = ""
                storage_range  = {
                    "max"  = "32000"
                    "min"  = "1500"
                    "step" = "5"
                }
                zone_ids       = [
                    {
                        id           = "cn-hangzhou-k"
                        sub_zone_ids = []
                    },
                ]
    },
    {
                instance_class = "pg.n2.small.1"
                price          = ""
                storage_range  = {
                    "max"  = "32000"
                    "min"  = "1500"
                    "step" = "5"
                }
                zone_ids       = [
                    {
                        id           = "cn-hangzhou-k"
                        sub_zone_ids = []
                    },
                ]
    },
    ......

Query regions

  1. In the main.tf file, add the following content:

    data "alicloud_regions" "query_regions" {
    }
  2. Run the following command:

    terraform apply

    When prompted, enter yes and press Enter. Wait for the command to complete. The following output indicates that the operation is successful.

    data.alicloud_regions.query_regions: Reading...
    alicloud_vpc.main: Refreshing state... [id=vpc-****]
    alicloud_vswitch.main: Refreshing state... [id=vsw-****]
    data.alicloud_regions.query_regions: Read complete after 1s [id=2105****]
    alicloud_db_instance.instance: Refreshing state... [id=pgm-****]
    
    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.

    You can run the following command to view the result:

    terraform show
    # data.alicloud_regions.query_regions:
    data "alicloud_regions" "query_regions" {
        id      = "210547****"
        ids     = [
            "cn-qingdao",
            "cn-beijing",
            "cn-zhangjiakou",
            "cn-huhehaote",
            "cn-wulanchabu",
            "cn-hangzhou",
            "cn-shanghai",
            "cn-nanjing",
            "cn-shenzhen",
            "cn-heyuan",
            "cn-guangzhou",
            "cn-fuzhou",
            "cn-chengdu",
            "cn-hongkong",
            "ap-northeast-1",
            "ap-northeast-2",
            "ap-southeast-1",
            "ap-southeast-2",
            "ap-southeast-3",
            "ap-southeast-6",
            "ap-southeast-5",
            "ap-southeast-7",
            "us-east-1",
            "us-west-1",
            "eu-west-1",
            "me-east-1",
            "me-central-1",
            "eu-central-1",
        ]
        regions = [
            {
                id         = "cn-qingdao"
                local_name = "China (Qingdao)"
                region_id  = "cn-qingdao"
            },
            {
                id         = "cn-beijing"
                local_name = "China (Beijing)"
                region_id  = "cn-beijing"
            },
            {
                id         = "cn-zhangjiakou"
                local_name = "China (Zhangjiakou)"
                region_id  = "cn-zhangjiakou"
            },
            {
                id         = "cn-huhehaote"
                local_name = "China (Hohhot)"
                region_id  = "cn-huhehaote"
            },
            {
                id         = "cn-wulanchabu"
                local_name = "China (Ulanqab)"
                region_id  = "cn-wulanchabu"
            },
            {
                id         = "cn-hangzhou"
                local_name = "China (Hangzhou)"
                region_id  = "cn-hangzhou"
            },
            {
                id         = "cn-shanghai"
                local_name = "China (Shanghai)"
                region_id  = "cn-shanghai"
            },
            {
                id         = "cn-shenzhen"
                local_name = "China (Shenzhen)"
                region_id  = "cn-shenzhen"
            },
            {
                id         = "cn-heyuan"
                local_name = "China (Heyuan)"
                region_id  = "cn-heyuan"
            },
            {
                id         = "cn-guangzhou"
                local_name = "China (Guangzhou)"
                region_id  = "cn-guangzhou"
            },
            {
                id         = "cn-chengdu"
                local_name = "China (Chengdu)"
                region_id  = "cn-chengdu"
            },
            {
                id         = "cn-hongkong"
                local_name = "China (Hong Kong)"
                region_id  = "cn-hongkong"
            },
            {
                id         = "ap-northeast-1"
                local_name = "Asia Pacific NE 1 (Tokyo)"
                region_id  = "ap-northeast-1"
            },
            {
                id         = "ap-northeast-2"
                local_name = "South Korea (Seoul)"
                region_id  = "ap-northeast-2"
            },
            {
                id         = "ap-southeast-1"
                local_name = "Asia Pacific SE 1 (Singapore)"
                region_id  = "ap-southeast-1"
            },
            {
                id         = "ap-southeast-2"
                local_name = "Asia Pacific SE 2 (Sydney)"
                region_id  = "ap-southeast-2"
            },
            {
                id         = "ap-southeast-3"
                local_name = "Asia Pacific SE 3 (Kuala Lumpur)"
                region_id  = "ap-southeast-3"
            },
            {
                id         = "ap-southeast-6"
                local_name = "Philippines (Manila)"
                region_id  = "ap-southeast-6"
            },
            {
                id         = "ap-southeast-5"
                local_name = "Asia Pacific SE 5 (Jakarta)"
                region_id  = "ap-southeast-5"
            },
            {
                id         = "ap-southeast-7"
                local_name = "Thailand (Bangkok)"
                region_id  = "ap-southeast-7"
            },
            {
                id         = "us-east-1"
                local_name = "US East 1 (Virginia)"
                region_id  = "us-east-1"
            },
            {
                id         = "us-west-1"
                local_name = "US West 1 (Silicon Valley)"
                region_id  = "us-west-1"
            },
            {
                id         = "eu-west-1"
                local_name = "UK (London)"
                region_id  = "eu-west-1"
            },
            {
                id         = "me-east-1"
                local_name = "Middle East 1 (Dubai)"
                region_id  = "me-east-1"
            },
            {
                id         = "eu-central-1"
                local_name = "EU Central 1 (Frankfurt)"
                region_id  = "eu-central-1"
            },
        ]
    }  

Query RDS instances

  1. In the main.tf file, add the following content:

    data "alicloud_db_instances" "queryinstances" {
    }
  2. Run the following command:

    terraform apply

    When prompted, enter yes and press Enter. Wait for the command to complete. The following output indicates that the operation is successful.

    data.alicloud_db_instances.queryinstances: Reading...
    alicloud_vpc.main: Refreshing state... [id=vpc-****]
    alicloud_vswitch.main: Refreshing state... [id=vsw-****]
    data.alicloud_db_instances.queryinstances: Read complete after 1s [id=277****]
    alicloud_db_instance.instance: Refreshing state... [id=pgm-****]
    
    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. You can verify the result.

    You can run the following command to view the result:

    terraform show
    # data.alicloud_db_instances.queryinstances:
    data "alicloud_db_instances" "queryinstances" {
        enable_details = false
        id             = "27790****"
        ids            = [
            "pgm-bp1zirc6i2****",
        ]
        instances      = [
            {
                acl                         = ""
                availability_zone           = "cn-hangzhou-j"
                ca_type                     = ""
                charge_type                 = "Postpaid"
                client_ca_cert              = ""
                client_ca_cert_expire_time  = ""
                client_cert_revocation_list = ""
                connection_mode             = "Standard"
                connection_string           = "pgm-****.pg.rds.aliyuncs.com"
                create_time                 = "2022-09-28T06:15:32Z"
                creator                     = ""
                db_instance_storage_type    = "cloud_essd"
                db_type                     = "Primary"
                delete_date                 = ""
                deletion_protection         = false
                description                 = ""
                encryption_key              = ""
                encryption_key_status       = ""
                engine                      = "PostgreSQL"
                engine_version              = "13.0"
                expire_time                 = ""
                guard_instance_id           = "<nil>"
                id                          = "pgm-****"
                instance_storage            = 50
                instance_type               = "pg.n2.2c.2m"
                key_usage                   = ""
                last_modify_status          = ""
                master_instance_id          = "<nil>"
                master_zone                 = ""
                material_expire_time        = ""
                modify_status_reason        = ""
                name                        = "terraformtest"
                net_type                    = "Intranet"
                origin                      = ""
                parameters                  = []
                port                        = "5432"
                readonly_instance_ids       = []
                region_id                   = "cn-hangzhou"
                replication_acl             = ""
                require_update              = ""
                require_update_item         = ""
                require_update_reason       = ""
                server_ca_url               = ""
                server_cert                 = ""
                server_key                  = ""
                ssl_create_time             = ""
                ssl_enabled                 = "off"
                ssl_expire_time             = ""
                status                      = "Running"
                temp_instance_id            = "<nil>"
                vpc_id                      = "vpc-****"
                vswitch_id                  = "vsw-****"
                zone_id_slave_a             = ""
                zone_id_slave_b             = ""
            },
        ]
        names          = [
            "terraformtest",
        ]
        page_size      = 100
        total_count    = 1
    }                     

Query instance details

  1. In the main.tf file, add the following content:

    • Query specific RDS instances.

      Note

      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.

      data "alicloud_db_instances" "queryinstance" {
        ids    = ["pgm-f8z04t******"]
        engine = "PostgreSQL"
      }
    • Query all instances in a region that is specified by the environment variable.

      data "alicloud_db_instances" "queryinstance" {
        ids    = []
        engine = "PostgreSQL"
      }
  2. Run the following command:

    terraform apply

    When prompted, enter yes and press Enter. Wait for the command to complete. The following output indicates that the operation is successful.

    data.alicloud_db_instances.queryinstance: Reading...
    data.alicloud_db_instances.queryinstance: Read complete after 5s [id=69816****]
    
    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.

    You can run the following command to view the result:

    terraform show
    # data.alicloud_db_instances.queryinstance:
    data "alicloud_db_instances" "queryinstance" {
        enable_details = false
        engine         = "PostgreSQL"
        id             = "277908****"
        ids            = [
            "pgm-****",
        ]
        instances      = [
            {
                acl                         = ""
                availability_zone           = "cn-hangzhou-j"
                ca_type                     = ""
                charge_type                 = "Postpaid"
                client_ca_cert              = ""
                client_ca_cert_expire_time  = ""
                client_cert_revocation_list = ""
                connection_mode             = "Standard"
                connection_string           = "pgm-****.pg.rds.aliyuncs.com"
                create_time                 = "2022-09-28T06:15:32Z"
                creator                     = ""
                db_instance_storage_type    = "cloud_essd"
                db_type                     = "Primary"
                delete_date                 = ""
                deletion_protection         = false
                description                 = ""
                encryption_key              = ""
                encryption_key_status       = ""
                engine                      = "PostgreSQL"
                engine_version              = "13.0"
                expire_time                 = ""
                guard_instance_id           = "<nil>"
                id                          = "pgm-****"
                instance_storage            = 50
                instance_type               = "pg.n2.2c.2m"
                key_usage                   = ""
                last_modify_status          = ""
                master_instance_id          = "<nil>"
                master_zone                 = ""
                material_expire_time        = ""
                modify_status_reason        = ""
                name                        = "terraformtest"
                net_type                    = "Intranet"
                origin                      = ""
                parameters                  = []
                port                        = "5432"
                readonly_instance_ids       = []
                region_id                   = "cn-hangzhou"
                replication_acl             = ""
                require_update              = ""
                require_update_item         = ""
                require_update_reason       = ""
                server_ca_url               = ""
                server_cert                 = ""
                server_key                  = ""
                ssl_create_time             = ""
                ssl_enabled                 = "off"
                ssl_expire_time             = ""
                status                      = "Running"
                temp_instance_id            = "<nil>"
                vpc_id                      = "vpc-****"
                vswitch_id                  = "vsw-****"
                zone_id_slave_a             = ""
                zone_id_slave_b             = ""
            },
        ]
        names          = [
            "terraformtest",
        ]
        page_size      = 100
        total_count    = 1
    }

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

terraform destroy

Complete sample code

Note

You can run this sample code: One-click Run

Sample code

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

provider "alicloud" {
  region = var.region
}

variable "zone_id" {
  default = "cn-hangzhou-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
}

# Query available zones.
data "alicloud_db_zones" "queryzones" {
  instance_charge_type     = "PostPaid"
  engine                   = "PostgreSQL"
  db_instance_storage_type = "cloud_essd"
}

# Query available instance types.
data "alicloud_db_instance_classes" "queryclasses" {
  instance_charge_type     = "PostPaid"
  engine                   = "PostgreSQL"
  db_instance_storage_type = "cloud_essd"
}

# Query regions.
data "alicloud_regions" "query_regions" {
}

# Query RDS instances.
data "alicloud_db_instances" "queryinstances" {
}

# Query specific RDS instances.
data "alicloud_db_instances" "queryinstance" {
  ids = [alicloud_db_instance.instance.id]
  # Query all instances in a region that is specified by the environment variable.
  # ids  = []
  engine = "PostgreSQL"
}

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