Securing Postgresql (pg) backend credentials

Hi folks,

I’m new to Terraform, therefore apologies in case I’m asking something obvious.

I am trying to use the pg backend in a secure way, and that means not storing the PostgreSQL connection string (containing username/password) on the file system.

So I’m trying to use environment variables. I know they are not perfect, but better than permanently storing credentials on the file system.

After a bit of struggle, I managed to figure out how to pass the connection string as an environment variable to the cli, which looks something like this:

TF_CLI_ARGS="-backend-config='conn_str=postgres://some_host/some_db'" \
        terraform init

…and this would be all right, but then I found out that .terraform/terraform.tfstate still contains the connection string in clear text under backend.config.conn_str.

Am I missing something? Is there a better, more secure way?

Thanks!

Hi @salomvary,

It sounds like you’re on the right track here that the typical answer is to put the sensitive values in the environment (in a backend-specific way) and put non-sensitive values in the configuration, which can either mean literally in configuration files (a backend block in a .tf file) or by overriding that configuration on the terraform init command line.

I think where I lost the trail of your question is the relationship between the fact that you put the credentials in the environment and the fact that the connection string appeared in the filesystem. That sounds like the expected result to me: the .terraform/terraform.tfstate would track the connection string but not the credentials.

Are you saying that the credentials from the environment variables are also ending up in the file on disk? If so, that isn’t expected, but we can work on figuring out why it happened and how to stop it.

I’m sorry if I’m missing something crucial here; I am admittedly coming from a position of knowing about how backends in general work rather than specifically how the pg backend works, so perhaps there’s something special about that one that I’m missing but I can go read up a bit if this turns out to be something specific to that backend.