In Terraform how to use a condition to only run on certain nodes?

Viewed 36

Terraform v1.2.8

I have a generic script that executes the passed-in shell script on my AWS remote EC2 instance that I've created also in Terraform.

resource "null_resource" "generic_script" {
  connection {
    type        = "ssh"
    user        = "ubuntu"
    private_key = file(var.ssh_key_file)
    host        = var.ec2_pub_ip
  }

  provisioner "file" {
    source      = "../modules/k8s_installer/${var.shell_script}"
    destination = "/tmp/${var.shell_script}"
  }

  provisioner "remote-exec" {
    inline = [
      "sudo chmod u+x /tmp/${var.shell_script}",
      "sudo /tmp/${var.shell_script}"
    ]
  }
}

Now I want to be able to modify it so it runs on

  • all nodes
  • this node but not that node
  • that node but not this node

So I created variables in the variables.tf file

variable "run_on_THIS_node" {
  type        = boolean
  description = "Run script on THIS node"
  default     = false
}

variable "run_on_THAT_node" {
  type        = boolean
  description = "Run script on THAT node"
  default     = false
}

How can I put a condition to achieve what I want to do?

resource "null_resource" "generic_script" {
  count = ???
  ...
}
1 Answers

You could use the ternary operator for this. For example, based on the defined variables, the condition would look like:

resource "null_resource" "generic_script" {
  count = (var.run_on_THIS_node || var.run_on_THAT_node) ? 1 : length(var.all_nodes) # or var.number_of_nodes
  ...
}

The piece of the puzzle that is missing is the variable (or a number) that would tell the script to run on all the nodes. It does not have to be with length function, you could define it as a number only. However, this is only a part of the code you would have to add/edit, as there would have to be a way to control the host based on the index. That means that you probably would have to modify var.ec2_pub_ip so that it is a list.

Related