004 · Domain 4: Terraform configuration · 13% of the exam
Task 4.2: Refer to resource attributes and create cross-resource references
Reference syntax for resources, data sources, modules, variables and locals; instances made by count and for_each; splat expressions; and the implicit dependencies that references create.
Study it
References, count and for_each instances, splats
Lesson coming
Sample questions
Try each one before opening the answer. Every option is explained, with the HashiCorp documentation page that proves it.
Question 1 · choose 2
A configuration contains:resource "aws_instance" "web" {
count = 3
# ...
}Which two expressions, written in an output block of the same module, are valid references to these instances' IDs? (Choose TWO.)
Aaws_instance.web[0].id
Baws_instance.web.id
Caws_instance.web[count.index].id
Dvalues(aws_instance.web)[0].id
Eaws_instance.web[*].id
Show the answer and why
Aaws_instance.web[0].id
Correct
With count, each instance is addressed by its zero-based index.
Baws_instance.web.id
Incorrect
That form fits a resource without count or for_each. A resource with count has no single instance; an index or a splat is required.
Caws_instance.web[count.index].id
Incorrect
count.index exists only inside a block that sets count itself, such as another counted resource; an output block has no count, so the reference is an error there.
Dvalues(aws_instance.web)[0].id
Incorrect
values() takes a map or object, which is what a for_each resource produces. A count resource is a list of instances, so the call fails.
Eaws_instance.web[*].id
Correct
The splat expression returns a list of the id attribute of every instance.
count makes a list of instances: index one with [n], or take them all with [*]. count.index and map functions belong to other contexts.
A resource uses for_each = var.users, where var.users is a map from user name to team. Which expressions give the current user's name and team inside the block?
Aeach.key and each.value
Bcount.index and count.value
Cvar.users.key and var.users.value
Dself.key and self.value
Show the answer and why
Aeach.key and each.value
Correct
In blocks with for_each, each.key is the map key and each.value is the corresponding value.
Bcount.index and count.value
Incorrect
count objects exist only with count, and count.value does not exist.
Cvar.users.key and var.users.value
Incorrect
These are not iteration references.
Dself.key and self.value
Incorrect
self refers to the resource, not to the iteration.
for_each gives each.key and each.value; count gives count.index.