Complete the code to create multiple instances using count.
resource "aws_instance" "example" { ami = "ami-12345678" instance_type = "t2.micro" count = [1] }
The count argument expects a number to specify how many instances to create. Using 3 creates three instances.
Complete the code to reference the ID of the second instance created using count.
output "second_instance_id" { value = aws_instance.example[[1]].id }
Terraform uses zero-based indexing. The second instance is at index 1.
Fix the error in the count expression to create instances based on a variable.
variable "instance_count" { type = number default = 2 } resource "aws_instance" "example" { ami = "ami-12345678" instance_type = "t2.micro" count = [1] }
var. prefix.To use a variable in Terraform, prefix it with var.. So var.instance_count correctly references the variable.
Fill both blanks to create instances with different names using count and the index.
resource "aws_instance" "example" { ami = "ami-12345678" instance_type = "t2.micro" count = 3 tags = { Name = "example-$[1]" Env = "$[2]" } }
count_index instead of count.index.var. prefix for variables.count.index gives the current instance number starting at 0, used to create unique names. var.environment references a variable for environment tagging.
Fill all three blanks to create a map of instance IDs keyed by their index using count.
output "instance_ids_map" { value = { for i in range([1]) : i => aws_instance.example[[2]].id if i [3] 0 } }
count.index instead of i inside the loop.< instead of > in the condition.range(var.instance_count) loops over the number of instances. i is the index used to access each instance. The condition i > 0 filters out the first instance.