Course contentsShow
← Cloud and Infrastructure
Lesson 823 of 2,98915. Terraform in PracticeFree lesson

Null Resources and Provisioners

Learn when and how to use null resources and provisioners for tasks outside Terraform's declarative model.

Null Resources and Provisioners

What you'll learn: How to use null resources and provisioners to handle tasks that fall outside Terraform's normal declarative model.

The Core Idea

Terraform excels at managing infrastructure declaratively—you describe what you want, and Terraform figures out how to create it. But sometimes you need to run arbitrary commands, scripts, or tasks that don't fit this model (like running a configuration script after a VM starts or triggering a webhook). That's where null resources and provisioners come in.

What Is a Null Resource?

A null resource (null_resource) is a special resource type that doesn't create any actual infrastructure. Think of it as a placeholder that exists only to trigger actions or track dependencies. It's useful when you need to run something based on Terraform's lifecycle but don't have a real resource to attach it to.

What Are Provisioners?

Provisioners are escape hatches that let you run scripts or commands during resource creation or destruction. Common types include local-exec (runs commands on your local machine) and remote-exec (runs commands on a remote resource via SSH).

Important caveat: Terraform documentation recommends avoiding provisioners when possible, because they break the declarative model and make your infrastructure harder to manage. Use them only when there's no better alternative.

When to Use Them

Use null resources and provisioners for:

  • Triggering external scripts after infrastructure changes
  • Running configuration management tools
  • Executing one-time setup tasks that can't be handled by cloud-init or user data

Example Pattern

resource "null_resource" "example" {
  triggers = {
    instance_id = aws_instance.web.id
  }

  provisioner "local-exec" {
    command = "echo Instance ${aws_instance.web.id} created"
  }
}

Key Takeaway: Null resources and provisioners handle imperative tasks outside Terraform's declarative model—use them sparingly and only when native resource arguments can't accomplish your goal.