Interview › Infrastructure as Code (Terraform, Ansible)
What is the difference between a data source and a resource?
Infrastructure as Code (Terraform, Ansible) · Basic level
Answer
A resource tells Terraform to create and manage an object. A data source reads an existing object or computed information without owning its lifecycle. For example, aws_vpc creates a VPC, while data.aws_ami reads the latest AMI ID for use by an instance.
Technical explanation
Data sources are read during planning and can introduce dependencies if their values are referenced.
Resources are owned by the current state and can be created, updated, or destroyed by Terraform.
Do not use a data source when Terraform should own lifecycle; do not create a resource when another team owns it.
Keep Terraform's ownership boundary clear: one state should own a resource or field, and other tools should consume published outputs instead of modifying it.
Use fmt, validate, linting, policy checks, plan review, and state locking before production applies.
Design for small blast radius by splitting state around lifecycle, permissions, and recovery boundaries.
Hands-on example
1. Create one resource and one data source side by side.
2. Use a data source for existing information and a resource for owned infrastructure:
data "aws_ami" "ubuntu" {
most_recent = true
owners = ["099720109477"]
filter { name = "name" values = ["ubuntu/images/hvm-ssd/ubuntu-jammy-22.04-amd64-server-*"] }
}
resource "aws_instance" "web" {
ami = data.aws_ami.ubuntu.id
instance_type = "t3.micro"
}3. Run plan and explain that Terraform reads the AMI but owns the EC2 instance lifecycle.
4. Delete the instance from code and see Terraform plan destruction; remove the data source and see no remote object deletion.
Check how well your resume matches the role with our free resume checker— match score, ATS check, and the skills you're missing.
More Infrastructure as Code (Terraform, Ansible) interview questions
- What is a dynamic block, and when would you use it?
- What is terraform import, and when do you need it?
- What problem does for_each solve that count creates when removing items?
- What is configuration drift, and how does Terraform detect it?
- What is the difference between count and for_each, and when do you use each?
- How do you handle resources changed manually outside Terraform?
- What are input variables, outputs, and locals?
- What are Terraform workspaces, and what are their limitations for environments?