All Products
Search
Document Center

ApsaraDB RDS:Enhance the data security of an RDS for PostgreSQL instance by using Terraform

Last Updated:Mar 01, 2026

Use Terraform to configure security groups, IP address whitelists, Secure Sockets Layer (SSL) encryption, and the enhanced whitelist mode for an ApsaraDB RDS for PostgreSQL instance.

Note

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

Overview

ApsaraDB RDS for PostgreSQL provides four security features that you can manage with Terraform:

FeatureTerraform parameterDescription
Security groupsecurity_group_idsControls which Elastic Compute Service (ECS) security groups can access the RDS instance
IP address whitelistsecurity_ipsSpecifies which IP addresses or CIDR blocks can connect to the RDS instance
SSL encryptionssl_actionEncrypts connections between clients and the RDS instance
Enhanced whitelist modesecurity_ip_modeEnables finer-grained IP address whitelist management. Only for instances that use Premium Local SSDs (irreversible)

Each feature is applied as an incremental change to a base Terraform configuration.

Prerequisites

  • An ApsaraDB RDS for PostgreSQL instance in the Running state. For more information, see Create an RDS instance. To verify the instance status:

  • A Resource Access Management (RAM) user with an AccessKey pair. Using a RAM user instead of your Alibaba Cloud account reduces the risk of credential exposure. For more information, see Create a RAM user and Create an AccessKey pair.

  • RAM permissions granted based on the principle of least privilege (PoLP). For more information, see Grant permissions to RAM users. The following policy provides the minimum required permissions:

        {
            "Version": "1",
            "Statement": [
                {
                    "Effect": "Allow",
                    "Action": [
                        "vpc:DescribeVpcAttribute",
                        "vpc:DescribeRouteTableList",
                        "vpc:DescribeVSwitchAttributes",
                        "vpc:DeleteVpc",
                        "vpc:DeleteVSwitch",
                        "vpc:CreateVpc",
                        "vpc:CreateVSwitch",
                        "vpc:DescribeVSwitches",
                        "ecs:CreateSecurityGroup",
                        "ecs:ModifySecurityGroupPolicy",
                        "ecs:DescribeSecurityGroups",
                        "ecs:ListTagResources",
                        "ecs:DeleteSecurityGroup",
                        "ecs:DescribeSecurityGroupAttribute",
                        "ecs:AuthorizeSecurityGroup",
                        "ecs:RevokeSecurityGroup"
                    ],
                    "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": "*"
                }
            ]
        }
  • A Terraform environment prepared using one of the following methods:

Resources

Note

Some resources incur charges. Release or unsubscribe from resources that you no longer need.

This tutorial uses the following Terraform resources:

Step 1: Set up the base configuration

Create a working directory and a file named main.tf with the following content. This configuration creates a VPC, a vSwitch, a security group, and an RDS instance.

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 a security group.
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
}

Run the following commands to initialize and deploy the resources:

terraform init

If the following output appears, 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.

Preview the changes:

terraform plan

Apply the configuration:

terraform apply

When prompted, enter yes and press Enter.

Step 2: Change the security group

Add the security_group_ids field to the resource "alicloud_db_instance" "instance" {} block in main.tf:

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
  security_group_ids   = [alicloud_security_group.example.id]
}
Note

The new configuration overwrites the original configuration. To configure multiple security groups, append their IDs to the security_group_ids list: security_group_ids = ["sg-aaa", "sg-bbb"].

Apply the change:

terraform apply

When prompted, enter yes and press Enter. The following output indicates success:

alicloud_db_instance.instance: Modifying... [id=pgm-****]
alicloud_db_instance.instance: Modifications complete after 4s [id=pgm-****]

Apply complete!  Resources: 0 added, 1 changed, 0 destroyed.

Verify the security group

Run terraform show and confirm that security_group_ids contains the expected security group ID:

terraform show

Relevant output:

security_group_ids         = [
    "sg-****",
]

Alternatively, log on to the ApsaraDB RDS console and check the security group on the instance details page.

Step 3: Modify the IP address whitelist

Add the security_ips field to the resource "alicloud_db_instance" "instance" {} block in main.tf:

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
  security_group_ids   = [alicloud_security_group.example.id]
  security_ips         = ["0.0.0.0/0"]
}
Warning

Setting security_ips to 0.0.0.0/0 allows access from any IP address. Use this value only for testing. In production, restrict the whitelist to specific IP addresses or CIDR blocks.

Note

The new configuration overwrites the original configuration. To add multiple IP addresses, append them to the security_ips list: security_ips = ["10.0.0.1", "192.168.1.0/24"].

Apply the change:

terraform apply

When prompted, enter yes and press Enter. The following output indicates success:

alicloud_db_instance.instance: Modifying... [id=pgm-****]
alicloud_db_instance.instance: Modifications complete after 6s [id=pgm-****]

Apply complete!  Resources: 0 added, 1 changed, 0 destroyed.

Verify the IP address whitelist

Run terraform show and confirm that security_ips contains the expected values:

terraform show

Relevant output:

security_ips               = [
    "0.0.0.0/0",
]

Alternatively, log on to the ApsaraDB RDS console and check the IP address whitelist on the instance security page.

Step 4: Enable SSL encryption

Add the ssl_action field to the resource "alicloud_db_instance" "instance" {} block in main.tf:

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
  security_group_ids   = [alicloud_security_group.example.id]
  security_ips         = ["0.0.0.0/0"]
  ssl_action           = "Open"
}

Apply the change:

terraform apply

When prompted, enter yes and press Enter. Enabling SSL may take several minutes. The following output indicates success:

alicloud_db_instance.instance: Modifying... [id=pgm-****]
alicloud_db_instance.instance: Still modifying... [id=pgm-****, 10s elapsed]
...
alicloud_db_instance.instance: Still modifying... [id=pgm-****, 6m31s elapsed]
alicloud_db_instance.instance: Modifications complete after 6m35s [id=pgm-****]

Apply complete!  Resources: 0 added, 1 changed, 0 destroyed.

Verify SSL encryption

Run terraform show and confirm that ssl_action is set to Open:

terraform show

Relevant output:

ssl_action                 = "Open"
acl                        = "prefer"
ca_type                    = "aliyun"
replication_acl            = "prefer"
server_cert                = (sensitive value)

Alternatively, log on to the ApsaraDB RDS console and check the SSL settings on the instance security page.

Step 5: Enable enhanced whitelist mode

Note

The enhanced whitelist mode applies to RDS instances that use Premium Local SSDs. After you enable this mode, it cannot be switched back to the standard whitelist mode. This change is irreversible.

Add the security_ip_mode field to the resource "alicloud_db_instance" "instance" {} block in main.tf:

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
  security_group_ids   = [alicloud_security_group.example.id]
  security_ips         = ["0.0.0.0/0"]
  ssl_action           = "Open"
  security_ip_mode     = "safety"
}

Apply the change:

terraform apply

When prompted, enter yes and press Enter. The following output indicates success:

alicloud_db_instance.instance: Modifying... [id=pgm-****]
alicloud_db_instance.instance: Modifications complete after 3s [id=pgm-****]

Apply complete!  Resources: 0 added, 1 changed, 0 destroyed.

Verify the whitelist mode

Run terraform show and confirm that security_ip_mode is set to safety:

terraform show

Relevant output:

security_ip_mode           = "safety"

Alternatively, log on to the ApsaraDB RDS console and check the whitelist mode on the instance security page.

Clean up resources

To release the resources created in this tutorial, run the following command. For more information about the terraform destroy command, see Common commands.

terraform destroy

When prompted, enter yes and press Enter.

Complete sample code

The following code includes all four security features as commented-out options. Uncomment the features you want to enable.

Note

Run this sample code 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"
}

variable "security_ips" {
  default = "0.0.0.0/0"
}

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
  # Change the security group.
  # security_group_ids   = [alicloud_security_group.example.id]
  # Modify an IP address whitelist.
  # security_ips         =  [var.security_ips]
  # Enable SSL encryption.
  # ssl_action           =  "Open"
  # Enable the enhanced whitelist mode for an RDS instance that uses Premium Local SSDs.
  # security_ip_mode     = "safety"
}

For more examples, see the quickstarts page and find the folder for the corresponding service.