Terraform Resources & Data Sources: Managing Infrastructure
Terraform resources are the core building blocks that represent infrastructure components, while data sources let you query existing infrastructure for use in your configurations.
What You'll Learn
In this tutorial, you will learn how to define Terraform resources and data sources, reference attributes between resources, manage dependencies, and use lifecycle rules for safe infrastructure changes.
Why It Matters
Resources are how you create and manage infrastructure. Data sources let you read information from existing infrastructure without modifying it. Together they form the foundation of every Terraform configuration.
Real-World Use
DodaTech uses AWS resources to define auto-scaling groups, RDS databases, and VPC networking for Durga Antivirus Pro's backend. Data sources fetch the latest AMI IDs, existing VPCs, and current AWS account details.
Resources
Every resource block creates, updates, or destroys a single infrastructure object. The syntax is resource "type" "name" { ... }.
resource "aws_instance" "web" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
tags = {
Name = "WebServer"
}
}
Expected output: Terraform creates one EC2 instance with the specified AMI, instance type, and name tag.
Resource Attributes
Resources expose attributes you can reference in other parts of your configuration:
resource "aws_instance" "web" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
}
output "instance_ip" {
value = aws_instance.web.public_ip
}
output "instance_id" {
value = aws_instance.web.id
}
Expected output: After apply, the outputs show the public IP address and instance ID of the created EC2 instance.
Resource Dependencies
Terraform builds a dependency graph automatically from references. Explicit dependencies use depends_on:
resource "aws_s3_bucket" "data" {
bucket = "my-app-data-bucket"
}
resource "aws_instance" "web" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
depends_on = [aws_s3_bucket.data]
}
Expected output: Terraform creates the S3 bucket before the EC2 instance, ensuring the bucket exists when the instance tries to use it.
Data Sources
Data sources read information from existing infrastructure managed outside Terraform or created by other configurations:
data "aws_ami" "ubuntu" {
most_recent = true
owners = ["099720109477"]
filter {
name = "name"
values = ["ubuntu/images/hvm-ssd/ubuntu-22.04-amd64-server-*"]
}
}
resource "aws_instance" "web" {
ami = data.aws_ami.ubuntu.id
instance_type = "t2.micro"
}
Expected output: The data source fetches the latest Ubuntu 22.04 AMI ID. The EC2 instance uses this ID, ensuring it always launches with the current AMI.
Combining Resources and Data Sources
data "aws_vpc" "default" {
default = true
}
data "aws_subnets" "default" {
filter {
name = "vpc-id"
values = [data.aws_vpc.default.id]
}
}
resource "aws_security_group" "web" {
name = "web-sg"
vpc_id = data.aws_vpc.default.id
ingress {
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
}
Expected output: Terraform queries the default VPC and its subnets, then creates a security group allowing HTTP traffic within that VPC.
Lifecycle Rules
Lifecycle rules control how Terraform creates, updates, and destroys resources:
resource "aws_instance" "web" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
lifecycle {
create_before_destroy = true
prevent_destroy = true
ignore_changes = [ami]
}
}
Expected output: create_before_destroy creates a new instance before destroying the old one during updates. prevent_destroy blocks any destroy operation. ignore_changes prevents Terraform from replacing the instance when the AMI changes externally.
Common Mistakes
1. Creating Resources That Already Exist
Using <a href="/devops/terraform/">terraform</a> apply on resources that already exist outside Terraform causes errors. Use <a href="/devops/terraform/">terraform</a> import to bring them under management.
2. Missing Required Arguments
Every resource has required arguments. Omitting them causes plan errors. Check provider documentation for required fields.
3. Circular Dependencies
Resource A depends on B, and B depends on A. Terraform detects this and returns a dependency cycle error.
4. Incorrect Data Source Filtering
Data sources with incorrect filters return empty or wrong results. Always test filters with <a href="/devops/terraform/">terraform</a> plan.
5. Not Using Lifecycle Rules for Critical Resources
Database instances and load balancers without prevent_destroy can be accidentally deleted by <a href="/devops/terraform/">terraform</a> destroy.
Practice Questions
1. What is the difference between a resource and a data source? A resource creates, updates, and destroys infrastructure. A data source reads existing infrastructure without modifying it.
2. How does Terraform handle resource dependencies?
Terraform automatically builds a dependency graph from attribute references. Explicit depends_on handles dependencies Terraform cannot infer.
3. What are three lifecycle rules and their purposes?
create_before_destroy minimizes downtime. prevent_destroy blocks accidental deletion. ignore_changes prevents updates from external modifications.
4. How do you reference an attribute from another resource?
Use the syntax resource_type.resource_name.attribute_name, for example aws_instance.web.public_ip.
5. Challenge: Write a configuration with a VPC data source, a security group using it, and an EC2 instance using the security group -- all with proper dependency ordering.
Mini Project: Complete Web Stack
Create resources for an S3 bucket, a security group, an EC2 instance, and an Elastic IP. Use data sources to fetch the default VPC and latest Amazon Linux AMI. Verify all resources are created and properly referenced.
Related Concepts
What's Next
Master resources and data sources, then make configurations dynamic with Variables, Locals and Outputs for reusable and parameterized infrastructure.
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro