How to use pg backend behind SSH tunnel?

I have postgres databases with NameCheap (cpanel) and I want to utilize these as Terraform backend. However, you need to connect via SSH first before using the databases.

Is there a way to use pg backend with SSH tunnel?

Hi @roniemartinez,

Usually when using an SSH tunnel it’s necessary to configure the client to connect to a localhost port that is the local endpoint of your tunnel, instead of to the real server address.

This is true for Terraform too: once you’ve established the SSH tunnel, you should set the backend storage address to refer to the localhost port which will forward connections to the remote service.

Because your local port is likely to vary over time depending on which port you bind it to, this is a good situation for overriding the backend configuration when you initialize your working directory. For example:

terraform init -backend-config="conn_str=..."

In the above example, you’ll need to replace ... with a suitable postgres:// URL describing how to reach your database via the SSH tunnel.