Terraform – Resources: Interview Questions & Answers
1. What is a resource in Terraform?
A resource represents a piece of infrastructure that Terraform manages. This can be
compute instances, storage buckets, databases, DNS records, etc.
2. How do you define a resource in Terraform?
You define a resource using the `resource` block. Example:
resource "aws_instance" "example" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
}
3. What are the parts of a resource block?
A resource block consists of:
- Resource type (e.g., aws_instance)
- Resource name (e.g., example)
- Configuration arguments (e.g., ami, instance_type)
4. How does Terraform handle resource dependencies?
Terraform automatically handles dependencies based on references between resources.
You can also use `depends_on` to manually specify dependencies.
5. What is the purpose of `depends_on`?
`depends_on` is used to explicitly declare a dependency between resources, ensuring
one resource is created or destroyed before another.
6. How do you reference one resource in another?
You can reference attributes from another resource using interpolation:
e.g., aws_instance.example.id
7. What happens if you change a resource configuration?
Terraform will detect changes during `terraform plan` and apply them with
`terraform apply`, modifying the infrastructure to match the updated configuration.
8. What is a meta-argument in a resource?
Meta-arguments are special arguments used for controlling behavior. Examples
include:
- count
- for_each
- depends_on
- provider
- lifecycle
9. What is the `lifecycle` block used for?
The `lifecycle` block controls the lifecycle behavior of a resource. For example:
- prevent_destroy = true
- create_before_destroy = true
- ignore_changes = [attribute]
10. What is the `count` meta-argument?
`count` allows creating multiple instances of a resource:
resource "aws_instance" "example" {
count = 2
ami = "ami-12345678"
instance_type = "t2.micro"
}
11. What is `for_each` and how is it different from `count`?
`for_each` is used for creating resources from a map or set of strings. Unlike
`count`, it gives a named index for each item, allowing more flexibility and
readability.
12. Can you create multiple types of resources in one file?
Yes, you can define multiple resource blocks in one file or across several `.tf`
files in the same directory.
13. What is resource tainting?
Tainting a resource with `terraform taint` marks it for recreation during the next
apply.
14. How do you delete a specific resource without affecting others?
You can use `terraform destroy -target=resource_type.name` to destroy just one
resource.
15. How do you import an existing AWS resource into Terraform?
Use `terraform import` to bring an existing resource under Terraform's management:
terraform import aws_instance.example i-1234567890abcdef0