terraform_data is a built-in Terraform resource that represents arbitrary data without managing a specific infrastructure object. Added in Terraform 1.4, it provides a provider-free alternative to null_resource for lifecycle behavior, testing, replacement triggers, and provisioners. section 6.8.4
Use terraform_data when Terraform needs a managed lifecycle node rather than another infrastructure object:
- Store an input expression and expose its result through the resource output, making it useful for inexpensive test modules. section 11.1.4
- Set triggers_replace to an expression so changes replace terraform_data and can propagate replacement through replace_triggered_by. section 6.8.4
- Attach provisioners independently of a specific resource, combining multiple dependencies so a provisioner runs when any trigger changes. section 10.3.5
Triggering a replacement from local logic
A local expression can drive terraform_data replacement even when replace_triggered_by cannot directly accept the variable or local expression. An aws_instance can then declare lifecycle.replace_triggered_by = [terraform_data.local_replacement]. section 6.8.4
Listing 10.19 Using terraform_data for provisioning
resource "terraform_data" "provisioners" { #1
connection {
type = "ssh"
user = "ubuntu"
private_key = file("~/.ssh/id_rsa")
host = aws_instance.main.public_ip #2
}
provisioner "remote-exec" {
script = "${path.module}/scripts/initialize.sh"
}
depends_on = [ #3
aws_instance.main,
aws_db_instance.main
]
}
This configuration shows terraform_data managing a remote-exec provisioner after an instance and database are available, with an SSH connection and explicit dependencies. section 10.3.5
For testing, terraform_data can carry harmless values through a low-cost module. Native Terraform tests can assert its output during apply; plan-based assertions must use values known during planning, or they fail with an unknown condition. section 11.1.4 section 9.4.1
