Skip to main content
Provisioners in OpenTofu enable you to execute scripts or commands either on remote resources or locally on the machine running the OpenTofu binary. They are useful for bootstrapping instances or performing cleanup tasks but should be used sparingly.

Provisioner Types

Remote-Exec Provisioner

Use remote-exec to run shell commands on a newly created EC2 instance. Place the provisioner block inside your resource:
  • A security group allowing SSH (22) or WinRM (5986 for Windows).
  • An SSH key pair created via aws_key_pair or your preferred key management.
  • Correct user name for your AMI (e.g., ubuntu, ec2-user, admin).

Example Resources

When you run tofu apply, you’ll see:

Local-Exec Provisioner

The local-exec provisioner runs commands on your workstation or CI/CD runner where OpenTofu is executed:
After tofu apply, verify the file:

Create-Time and Destroy-Time Hooks

By default, provisioners run after creation. You can also run them before destruction:

Handling Provisioner Failures

By default, a failed provisioner aborts the apply and marks the resource as tainted:
To continue despite errors, set on_failure = "continue":
Overusing on_failure = "continue" can hide critical bootstrap errors. Use it only when failures are non-fatal.

Best Practices

  • Use provisioners only as a last resort.
  • Prefer native options when available:
    • AWS: user_data
    • Azure: custom_data
    • GCP: metadata.startup-script
Example using AWS user_data:
Using user_data or cloud-init reduces complexity and maintains idempotency compared to provisioners.

Watch Video