在通过 Terraform 创建 RDS 实例后向数据库添加 Postgresql 角色

Adding a Postgresql role to a database after the RDS instance was created via Terraform

我正在尝试通过 Terraform 在 RDS 中创建角色后向 Postgresql 数据库添加角色。

我有两个独立的模块,一个创建 RDS 实例,一个向其添加新角色。数据库地址是persistence模块的输出和persistenceApplicationRole模块的输入。问题好像是Postgresql提供者在创建RDS实例之前运行,所以地址是空的
我得到的错误是:

Error: Error initializing PostgreSQL client: error detecting capabilities: error PostgreSQL version: dial tcp :5432: connect: connection refused

  on ../modules/persistenceApplicationRole/main.tf line 9, in provider "postgresql":
   9: provider postgresql {

运行 模块通过 -target=module.persistence 标志单独工作,因为 persistenceApplicationRole 一旦创建就获取数据库地址。 我在他们的文档 here.

中找到了 MySQL Provider 的这个确切场景的示例
# module.persistenceApplicationRole
provider postgresql {
  host      = var.databaseAddress
  username  = data.external.root_credentials.result["username"]
  password  = data.external.root_credentials.result["password"]
  superuser = false
}

resource "postgresql_role" "application_role" {
  name     = data.external.application_credentials.result["username"]
  password = data.external.application_credentials.result["password"]

  login               = true
  encrypted_password  = true
  skip_reassign_owned = true
  skip_drop_role      = true
}

前一段时间 1.4.0 release of the Postgresql provider added expected_version which you can use to avoid the feature detection at plan time that attempts to connect to the database. This was introduced in the 0.1.1 release 打破了人们能够同时创建底层实例和配置数据库的能力。

要使用 expected_version,您需要这样做:

provider postgresql {
  host      = var.databaseAddress
  username  = data.external.root_credentials.result["username"]
  password  = data.external.root_credentials.result["password"]
  superuser = false

  expected_version = "10.1"
}

更常见的用例是创建 RDS 实例或其他实例并将其插入:

resource "aws_db_instance" "database" {
  # ...
}

provider "postgresql" {
  version = ">=1.4.0"

  host             = aws_db_instance.database.address
  port             = aws_db_instance.database.port
  username         = aws_db_instance.database.user
  password         = aws_db_instance.database.password
  sslmode          = "require"
  connect_timeout  = 15
  superuser        = false
  expected_version = aws_db_instance.database.engine_version
}