Lesson 2 of 8 · 11 min · Writing configuration
Providers, resources and dependencies (AWS example)
What you will learn
- Providers: what they are, how to configure and pin them
- Resources and data sources, and the
TYPE.NAME.ATTRIBUTEreference syntax - Implicit and explicit dependencies, and the dependency graph
- A complete AWS configuration (network, firewall, storage, IAM) with real plan output
- What changes in place and what forces replacement
In simple words
Terraform doesn't know AWS or Azure by itself. It uses plug-ins called providers that speak to each cloud. In your files you describe resources, the things you want to exist, and Terraform works out the right order, because a server can't be created before the network it sits in.
Words to know
- Provider: the plug-in that lets Terraform talk to one platform, such as AWS.
- Resource: one thing Terraform manages, such as a server or a storage bucket.
- Data source: a way to look up something that already exists, without managing it.
- Dependency: one resource needing another to exist first.
Providers
Terraform core knows nothing about AWS or Kubernetes. Providers are plugins that translate resources into API calls for a platform. The Terraform Registry lists thousands: hashicorp/aws, hashicorp/azurerm, hashicorp/google, hashicorp/kubernetes, integrations/github, cloudflare/cloudflare, hashicorp/random, and so on. You declare which you need and Terraform downloads them in init:
terraform {
required_version = ">= 1.6"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
}
provider "aws" {
region = "ap-south-1"
}
sourceisnamespace/typeon the registry.versionconstraints:~> 5.0means>= 5.0, < 6.0(accept minor and patch updates, not a new major). The lock file pins the exact version chosen (we got5.100.0). Upgrade deliberately withterraform init -upgradeand review the plan.- The provider block holds configuration: region, default tags, assume-role settings. Credentials come from the environment or an assumed role/OIDC, never from literals in code. Use
aliasto configure several instances (two regions, two accounts).
To follow along without an AWS account, point the provider at a local AWS emulator by overriding endpoints and using dummy credentials. On real AWS you simply omit all that.
Resources
A resource block declares one infrastructure object:
resource "aws_vpc" "main" {
cidr_block = "10.0.0.0/16"
enable_dns_hostnames = true
tags = merge(local.tags, { Name = "${var.env}-vpc" })
}
aws_vpc is the resource type (provider prefix + kind), main the local name used to refer to it (unique per type within the module). The arguments are the settings; the provider documents each one, and which are required, optional, or "computed" (set by the cloud after creation, such as ids and ARNs). Every resource type's documentation page on the registry lists arguments, attributes (readable results) and an import command: bookmark it, it is your main reference.
References and dependencies
You use one resource's attributes in another with TYPE.NAME.ATTRIBUTE:
resource "aws_subnet" "public" {
for_each = { a = "10.0.1.0/24", b = "10.0.2.0/24" }
vpc_id = aws_vpc.main.id # reference
cidr_block = each.value
availability_zone = "ap-south-1${each.key}"
tags = merge(local.tags, { Name = "${var.env}-public-${each.key}" })
}
Because vpc_id uses aws_vpc.main.id, Terraform knows the subnet depends on the VPC and creates the VPC first. This is an implicit dependency, and it is how nearly all ordering is expressed. Terraform builds a dependency graph of all resources and walks it: independent branches run in parallel, dependent ones in order; on destroy, in reverse. terraform graph prints it (DOT format).
When a dependency exists but is not visible in an attribute reference (a policy that must exist before an instance starts), declare an explicit one: depends_on = [aws_iam_role_policy.x]. Use it sparingly; prefer real references.
Data sources
A data source reads something that already exists (or computes something) without managing it:
data "aws_iam_policy_document" "read_assets" {
statement {
actions = ["s3:GetObject", "s3:ListBucket"]
resources = [aws_s3_bucket.assets.arn, "${aws_s3_bucket.assets.arn}/*"]
}
}
resource "aws_iam_policy" "read_assets" {
name = "${var.env}-read-assets"
policy = data.aws_iam_policy_document.read_assets.json
}
Other common data sources: aws_ami (find the latest image), aws_availability_zones, aws_caller_identity (current account id), aws_vpc (look up an existing network), terraform_remote_state (read another stack's outputs). Data sources are read during plan and let one stack use things managed elsewhere.
A tested AWS example
Putting it together: a network, a firewall rule, a versioned bucket and a read-only policy (the VPC and subnet blocks are the ones shown above; the rest follows).
resource "aws_security_group" "web" {
name = "${var.env}-web"
description = "Allow HTTPS from anywhere"
vpc_id = aws_vpc.main.id
ingress {
from_port = 443
to_port = 443
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
tags = local.tags
}
resource "aws_s3_bucket" "assets" {
bucket = "shop-${var.env}-assets-demo"
tags = local.tags
}
resource "aws_s3_bucket_versioning" "assets" {
bucket = aws_s3_bucket.assets.id
versioning_configuration {
status = "Enabled"
}
}
terraform plan listed seven resources to create, in no particular textual order, ordered correctly by the graph:
aws_iam_policy.read_assets will be created
aws_s3_bucket.assets will be created
aws_s3_bucket_versioning.assets will be created
aws_security_group.web will be created
aws_subnet.public["a"] will be created
aws_subnet.public["b"] will be created
aws_vpc.main will be created
Plan: 7 to add, 0 to change, 0 to destroy.
and apply created them, printing the outputs vpc_id and subnet_ids. terraform state list then showed each with its address, including aws_subnet.public["a"] (the key from for_each) and the data source.
In place or replace?
Which change is cheap and which is destructive depends on the attribute. Changing a tag value:
aws_vpc.main will be updated in-place
aws_s3_bucket.assets will be updated in-place
aws_security_group.web will be updated in-place
...
Changing the VPC's CIDR block is a different story:
# aws_vpc.main must be replaced
~ cidr_block = "10.0.0.0/16" -> "10.1.0.0/16" # forces replacement
# aws_subnet.public["a"] must be replaced
~ vpc_id = "vpc-ffafb4dc" -> (known after apply) # forces replacement
# aws_security_group.web must be replaced
~ vpc_id = ... # forces replacement
A VPC's range cannot be edited, so it is destroyed and recreated, and everything that depends on it is replaced too (the dependency cascade). With a real network this would take down every server in it. This is exactly why you read plans: # forces replacement on a foundational resource is a stop sign. To reduce risk use lifecycle { prevent_destroy = true } for critical resources, create_before_destroy where a replacement can run beside the old one, and design environments so that foundations rarely change.
Good habits for resources
- Tag everything (project, environment, owner, managed-by) via
default_tagsin the provider or alocal.tagsmap: tags drive cost reports and clean-up. - Name consistently (
${var.env}-${purpose}), but let the cloud generate unique names where required (S3 bucket names are global). - One resource, one purpose: AWS provider 4+ splits S3 settings into separate resources (versioning, encryption, lifecycle) instead of one huge block, as above.
- Prefer the provider's secure defaults and add encryption, versioning, public-access blocks explicitly.
- Read the provider's changelog before upgrading majors: arguments move between resources.
- Do not hard-code IDs (AMIs, account numbers, subnet ids): reference resources or look them up with data sources.
Common mistakes
- Hard-coded values that differ between environments.
- Missing
versionconstraints for providers. - Overusing
depends_oninstead of references. - Not noticing
forces replacementon a database, disk or network. - Using
countwith lists where removing an element shifts all later indices (next lesson). - Putting credentials in provider blocks.
- Copying resource arguments from old blog posts for a provider version that changed them.
Try it yourself
- Write a configuration for a VPC with two subnets and a security group. Run
planand read the order. Runterraform graph | dot -Tpng > graph.png(Graphviz) to see the dependency graph. - Add a tag and confirm an in-place update. Change an immutable argument and find
forces replacement. - Add a data source (
aws_availability_zones) and use its names instead of hard-coding zones. - Look up
aws_instanceon the registry and list which arguments are required.
Check yourself
What is a provider?
A plugin that lets Terraform manage a platform's resources through its API (AWS, Kubernetes, GitHub and others). It is declared in required_providers, configured in a provider block and downloaded by init.
How does Terraform know to create the VPC before the subnet?
The subnet refers to aws_vpc.main.id, which creates an implicit dependency in the graph. Terraform orders creation (and reverses it on destroy) accordingly.
What is the difference between a resource and a data source?
A resource is created and managed by Terraform; a data source only reads existing information (or computes a value) and never changes anything.
What does ~> 5.0 mean in a version constraint?
Any version from 5.0 up to but excluding 6.0: new minor and patch releases are allowed, a new major is not.
Interview questions
Terraform wants to replace your production database. How do you react?
Stop and read why: find the # forces replacement argument. Avoid the change if possible, use prevent_destroy, plan a migration (snapshot, new resource, cut over), or ignore_changes/moved blocks if it is just a rename. Never apply unreviewed.
How do you create resources in two regions?
Declare two provider "aws" blocks with an alias and select one in each resource (provider = aws.mumbai), or pass providers to modules.
When do you need depends_on?
When one resource depends on another's side effect that is not visible through an attribute reference, such as an IAM policy attachment that must exist before a service starts.
Summary
- Providers translate Terraform resources into platform API calls; pin versions and let the lock file record the exact build.
- Resources are managed; data sources are read-only. References create the dependency graph automatically.
- Whether a change is in-place or a replacement depends on the attribute; replacements cascade through dependencies, so read every plan.
- Tag, name and secure resources consistently; never hard-code credentials or ids.
Going deeper
- Terraform Registry: providers, resources and modules documentation.
- AWS provider documentation: every AWS resource and data source.
- Resource behaviour and dependencies: the dependency graph in detail.
- Provider requirements and versions:
required_providersand constraints. - Data sources: reading existing information.
See how much of this you can explain
A free mock interview asks you new questions on Infrastructure as Code with Terraform for DevOps Engineer and scores every answer, with what to fix.