π -replace (Modern alternative to taint)
- Forces destroy + recreate of a resource in the same apply run β
- Change appears in
planas-/+before execution β - Safer & explicit than taint π‘
- Works without manually modifying state π
π Command
terraform apply -replace="aws_instance.app"π Plan output will show
# aws_instance.app will be replaced
-/+ destroy and then create
When to use π‘
1οΈβ£ Resource is corrupted (EC2, DB, etc.)
2οΈβ£ Provisioner left system in bad state
3οΈβ£ Want a fresh instance without touching config
π§° Terraform Provisioners
π Definition
- Run scripts/commands after resource creation
- Not recommended for regular use (final option) β
π Types
1οΈβ£ local-exec β Runs on Terraform host machine β
resource "aws_instance" "web" {
ami = "ami-0c02fb55956c7d316" # Amazon Linux 2
instance_type = "t2.micro"
provisioner "local-exec" {
command = "echo 'EC2 Created: ${self.public_ip}' >> ec2.log"
}
}2οΈβ£ remote-exec β Runs on remote server via SSH/WinRM β
resource "aws_instance" "web3" {
ami = "ami-0c02fb55956c7d316"
instance_type = "t2.micro"
connection {
type = "ssh"
user = "ec2-user"
private_key = file("~/.ssh/id_rsa")
host = self.public_ip
}
provisioner "remote-exec" {
inline = [
"chmod +x /tmp/install.sh",
"sudo /tmp/install.sh",
"sudo systemctl start nginx"
]
}
}3οΈβ£ file β Copies file to remote server β
resource "aws_instance" "web2" {
ami = "ami-0c02fb55956c7d316"
instance_type = "t2.micro"
connection {
type = "ssh"
user = "ec2-user"
private_key = file("~/.ssh/id_rsa")
host = self.public_ip
}
provisioner "file" {
source = "install.sh"
destination = "/tmp/install.sh"
}
}π Connection (only used by remote/file)
connection {
type = "ssh"
user = "ec2-user"
private_key = file("~/.ssh/id_rsa")
host = self.public_ip
}β Options
when = create(default) βon_failure = continueβ (doesnβt break apply)on_failure = failβ (stops apply)
β Key Notes
- If provisioner fails β resource still saved in state
- On resource replace (
-/+) β provisioner runs again - Better alternatives: EC2 User Data, Ansible, CI/CD scripts π‘