cyrilgdn / terraform-provider-postgresql

Terraform PostgreSQL provider
https://www.terraform.io/docs/providers/postgresql/
Mozilla Public License 2.0
355 stars 180 forks source link

Add support for GCP IAM impersonation #448

Open michaellzc opened 2 weeks ago

michaellzc commented 2 weeks ago

Add support for GCP IAM service account impersonation

Use cases

The company has a centralized service account that is used for Terraform automation. However, such GSA should not be used to access the database directly.

This added an option to impersonate the database IAM user via the centralized credentials GOOGLE_APPLICATION_CREDENTIALS, as long as it has sufficient permissions to impersonate as the database IAM user, to perform database automation in Terraform.

Testing

resource "google_sql_database_instance" "self" {}
resource "google_sql_user" "admin" {}
resource "google_service_account" "db_iam_admin" {}
resource "google_sql_user" "iam_admin" {
  name     = trimsuffix(google_service_account.db_iam_admin.email, ".gserviceaccount.com")
  instance = google_sql_database_instance.self.name
  type     = "CLOUD_IAM_SERVICE_ACCOUNT"
}
resource "google_project_iam_member" "iam_admin_project_iam_members" {
  for_each = toset(["roles/cloudsql.client", "roles/cloudsql.instanceUser"])
  member   = google_service_account.db_iam_admin.member
  role     = each.key
}

provider "postgresql" {
  scheme                              = "gcppostgres"
  host                                = google_sql_database_instance.self.connection_name
  username                            = trimsuffix(google_service_account.db_iam_admin.email, ".gserviceaccount.com")
  gcp_iam_impersonate_service_account = google_service_account.db_iam_admin.email
  port                                = 5432
  superuser                           = false
  alias                               = "iamAdmin"
}

# it should work and able to apply resources using the IAM db user
resource "postgresql_*" "*" {
  provider = postgresql.iamAdmin

  // *
}