使用 Terraform 的 AWS RDS IAM 身份验证

AWS RDS IAM Authentication with Terraform

我正尝试在没有密码或密钥的情况下正确设置我的基础设施。 AWS RDS 有一个选项可以让用户(应用程序)使用生成的令牌进行身份验证。

但是,在文档中,其中一个步骤(this one)需要运行在 Postgres 数据库中进行查询以创建用户并授予他特定权限:

CREATE USER test_rds WITH LOGIN;
GRANT rds_iam TO test_rds;

我想使用 Terraform 提供整个堆栈。在 RDS 实例化之后,我已经查找了一些 "hacks" 到 运行 查询 (here):

resource "null_resource" "db_setup" {
  depends_on = ["aws_db_instance.your_database_instance",   "aws_security_group.sg_allowing_external_access"]

    provisioner "local-exec" {
 // run shell commands to manually psql into the db

或:

resource "aws_instance" "web" {


  provisioner "remote-exec" {
    inline = [
   // run shell commands to manually psql into the db

但它们都需要创建主密码并以某种方式将其传送到 "scripts"。

是否可以使用 Terraform 干净地做到这一点,没有硬编码密码被传递?

我很乐意配置数据库并仅启用具有正确 permissions 的特定 EC2/ECS 实例来访问它,而我的 git 存储库中没有任何密码。

为 RDS 数据库启用 IAM 身份验证后,您将无法再为该数据库使用基于密码的身份验证。user/role。

这意味着您可以使用不太安全的密码,甚至可以生成一个随机密码(使用 random_id resource),您可以使用该密码来设置主密码并首先用于身份验证,以便您可以授予rds_iam 对主用户和您创建的任何其他用户的权限。

虽然此密码最终会出现在状态文件中(即使是随机生成的),但如前所述,一旦应用了 rds_iam 授权,您将无法使用此密码登录你的数据库。

要为 IAM 身份验证准备好 RDS 数据库用户,可以添加以下 terraform 配置:

resource "postgresql_role" "db_user" {
  name  = "db_userx"
  login = true
  roles = ["rds_iam"]
}

上面的代码使用了 cyrilgdn/postgresql 提供程序。如果您使用 aws_db_instance 属性为其连接参数配置提供程序,如下所示,则会强制执行正确的依赖项顺序。

provider "postgresql" {
  host            = aws_db_instance.web.address
  port            = aws_db_instance.web.port
  database        = "postgres"
  username        = aws_db_instance.web.username
  password        = aws_db_instance.web.password
  sslmode         = "require"
  connect_timeout = 15
  superuser       = false # postgres user is not a true superuser in RDS
}

RDS User Guide 现在包括以下内容:

For PostgreSQL, if the IAM role (rds_iam) is added to the master user, IAM authentication takes precedence over Password authentication so the master user has to log in as an IAM user