如何使用Terraform销毁RDS中其他用户拥有的Postgres数据库?

时间:2017-08-03 13:22:09

标签: postgresql amazon-web-services amazon-rds terraform

我设法很好地让Terraform在RDS Postgres数据库中创建数据库和角色,但是由于rds_superuser的权限被剥离,我看不到一种简单的方法来销毁另一个拥有的创建的数据库用户。

使用以下配置:

resource "postgresql_role" "app" {
  name                = "app"
  login               = true
  password            = "foo"
  skip_reassign_owned = true
}

resource "postgresql_database" "database" {
  name  = "app_database"
  owner = "${postgresql_role.app.name}"
}

(供参考,skip_reassign_owned是必需的,因为rds_superuser群组未获得重新分配所有权的必要权限。

导致此错误:

Error applying plan:

1 error(s) occurred:

* postgresql_database.database (destroy): 1 error(s) occurred:

* postgresql_database.database: Error dropping database: pq: must be owner of database debug_db1

Terraform does not automatically rollback in the face of errors.
Instead, your Terraform state file has been partially updated with
any resources that successfully completed. Please address the error
above and apply again to incrementally change your infrastructure.

使用local-exec配置程序,我能够将拥有数据库的角色授予admin用户和应用程序用户:

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

provider "postgresql" {
  host            = "${aws_db_instance.database.address}"
  port            = 5432
  username        = "myadminuser"
  password        = "adminpassword"
  sslmode         = "require"
  connect_timeout = 15
}

resource "postgresql_role" "app" {
  name                = "app"
  login               = true
  password            = "apppassword"
  skip_reassign_owned = true
}

resource "postgresql_role" "group" {
  name                = "${postgresql_role.app.name}_group"
  skip_reassign_owned = true

  provisioner "local-exec" {
    command = "PGPASSWORD=adminpassword psql -h ${aws_db_instance.database.address} -U myadminuser postgres -c 'GRANT ${self.name} TO myadminuser, ${postgresql_role.app.name};'"
  }
}

resource "postgresql_database" "database" {
  name  = "mydatabase"
  owner = "${postgresql_role.group.name}"
}

与仅为app用户设置所有权相比,似乎有效。我想知道是否有更好的方法可以做到这一点,而不必在本地执行官中掏空?

1 个答案:

答案 0 :(得分:2)

提出这个问题之后,我设法提出了pull request with the fix中发布的version 0.1.1 of the Postgresql provider,所以现在可以在最新版本的提供程序中正常工作。