You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取Terraform部署的AWS RDS实例的IPv4地址?

获取Terraform部署的AWS RDS实例IPv4地址的方法

方法一:直接使用RDS资源自带的IP属性

Terraform AWS Provider(版本≥3.0.0)的aws_db_instance资源提供了直接获取IP的属性:

  • private_ip_address:返回RDS实例的私有IPv4地址
  • public_ip_address:若RDS实例启用了公网访问,返回对应的公网IPv4地址

示例代码:

resource "aws_db_instance" "example" {
  allocated_storage    = 20
  engine               = "mysql"
  engine_version       = "8.0"
  instance_class       = "db.t3.micro"
  name                 = "exampledb"
  username             = "admin"
  password             = "yoursecurepassword"
  parameter_group_name = "default.mysql8.0"
  publicly_accessible  = true # 启用公网访问才会返回公网IP
}

output "rds_private_ip" {
  value = aws_db_instance.example.private_ip_address
}

output "rds_public_ip" {
  value = aws_db_instance.example.public_ip_address
}

方法二:通过DNS解析Endpoint获取IP

如果你的AWS Provider版本较低,没有上述IP属性,可以解析endpoint中的域名部分获取IP,使用Terraform的dns_a_record_set数据源查询域名的A记录:

示例代码:

resource "aws_db_instance" "example" {
  allocated_storage    = 20
  engine               = "mysql"
  engine_version       = "8.0"
  instance_class       = "db.t3.micro"
  name                 = "exampledb"
  username             = "admin"
  password             = "yoursecurepassword"
  parameter_group_name = "default.mysql8.0"
}

# 拆分Endpoint,仅保留域名部分(去掉端口)
data "dns_a_record_set" "rds_ip" {
  host = split(":", aws_db_instance.example.endpoint)[0]
}

# 输出解析得到的第一个IP地址
output "rds_ip_address" {
  value = data.dns_a_record_set.rds_ip.addrs[0]
}

注意事项

  • 若RDS为多AZ部署或有只读副本,dns_a_record_set的addrs会返回所有关联IP,可根据需求选择对应值
  • 公网IP的解析依赖于publicly_accessible属性设置为true,否则域名仅会解析到私有IP

内容的提问来源于stack exchange,提问作者Akshay Lokur

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 09:01:09