Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Provisioner local-exec: 'always_run' trigger doesn't work as expected

Tags:

terraform

In my terraform I have mysql module as follows:

# create ssh tunnel to RDS instance
resource "null_resource" "ssh_tunnel" {
  provisioner "local-exec" {
    command = "ssh -i ${var.private_key} -L 3306:${var.rds_endpoint} -fN ec2-user@${var.bastion_ip} -v >./stdout.log 2>./stderr.log"
  }
  triggers = {
    always_run = timestamp()
  }
}

# create database
resource "mysql_database" "rds" {
  name = var.db_name
  depends_on = [null_resource.ssh_tunnel]
}

When I'm adding new module and running terraform apply first time it works as expected. But when terraform apply running without any changes I'm getting an error:

Could not connect to server: dial tcp 127.0.0.1:3306: connect: connection refused

If I understand correctly, provisioner "local-exec" should execute script every time due to the trigger settings. Could you explain how should it works properly?

like image 443
local Avatar asked Nov 16 '25 00:11

local


2 Answers

I suspect that this happens because your first local-exec creates the tunnel in the background (-f). Then second execution fails because the first tunnel still exists. You do not close it at all in your code. You would have to extend your code to check for an existence of tunnels and maybe properly close them when you are done using them.

like image 195
Marcin Avatar answered Nov 18 '25 21:11

Marcin


Finally I've implemented this solution https://registry.terraform.io/modules/flaupretre/tunnel/ssh/latest instead of using null_resource.

like image 20
local Avatar answered Nov 18 '25 19:11

local