To look up existing subnets and create an instance in one of them, define a data block and a resource block. Blocks are Terraform HCL’s primary construct: each represents a concrete piece of configuration or infrastructure rather than a step to execute. section 2.2 section 2.10
A block starts with a type and, where required, one or more labels. Braces enclose arguments and optional nested blocks. Arguments set values; a nested block supplies its own arguments. A block can also expose attributes that another block uses as argument values. section 2.2
Listing 2.8 HCL example with real resources
data "aws_subnets" "main" { #1
filter { #2
name = "vpc-id"
values = ["vpc-9ba9b5c6db85a9918"] #3
}
}
resource "aws_instance" "hello_world" { #4
ami = "ami-0eeb7197a00865f8a" #5
subnet_id = data.aws_subnets.main.ids[0] #6
}
The subnet lookup contains a filter block. The instance resource uses the lookup’s ids attribute for its subnet_id argument, linking the two blocks. section 2.2
Labels depend on the block type:
- terraform and locals blocks have no labels; a module has one terraform block. section 2.2.2
- variable, provider, output, and module blocks have one label. A provider label must correspond to a provider in required_providers. section 2.2.2
- data and resource blocks have a subtype followed by an identifier. Their type and labels distinguish blocks so their attributes can be referenced elsewhere. section 2.2.2
File position does not determine execution order: blocks may appear in any order, even across files. During planning, Terraform uses attribute references to identify dependencies and build a directed acyclic graph. If a subnet lookup uses a VPC lookup’s id, the VPC lookup must load first. The depends_on meta-parameter can also manage dependencies directly. section 2.2.5
