0
0
TerraformConceptBeginner · 3 min read

When to Use Provisioner in Terraform: Simple Guide

Use provisioner in Terraform when you need to run scripts or commands on a resource after it is created or before it is destroyed. They help with tasks like software installation or configuration that Terraform cannot manage directly.
⚙️

How It Works

Think of Terraform as a builder who creates your infrastructure pieces like servers or databases. Sometimes, after building, you want to decorate or set up the inside, like installing software or copying files. Provisioners are like helpers who enter the finished building to do these extra tasks.

They run scripts or commands on the resource after Terraform creates it or before it deletes it. This way, you can automate setup steps that Terraform alone can't handle, such as configuring a server or running a custom script.

💻

Example

This example shows a simple local-exec provisioner that runs a command on your local machine after creating an AWS EC2 instance.

terraform
resource "aws_instance" "example" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"

  provisioner "local-exec" {
    command = "echo Instance created with ID: ${self.id}"
  }
}
Output
Instance created with ID: i-0abcd1234efgh5678
🎯

When to Use

Use provisioners when you need to perform setup tasks that Terraform cannot do by itself, such as:

  • Installing software on a new server
  • Running configuration scripts
  • Copying files to a resource
  • Triggering commands before resource destruction

However, avoid using provisioners for regular resource management because they can make your setup less predictable and harder to maintain. Instead, use them only when no other Terraform resource or provider supports the task.

Key Points

  • Provisioners run scripts or commands on resources after creation or before destruction.
  • They help with tasks Terraform cannot manage directly.
  • Use them sparingly to keep infrastructure predictable.
  • Common types are local-exec and remote-exec.
  • Prefer native Terraform resources or providers when possible.

Key Takeaways

Use provisioners to run setup scripts on resources after creation or before deletion.
Provisioners are best for tasks Terraform cannot handle natively, like software installs.
Avoid overusing provisioners to keep your infrastructure stable and easy to manage.
Common provisioners include local-exec for local commands and remote-exec for remote commands.
Always prefer native Terraform resources or providers before resorting to provisioners.