Can not connect to PostgreSQL behind a tunnel
Closed this issue · 1 comments
I did exactly like in the documentation, but Terraform returned an error.
Tunnel:
module "tunnel" {
source = "flaupretre/tunnel/ssh"
version = "2.0.4"
gateway_host = aws_instance.app_ec2.public_ip
target_host = module.rds_postgresql.db_instance_address
target_port = module.rds_postgresql.db_instance_port
ssh_cmd = "ssh -o StrictHostKeyChecking=no -o PasswordAuthentication=no -i ${var.PRIVATE_KEY_PATH}"
}
Connection and working with DB. If I use a commented string then I get an error like dial tcp 127.0.0.1:22882:5432: connect: connection refused
.
provider "postgresql" {
alias = "master"
# host = "${module.tunnel.host}:${module.tunnel.port}"
host = module.tunnel.host
port = module.tunnel.port
username = local.db.app.username
password = local.db.app.password
database = local.db.app.name
sslmode = "require"
connect_timeout = 15
}
resource "postgresql_role" "pg_role" {
provider = postgresql.master
name = local.db.app_db.username
password = local.db.app_db.password
login = true
}
resource "postgresql_database" "pg_db" {
provider = postgresql.master
name = local.db.app_db.name
owner = local.db.app_db.username
}
And I get an error:
╷
│ Error: Error connecting to PostgreSQL server 127.0.0.1 (scheme: postgres): dial tcp 127.0.0.1:22882: connect: connection refused
│
│ with postgresql_role.pg_role,
│ on rds-postgresql.tf line 107, in resource "postgresql_role" "pg_role":
│ 107: resource "postgresql_role" "pg_role" {
│
╵
╷
│ Error: Error connecting to PostgreSQL server 127.0.0.1 (scheme: postgres): dial tcp 127.0.0.1:22882: connect: connection refused
│
│ with postgresql_database.pg_db,
│ on rds-postgresql.tf line 114, in resource "postgresql_database" "pg_db":
│ 114: resource "postgresql_database" "pg_db" {
│
╵
I have a project in a container on this server ( gateway_host
) that has a connection to this PostgreSQL instance.
I have found the solution.
If a user for SSH isn't present then will be used the username of a current local user for connection. Obviously, the user's name on my machine is different than in an EC2 instance.
So using gateway_user = local.ec2.user
is required for a successful connection. Initializing the module must be as follows:
module "tunnel" {
source = "flaupretre/tunnel/ssh"
version = "2.0.4"
gateway_host = aws_instance.app_ec2.public_ip
gateway_user = local.ec2.user # <---- I added this string!
target_host = module.rds_postgresql.db_instance_address
target_port = module.rds_postgresql.db_instance_port
ssh_cmd = "ssh -o StrictHostKeyChecking=no -o PasswordAuthentication=no -i ${var.PRIVATE_KEY_PATH}"
}
But why the module doesn't show an error that a tunnel was not established? Terraform returns an error right after trying a tunnel. It's very weird and confusing.
@flaupretre , please add the gateway_user
parameter to the examples.