Use Terraform to manage the network configuration of an ApsaraDB RDS for PostgreSQL instance

Updated at: 2025-01-26 05:19

This topic describes how to use Terraform to apply for a public endpoint for an ApsaraDB RDS for PostgreSQL instance and how to modify and release the public endpoint. This topic also describes how to query and change the vSwitch 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.

Apply for a public endpoint

  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"
      }
      
      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
      }
    • In the main.tf file, add the resource "alicloud_db_database" "db" {} and resource "alicloud_db_connection" "extranet" {} configuration items and configure the configuration items based on the following code snippet:

      ...
      resource "alicloud_db_database" "db" {
        instance_id = alicloud_db_instance.instance.id
        name        = "tf_database_test"
      }
      
      resource "alicloud_db_connection" "extranet" {
        instance_id = alicloud_db_instance.instance.id
        port        = "5432"
      }
  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_db_connection.extranet: Creating...
    alicloud_db_connection.extranet: Still creating... [10s elapsed]
    alicloud_db_connection.extranet: Creation complete after 11s [id=pgm-****:pgm-****]
    
    Apply complete!  Resources: 1 added, 0 changed, 0 destroyed.
  5. Verify the result.

    Run the terraform show command
    Log on to the ApsaraDB RDS console

    Run the following command to view the public endpoint of the RDS instance:

    terraform show
    # alicloud_db_connection.extranet:
    resource "alicloud_db_connection" "extranet" {
        connection_prefix = "pgm-****"
        connection_string = "pgm-****.pg.rds.aliyuncs.com"
        id                = "pgm-****:pgm-****"
        instance_id       = "pgm-****"
        ip_address        = "47.118.XX.XX"
        port              = "5432"
    }
    
    # alicloud_db_instance.instance:
    resource "alicloud_db_instance" "instance" {
        client_ca_enabled          = 0
        client_crl_enabled         = 0
        connection_string          = "pgm-****.pg.rds.aliyuncs.com"
        connection_string_prefix   = "pgm-****"
        db_instance_storage_type   = "cloud_essd"
        db_time_zone               = "Asia/Shanghai"
        deletion_protection        = false
        engine                     = "PostgreSQL"
        engine_version             = "13.0"
        force_restart              = false
        ha_config                  = "Auto"
        id                         = "pgm-****"
        instance_charge_type       = "Postpaid"
        instance_name              = "terraformtest"
        instance_storage           = 50
        instance_type              = "pg.n2.2c.2m"
        maintain_time              = "05:00Z-06:00Z"
        monitoring_period          = 300
        period                     = 0
        port                       = "5432"
        private_ip_address         = "172.16.XX.XX"
        resource_group_id          = "rg-****"
        security_group_ids         = []
        security_ip_mode           = "normal"
        security_ips               = [
            "127.0.0.1",
        ]
        sql_collector_config_value = 30
        sql_collector_status       = "Disabled"
        storage_auto_scale         = "Enable"
        storage_threshold          = 30
        storage_upper_bound        = 100
        target_minor_version       = "rds_postgres_1300_20220830"
        tcp_connection_type        = "SHORT"
        vpc_id                     = "vpc-****"
        vswitch_id                 = "vsw-"
        zone_id                    = "cn-heyuan-j"
    
        pg_hba_conf {
            address     = "127.0.0.1"
            database    = "all"
            method      = "md5"
            priority_id = 1
            type        = "host"
            user        = "all"
        }
    }

    Log on to the ApsaraDB RDS console to view the public endpoint of the RDS instance.外网地址

Modify a public endpoint

