cyrilgdn / terraform-provider-postgresql

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

Issue when dynamically pass password to postgres provider #266

Closed pmquang closed 1 year ago

pmquang commented 1 year ago

Terraform Version

Terraform v1.2.5 on darwin_amd64

Terraform Configuration Files

provider "postgresql" {
  host             = "db.host"
  port             = 5432
  database         = "postgres"
  username         = "root"
  password         = random_password.password.result
  sslmode          = "require"
  connect_timeout  = 10
  expected_version = "13.6"
  superuser        = false
}

resource "postgresql_database" "test" {
  name              = "test"
}

// Renew RDS master password in the period of months
// resource "time_rotating" "rds_password" {
//  rotation_minutes = 5
// }

resource "random_password" "password" {
  length  = 32
  special = true

//  keepers = {
//    rotation = time_rotating.rds_password.id
//  }
}

Debug Output

I make changes of provider.go like this: https://gist.github.com/pmquang/bbd51ebd56698e0b0f6a67ed9a47dbbf#file-provider-go

Panic Output

https://gist.github.com/pmquang/37a72da4fa122ef5768b1d0da717bd9a#file-ouput-txt

Expected Behavior

When do planning, it should be fine as long as password is right

Actual Behavior

When something changed on resource random_password, something like length or whatever that doesn't change the password. The postgres provider still receives the empty password string.

Steps to Reproduce

  1. Firstly, import random_password as your password

terraform import random_password.password YOUR_PASSWORD_TO_CONNECT_POSTGRES

  1. Do apply to create database test

terraform apply -auto-approve

  1. Then change something on resource random_password

For example: change special = true -> special = false

  1. Do planning again, error will happen

When you revert back special = true, it will do planning fine

cyrilgdn commented 1 year ago

Hi @pmquang ,

Unfortunately we cannot do anything on the provider for that. This is not a bug on the provider but the way Terraform works. During plan, the result of random_password is unknown ("known after apply") so empty. As you said:

The postgres provider still receives the empty password string.

The provider does not know where it comes from and cannot know it comes from another resource. And even if it could be aware of that, there's no way to get the previous password. Provider's configuration are not stored in the state, so you always have to provide the good password for every Terraform command. (except if the resource you work on doesn't exist, terraform plan will not try to connect in this case)

I close this issue but feel free to open it back if I missed something.