πŸ” -replace (Modern alternative to taint)

  • Forces destroy + recreate of a resource in the same apply run βœ”
  • Change appears in plan as -/+ 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 πŸ’‘