You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Resources and data sources are the building blocks of every Terraform configuration. Resources create and manage infrastructure, while data sources read existing information. This lesson covers how to define, reference, and connect them.
A resource block declares a piece of infrastructure that Terraform will manage:
resource "aws_instance" "web" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t3.micro"
tags = {
Name = "web-server"
}
}
Every resource has a unique address: <type>.<name>
aws_instance.web — the resource abovegoogle_compute_instance.api — a GCP compute instance named "api"| Term | When Set | Example |
|---|---|---|
| Argument | In your configuration (input) | instance_type = "t3.micro" |
| Attribute | After creation (output) | aws_instance.web.public_ip |
You reference attributes of one resource in another to create implicit dependencies.
Resources support special meta-arguments that change their behaviour:
Create multiple instances of a resource:
resource "aws_instance" "web" {
count = 3
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t3.micro"
tags = {
Name = "web-${count.index}"
}
}
Access individual instances: aws_instance.web[0], aws_instance.web[1], etc.
Create instances from a map or set:
resource "aws_s3_bucket" "buckets" {
for_each = toset(["logs", "data", "backups"])
bucket = "${var.prefix}-${each.key}"
}
Access individual instances: aws_s3_bucket.buckets["logs"].
Explicitly declare dependencies when Terraform cannot infer them:
resource "aws_instance" "web" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t3.micro"
depends_on = [aws_iam_role_policy.web_policy]
}
Use a non-default provider configuration:
resource "aws_instance" "eu_web" {
provider = aws.eu
ami = "ami-0abc12345def67890"
instance_type = "t3.micro"
}
| Feature | count | for_each |
|---|---|---|
| Input | Number | Map or Set |
| Index | count.index (integer) | each.key / each.value |
| Reordering | Shifting indices causes recreation | Stable — keyed by name |
| Best for | Identical resources | Resources with unique attributes |
Tip: Prefer
for_eachovercountwhen resources have distinct identities. Removing an item from acountlist shifts all subsequent indices, causing unnecessary resource recreation.
A data source reads information from an existing resource that Terraform does not manage:
data "aws_ami" "ubuntu" {
most_recent = true
owners = ["099720109477"] # Canonical
filter {
name = "name"
values = ["ubuntu/images/hvm-ssd/ubuntu-jammy-22.04-amd64-server-*"]
}
}
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.