0
0
Terraformcloud~15 mins

Local-exec provisioner in Terraform - Deep Dive

Choose your learning style9 modes available
Overview - Local-exec provisioner
What is it?
The local-exec provisioner in Terraform runs commands on the machine where Terraform is executed. It allows you to execute scripts or shell commands locally during resource creation or destruction. This helps automate tasks that need to happen outside the cloud or infrastructure itself. It is useful for setup steps that cannot be done directly by cloud providers.
Why it matters
Without the local-exec provisioner, you would have to manually run commands or scripts after Terraform finishes, which can cause errors or delays. It solves the problem of automating local tasks tied to infrastructure changes, making deployments smoother and more reliable. This saves time and reduces mistakes in managing cloud resources and related local configurations.
Where it fits
Before learning local-exec, you should understand basic Terraform resources and how Terraform manages infrastructure state. After mastering local-exec, you can explore remote-exec provisioners and advanced automation with Terraform modules and external tools.
Mental Model
Core Idea
Local-exec provisioner runs commands on your local machine as part of Terraform's resource lifecycle.
Think of it like...
It's like having a personal assistant who, whenever you buy a new gadget, immediately sets it up on your desk instead of waiting for you to do it later.
Terraform Resource
  │
  ├─ Creates or updates cloud resource
  │
  └─ Triggers local-exec provisioner
       │
       └─ Runs command/script on local machine
Build-Up - 7 Steps
1
FoundationWhat is a provisioner in Terraform
🤔
Concept: Provisioners run scripts or commands during resource creation or destruction.
Terraform provisioners let you execute actions tied to resource lifecycle events. They can run locally or remotely. Local-exec runs commands on your computer, while remote-exec runs commands on the created resource itself.
Result
You understand that provisioners automate tasks during infrastructure changes.
Knowing provisioners exist helps you automate beyond just creating resources, bridging infrastructure and configuration.
2
FoundationBasics of local-exec provisioner syntax
🤔
Concept: Local-exec provisioner uses a command block inside a resource to run local commands.
Example: resource "null_resource" "example" { provisioner "local-exec" { command = "echo Hello from local machine" } } This runs the echo command on your local machine when the resource is created.
Result
Terraform runs the specified command locally during apply.
Understanding the syntax lets you start automating local tasks tied to resource changes.
3
IntermediateWhen local-exec runs during lifecycle
🤔Before reading on: Do you think local-exec runs only on resource creation, or also on updates and deletions? Commit to your answer.
Concept: Local-exec runs during create, update, and destroy phases depending on configuration.
By default, local-exec runs when the resource is created. You can also configure it to run on destroy by adding a 'when = destroy' argument. This lets you automate cleanup or setup tasks tied to resource lifecycle.
Result
You can control when local commands run, matching your automation needs.
Knowing lifecycle triggers prevents surprises and lets you automate both setup and teardown steps.
4
IntermediatePassing variables and outputs to local-exec
🤔Before reading on: Can local-exec access Terraform variables and resource outputs directly inside commands? Guess yes or no.
Concept: You can use Terraform interpolation to pass variables and outputs into local-exec commands.
Example: resource "null_resource" "example" { provisioner "local-exec" { command = "echo Resource ID is ${self.id}" } } Here, ${self.id} is replaced by Terraform with the resource's ID before running the command.
Result
Commands can dynamically use Terraform data, making automation flexible.
Understanding interpolation lets you connect Terraform state with local scripts seamlessly.
5
IntermediateHandling errors and command outputs
🤔Before reading on: Do you think local-exec failures stop Terraform apply by default? Commit to yes or no.
Concept: Local-exec errors cause Terraform to fail unless ignored; output is shown in logs.
If the local command returns a non-zero exit code, Terraform stops and reports an error. You can add 'ignore_errors = true' to continue despite failures. Command output appears in Terraform logs, helping debug.
Result
You can control error handling and see command results during runs.
Knowing error behavior helps you write robust automation that fails safely or continues as needed.
6
AdvancedUsing local-exec for complex automation
🤔Before reading on: Is local-exec suitable for long-running or interactive scripts? Guess yes or no.
Concept: Local-exec is best for short, non-interactive commands; complex automation may need external tools.
Local-exec runs commands synchronously and waits for completion. Long or interactive scripts can block or fail. For complex workflows, use external CI/CD pipelines or configuration management tools triggered by Terraform outputs.
Result
You avoid misusing local-exec and choose better tools for complex tasks.
Understanding local-exec limits prevents automation bottlenecks and failures.
7
ExpertSecurity and environment considerations
🤔Before reading on: Does local-exec run with the same environment as Terraform? Can it access sensitive data safely? Commit your thoughts.
Concept: Local-exec runs with the user's environment and can expose sensitive data if not handled carefully.
Commands run with your shell environment, so environment variables and credentials are accessible. Avoid printing secrets in logs. Use environment variables or files securely. Be cautious running local-exec in shared or automated environments to prevent leaks.
Result
You write secure local-exec commands that protect sensitive information.
Knowing environment and security risks helps prevent accidental data exposure in automation.
Under the Hood
Terraform executes local-exec provisioner by spawning a shell process on the machine running Terraform. It passes the command string to the shell, waits for it to finish, and captures the exit code and output. Terraform uses this to decide success or failure of the provisioner step. The provisioner runs synchronously within the resource lifecycle, blocking further steps until completion.
Why designed this way?
Local-exec was designed to allow users to run arbitrary local commands tied to resource changes without needing remote access or complex orchestration. It leverages the local machine's environment for flexibility. Alternatives like remote-exec require SSH or API access to resources, which is not always possible or desired. This design balances power and simplicity.
Terraform Apply
  │
  ├─ Create/Update Resource
  │    │
  │    └─ Trigger local-exec provisioner
  │          │
  │          ├─ Spawn shell process locally
  │          ├─ Run command/script
  │          ├─ Capture output and exit code
  │          └─ Return success/failure to Terraform
  │
  └─ Continue or stop based on provisioner result
Myth Busters - 4 Common Misconceptions
Quick: Does local-exec run commands on the cloud resource itself? Commit yes or no.
Common Belief:Local-exec runs commands inside the cloud resource like a remote shell.
Tap to reveal reality
Reality:Local-exec runs commands only on the machine where Terraform runs, not on the cloud resource.
Why it matters:Confusing local-exec with remote-exec leads to failed automation and wasted troubleshooting time.
Quick: Will local-exec commands run every time you run terraform apply? Commit yes or no.
Common Belief:Local-exec runs every time you apply Terraform, regardless of resource changes.
Tap to reveal reality
Reality:Local-exec runs only when the resource it is attached to is created, updated, or destroyed.
Why it matters:Expecting local-exec to run always can cause missed automation steps or unexpected behavior.
Quick: Can local-exec provisioner be used for long interactive scripts safely? Commit yes or no.
Common Belief:Local-exec is suitable for any script, including long or interactive ones.
Tap to reveal reality
Reality:Local-exec is synchronous and not designed for long-running or interactive scripts; these can cause blocking or failures.
Why it matters:Misusing local-exec for complex scripts can stall Terraform runs and cause deployment failures.
Quick: Does local-exec automatically handle sensitive data securely? Commit yes or no.
Common Belief:Local-exec protects sensitive data automatically during command execution.
Tap to reveal reality
Reality:Local-exec runs commands with full access to environment and can expose secrets if not handled carefully.
Why it matters:Assuming automatic security can lead to accidental leaks of credentials or secrets.
Expert Zone
1
Local-exec runs with the user's shell environment, so differences in shells or OS can affect command behavior subtly.
2
Terraform does not retry failed local-exec commands automatically; handling retries requires external scripting or tooling.
3
Local-exec provisioners do not create dependencies between resources automatically; explicit depends_on is needed to order execution.
When NOT to use
Avoid local-exec for complex, long-running, or interactive automation tasks. Instead, use remote-exec provisioners, configuration management tools like Ansible, or CI/CD pipelines triggered by Terraform outputs.
Production Patterns
In production, local-exec is often used for simple local setup tasks like generating files, notifying systems, or running quick scripts. It is combined with remote-exec for resource configuration and external orchestration for complex workflows.
Connections
Remote-exec provisioner
Complementary concept; local-exec runs commands locally, remote-exec runs commands on remote resources.
Understanding both provisioners helps design complete automation that covers local and remote configuration steps.
CI/CD pipelines
Builds-on local-exec by moving complex automation outside Terraform into dedicated automation systems.
Knowing local-exec limits encourages using CI/CD tools for scalable, maintainable infrastructure automation.
Operating system shell scripting
Local-exec runs shell commands, so knowledge of shell scripting directly improves local-exec usage.
Mastering shell scripting empowers writing effective local-exec commands that integrate smoothly with Terraform.
Common Pitfalls
#1Running local-exec commands that depend on resources not yet created.
Wrong approach:resource "null_resource" "example" { provisioner "local-exec" { command = "cat /tmp/resource_output.txt" } } resource "aws_instance" "web" { # instance config }
Correct approach:resource "aws_instance" "web" { # instance config } resource "null_resource" "example" { depends_on = [aws_instance.web] provisioner "local-exec" { command = "cat /tmp/resource_output.txt" } }
Root cause:Terraform may run local-exec before the resource output file exists because dependencies were not declared.
#2Ignoring errors in local-exec without intention.
Wrong approach:provisioner "local-exec" { command = "exit 1" ignore_errors = false }
Correct approach:provisioner "local-exec" { command = "exit 1" ignore_errors = true }
Root cause:By default, local-exec failures stop Terraform; forgetting ignore_errors causes unexpected apply failures.
#3Embedding sensitive secrets directly in local-exec commands.
Wrong approach:provisioner "local-exec" { command = "echo 'password=MySecret123' > secret.txt" }
Correct approach:provisioner "local-exec" { command = "echo 'password=${var.secret_password}' > secret.txt" environment = { secret_password = var.secret_password } }
Root cause:Hardcoding secrets in commands risks exposure in logs and version control.
Key Takeaways
Local-exec provisioner runs commands on your local machine during Terraform resource lifecycle events.
It is useful for automating local tasks that cannot be done directly on cloud resources.
Local-exec runs synchronously and can be configured to run on create, update, or destroy phases.
Proper error handling and secure management of sensitive data are critical when using local-exec.
For complex or long-running automation, use remote-exec or external tools instead of local-exec.