Terraform by Example: Resources
Resources are the fundamental building blocks of Terraform infrastructure. This code example demonstrates creating an AWS EC2 instance with lifecycle management and explicit dependencies.
Code
resource "aws_instance" "web_server" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
tags = {
Name = "ExampleAppServerInstance"
}
# Meta-arguments
lifecycle {
create_before_destroy = true
prevent_destroy = false
}
}
# Resource dependency
resource "aws_eip" "ip" {
instance = aws_instance.web_server.id
domain = "vpc"
}Explanation
Resources are the core components of any Terraform configuration, representing infrastructure objects like virtual machines, networks, or DNS records. Each resource block declares a specific infrastructure object that Terraform is responsible for creating, updating, and managing the lifecycle of. The syntax resource "type" "name" defines a unique identifier for the resource within the module.
Beyond basic configuration, resources support powerful meta-arguments that control their behavior. The lifecycle block is particularly useful for managing updates, allowing you to specify rules like create_before_destroy to ensure zero-downtime replacements, or prevent_destroy to protect critical infrastructure from accidental deletion.
Terraform automatically handles dependencies between resources. When you reference an attribute of one resource (like aws_instance.web_server.id) in another, Terraform infers the dependency and ensures they are created in the correct order. This implicit dependency management simplifies the orchestration of complex infrastructure stacks.
Code Breakdown
aws_instance specifies the resource type provided by the AWS provider.tags block assigns metadata like the instance Name.lifecycle block controls operational behavior like replacement strategy.create_before_destroy ensures the new resource is up before removing the old one.aws_instance.web_server.id creates an implicit dependency by referencing the ID.
