Run local commands and scripts with Terraform

Aug 06, 2022 · 2 mins read · Post a comment

Every once in a while, using built-in Terraform modules is just not enough. From time to time as new cloud features are developed and released, there is no native support yet, so it always takes time for them to be added in the respective TF module pipelines. This often leads to applying manual cloud CLI command steps, and from my experience, either go full on IaC or don’t do it at all.

In this case, null_resource and the local-exec provisioner are go-to for any action that needs manual steps – from running CLI commands to invoking shell scripts.


  • Terraform


The null_resource acts as any TF resource does, but without doing anything. Sounds weird, so what’s the catch. You can think of it as a resource so that you can attach provisioners as a last resort for any manual jobs that needs to be executed. And, this is where the local-exec provisioner comes in hand. It allows us to invoke any local shell command / script. For instance, you could run a simple script with arguments:

## variables.tf
variable "vm_names" {
  description = "List of VMs that needs to be scheduled for start / start"
  type        = list(string)
  default     = ["devcoops-web1"]

## main.tf
resource "null_resource" "stop_vms" {

  triggers = {
    shell_hash = "${sha256(file("${path.module}/stop_vms.sh"))}"
    vm_names   = var.vm_names

  provisioner "local-exec" {
    command     = "./stop_vms.sh ${vm_names}"
    interpreter = ["/bin/bash", "-c"]

or running simple “Hello World” command:

resource "null_resource" "hello_world" {

  provisioner "local-exec" {
    command = "echo HELLO WORLD"

Note(s): Anything that runs under the local-exec provisioner can’t be stored in the TF state. If you need some changes to be made, make sure to include the triggers argument. Adding variables to triggers will prompt for new deployment on every variable’s value update.


If you want to see more, here’s some related posts including the null_resource / local-exec:

Tried everything and nothing works? Let me know in the comment section below. On a side note, follow our official channel on Telegram.