This section describes how to change the prefix of the public endpoint of an RDS instance to pgtest.

  1. In the main.tf file, add the connection_prefix field to the resource "alicloud_db_connection" "extranet" {} configuration item and configure the field based on the following code snippet:

    ...
    resource "alicloud_db_connection" "extranet" {
    ...
      connection_prefix = "pgtest"
    }
  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_connection.extranet: Destroying... [id=pgm-****:pgm-****]
    alicloud_db_connection.extranet: Destruction complete after 1s
    alicloud_db_connection.extranet: Creating...
    alicloud_db_connection.extranet: Still creating... [10s elapsed]
    alicloud_db_connection.extranet: Creation complete after 15s [id=pgm-****:pgtest]
    
    Apply complete!  Resources: 1 added, 0 changed, 1 destroyed.
  3. Verify the result.

    Run the terraform show command
    Log on to the ApsaraDB RDS console

    Run the following command to view the public endpoint of the RDS instance:

    terraform show
    # alicloud_db_connection.extranet:
    resource "alicloud_db_connection" "extranet" {
        connection_prefix = "pgtest"
        connection_string = "pgtest.pg.rds.aliyuncs.com"
        id                = "pgm-****:pgtest"
        instance_id       = "pgm-****"
        ip_address        = "47.118.XX.XX"
        port              = "5432"
    }
    
    # alicloud_db_instance.instance:
    resource "alicloud_db_instance" "instance" {
        client_ca_enabled          = 0
        client_crl_enabled         = 0
        connection_string          = "pgm-****.pg.rds.aliyuncs.com"
        connection_string_prefix   = "pgm-****"
        db_instance_storage_type   = "cloud_essd"
        db_time_zone               = "Asia/Shanghai"
        deletion_protection        = false
        engine                     = "PostgreSQL"
        engine_version             = "13.0"
        force_restart              = false
        ha_config                  = "Auto"
        id                         = "pgm-****"
        instance_charge_type       = "Postpaid"
        instance_name              = "terraformtest"
        instance_storage           = 50
        instance_type              = "pg.n2.2c.2m"
        maintain_time              = "05:00Z-06:00Z"
        monitoring_period          = 300
        period                     = 0
        port                       = "5432"
        private_ip_address         = "172.16.XX.XX"
        resource_group_id          = "rg-****"
        security_group_ids         = []
        security_ip_mode           = "normal"
        security_ips               = [
            "127.0.0.1",
        ]
        sql_collector_config_value = 30
        sql_collector_status       = "Disabled"
        storage_auto_scale         = "Enable"
        storage_threshold          = 30
        storage_upper_bound        = 100
        target_minor_version       = "rds_postgres_1300_20220830"
        tcp_connection_type        = "SHORT"
        vpc_id                     = "vpc-****"
        vswitch_id                 = "vsw-****"
        zone_id                    = "cn-heyuan-j"
    
        pg_hba_conf {
            address     = "127.0.0.1"
            database    = "all"
            method      = "md5"
            priority_id = 1
            type        = "host"
            user        = "all"
        }
    }

    Log on to the ApsaraDB RDS console to view the public endpoint of the RDS instance.外网连接地址改后

Release a public endpoint

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

    ...
    resource "alicloud_db_connection" "extranet" {
      instance_id = alicloud_db_instance.instance.id
      port  = "5432"
      connection_prefix = "pgtest"
    }
  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_connection.extranet: Destroying... [id=pgm-****:pgtest]
    alicloud_db_connection.extranet: Destruction complete after 1s
    
    Apply complete!  Resources: 0 added, 0 changed, 1 destroyed.
  3. Verify the result.

    Run the terraform show command
    Log on to the ApsaraDB RDS console

    Run the following command to view the public endpoint of the RDS instance:

    terraform show
    # alicloud_db_account.account:
    resource "alicloud_db_account" "account" {
        account_name     = "tf_account_test"
        account_password = (sensitive value)
        account_type     = "Normal"
        db_instance_id   = "pgm-****"
        id               = "pgm-****:tf_account_test"
        instance_id      = "pgm-****)"
        name             = "tf_account_test"
        status           = "Available"
        type             = "Normal"
    }
    # alicloud_db_instance.instance:
    resource "alicloud_db_instance" "instance" {
        client_ca_enabled          = 0
        client_crl_enabled         = 0
        connection_string          = "pgm-****.pg.rds.aliyuncs.com"
        connection_string_prefix   = "pgm-****"
        db_instance_storage_type   = "cloud_essd"
        db_time_zone               = "Asia/Shanghai"
        deletion_protection        = false
        engine                     = "PostgreSQL"
        engine_version             = "13.0"
        force_restart              = false
        ha_config                  = "Auto"
        id                         = "pgm-****"
        instance_charge_type       = "Postpaid"
        instance_name              = "terraformtest"
        instance_storage           = 50
        instance_type              = "pg.n2.2c.2m"
        maintain_time              = "05:00Z-06:00Z"
        monitoring_period          = 300
        period                     = 0
        port                       = "5432"
        private_ip_address         = "172.16.XX.XX"
        resource_group_id          = "rg-****"
        security_group_ids         = []
        security_ip_mode           = "normal"
        security_ips               = [
            "127.0.0.1",
        ]
        sql_collector_config_value = 30
        sql_collector_status       = "Disabled"
        storage_auto_scale         = "Enable"
        storage_threshold          = 30
        storage_upper_bound        = 100
        target_minor_version       = "rds_postgres_1300_20220730"
        tcp_connection_type        = "SHORT"
        vpc_id                     = "vpc-****"
        vswitch_id                 = "vsw-****"
        zone_id                    = "cn-heyuan-j"
    }
                                    

    Log on to the ApsaraDB RDS console to check whether the public endpoint of the RDS instance is released.已释放外网地址

