如何从Terraform azurerm_postgresql_flexible_server获取数据库URL?
获取Azure PostgreSQL Flexible Server的数据库URL
Azure PostgreSQL Flexible Server没有直接提供现成的数据库URL输出项,但你可以通过资源属性拼接出完整URL,以下是两种常用方式:
一、在Terraform配置里直接拼接输出
Terraform的azurerm_postgresql_flexible_server资源提供了拼接URL所需的所有属性,直接组合即可:
- 服务器FQDN:
azurerm_postgresql_flexible_server.example.fqdn(替换example为你的资源名称) - 默认端口:5433(Azure PostgreSQL Flexible Server的默认端口是5433,不是标准的5432)
- 管理员用户名:
azurerm_postgresql_flexible_server.example.administrator_login - 管理员密码:配置里设置的
administrator_login_password - 数据库名:如果创建了
azurerm_postgresql_flexible_database资源,用azurerm_postgresql_flexible_database.example.name,默认数据库是postgres
示例输出配置:
output "postgresql_database_url" { value = "postgres://${azurerm_postgresql_flexible_server.example.administrator_login}:${azurerm_postgresql_flexible_server.example.administrator_login_password}@${azurerm_postgresql_flexible_server.example.fqdn}:5433/${azurerm_postgresql_flexible_database.example.name}" sensitive = true # 包含敏感密码,标记为敏感输出避免泄露 }
如果用Azure AD认证,不需要密码的话,URL格式改为:postgres://<username>@<server_fqdn>:5433/<database_name>?sslmode=require
二、创建完成后手动获取拼接
1. Azure CLI方式
先获取服务器FQDN:
az postgres flexible-server show --resource-group <你的资源组名> --name <你的服务器名> --query "fullyQualifiedDomainName" --output tsv
然后用拿到的FQDN,结合用户名、密码、数据库名,拼接成postgres://<username>:<password>@<fqdn>:5433/<database-name>格式的URL。
2. Azure Portal方式
- 打开Azure Portal,进入你的PostgreSQL Flexible Server概览页面
- 复制“服务器名称”栏的完整FQDN
- 用这个FQDN搭配你的数据库用户名、密码、数据库名称,按照上述格式拼接即可。
内容的提问来源于stack exchange,提问作者spierce7
相关产品推荐
相关产品推荐

