4.1.1. resource Blocks
💡 First Principle: A resource block is a contract that says "make reality match this and keep it that way" — which is why Terraform will create, update, or destroy the real object to honor the block, and why removing the block triggers a destroy.
A resource block names a type (which provider owns it, e.g. aws_instance) and a local name (your label, unique within the module), followed by arguments:
resource "aws_instance" "web" {
ami = "ami-0abcd1234"
instance_type = "t3.micro"
lifecycle {
create_before_destroy = true
prevent_destroy = false
ignore_changes = [tags]
}
}
Beyond arguments, resources accept meta-arguments that change how Terraform manages them: count and for_each (create multiple instances), provider (select a provider configuration), depends_on (explicit ordering), and lifecycle. The lifecycle block is exam-relevant in 004: create_before_destroy makes Terraform build a replacement before destroying the old one (avoiding downtime), prevent_destroy blocks accidental deletion, and ignore_changes tells Terraform to stop reacting to drift on specific attributes.
⚠️ Exam Trap: create_before_destroy = true reverses the default replace order (default is destroy-then-create). It's the answer to "how do you replace a resource without downtime?" Don't confuse it with prevent_destroy, which simply refuses to destroy the resource at all and causes an error if a plan would.
Reflection Question: Why would create_before_destroy matter for a load-balanced web server but be irrelevant for a one-off scratch database?