Query vSwitch details

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

    ...
    data "alicloud_vswitches" "instance" {
      vpc_id            = alicloud_vpc.main.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:

    data.alicloud_vswitches.instance: Reading...
    alicloud_db_instance.instance: Refreshing state... [id=pgm-****]
    data.alicloud_vswitches.instance: Read complete after 1s [id=44344****]
    
    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 result:

    terraform show
    # data.alicloud_vswitches.instance:
    data "alicloud_vswitches" "instance" {
        id        = "246547****"
        ids       = [
            "vsw-****",
            "vsw-****",
        ]
        names     = [
            "test",
            "",
        ]
        vpc_id    = "vpc-****"
        vswitches = [
            {
                available_ip_address_count = 252
                cidr_block                 = "10.1.0.0/24"
                creation_time              = "2022-09-13T01:57:56Z"
                description                = ""
                id                         = "vsw-****"
                is_default                 = false
                name                       = "test"
                resource_group_id          = "rg-****"
                route_table_id             = "vtb-****"
                status                     = "Available"
                tags                       = {}
                vpc_id                     = "vpc-****"
                vswitch_id                 = "vsw-****"
                vswitch_name               = "test"
                zone_id                    = "cn-heyuan-b"
            },
            {
                available_ip_address_count = 237
                cidr_block                 = "10.2.0.0/24"
                creation_time              = "2022-09-07T06:18:47Z"
                description                = ""
                id                         = "vsw-****"
                is_default                 = false
                name                       = ""
                resource_group_id          = "rg-****"
                route_table_id             = "vtb-****"
                status                     = "Available"
                tags                       = {}
                vpc_id                     = "vpc-****"
                vswitch_id                 = "vsw-****"
                vswitch_name               = ""
                zone_id                    = "cn-heyuan-b"
            },
        ]
    }

Change a vSwitch

This section describes how to change the vSwitch of your RDS instance to meet your business requirements.

Important
  • If you change the vSwitch of your RDS instance, the original RDS instance is deleted, and another RDS instance is created. The new RDS instance does not inherit the data of the original RDS instance. Proceed with caution.

  • You cannot change the VPC of an RDS instance. The new vSwitch must belong to the VPC of the RDS instance.

  1. In the main.tf file, change the value of the vswitch_id field in the resource "alicloud_db_instance" "instance" {} configuration item based on the following code snippet:

    ...
    resource "alicloud_db_instance" "instance" {
    ...
      vswitch_id       = "vsw-****"
    }
  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: Destroying... [id=pgm-****]
    alicloud_db_instance.instance: Still destroying... [id=pgm-****, 10s elapsed]
    alicloud_db_instance.instance: Still destroying... [id=pgm-****, 20s elapsed]
    alicloud_db_instance.instance: Still destroying... [id=pgm-****, 30s elapsed]
    alicloud_db_instance.instance: Destruction complete after 31s
    alicloud_db_instance.instance: Creating...
    alicloud_db_instance.instance: Still creating... [10s elapsed]
    alicloud_db_instance.instance: Still creating... [20s elapsed]
    ...
    alicloud_db_instance.instance: Still creating... [10m58s elapsed]
    alicloud_db_instance.instance: Creation complete after 11m1s [id=pgm-****]
    
    Apply complete!  Resources: 1 added, 0 changed, 1 destroyed.
  3. Verify the result.

    Run the terraform show command
    Log on to the ApsaraDB RDS console

    Run the following command to view the details about the vSwitch of the RDS instance:

    terraform show
    # alicloud_db_instance.instance:
    resource "alicloud_db_instance" "instance" {
        client_ca_enabled          = 0
        client_crl_enabled         = 0
        connection_string          = "pgm-****.pg.rds.aliyuncs.com"
        connection_string_prefix   = "pgm-****"
        db_instance_storage_type   = "cloud_essd"
        db_time_zone               = "Asia/Shanghai"
        deletion_protection        = false
        engine                     = "PostgreSQL"
        engine_version             = "13.0"
        force_restart              = false
        ha_config                  = "Auto"
        id                         = "pgm-****"
        instance_charge_type       = "Postpaid"
        instance_name              = "terraformtest"
        instance_storage           = 50
        instance_type              = "pg.n2.2c.2m"
        maintain_time              = "05:00Z-06:00Z"
        monitoring_period          = 300
        period                     = 0
        port                       = "5432"
        private_ip_address         = "192.168.XX.XX"
        resource_group_id          = "rg-****"
        security_group_ids         = []
        security_ip_mode           = "normal"
        security_ips               = [
            "127.0.0.1",
        ]
        sql_collector_config_value = 30
        sql_collector_status       = "Disabled"
        storage_auto_scale         = "Enable"
        storage_threshold          = 30
        storage_upper_bound        = 100
        target_minor_version       = "rds_postgres_1300_20220830"
        tcp_connection_type        = "SHORT"
        vpc_id                     = "vpc-****"
        vswitch_id                 = "vsw-****"
        zone_id                    = "cn-heyuan-j"
    
        pg_hba_conf {
            address     = "127.0.0.1"
            database    = "all"
            method      = "md5"
            priority_id = 1
            type        = "host"
            user        = "all"
        }
    }

    Log on to the ApsaraDB RDS console to view the details about the vSwitch 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

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-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 database.
resource "alicloud_db_database" "db" {
  instance_id = alicloud_db_instance.instance.id
  name        = "tf_database_test"
}

# Apply for a public endpoint.
resource "alicloud_db_connection" "extranet" {
  instance_id       = alicloud_db_instance.instance.id
  port              = "5432"
  # Modify the public endpoint.
  connection_prefix = "pgtest"
}

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

  • On this page (1, T)
  • Prerequisites
  • Resources
  • Apply for a public endpoint
  • Modify a public endpoint
  • Release a public endpoint
  • Query vSwitch details
  • Change a vSwitch
  • Clear resources
  • Complete sample code
  • Sample code
  • References
Feedback