Resource blocks
A resource block declares an infrastructure object that Terraform should create and manage, e.g. a virtual machine, a DNS record, or a local file.
Resource blocks are the most important building block of a Terraform configuration. Declare a resource using a resource block:
| |
A resource block consists of four parts:
- The
resourcekeyword. - The resource type (
local_file). The prefix before the first underscore tells you which provider the resource belongs to (here thelocalprovider). - The local name (
greeting). You choose this name, and it is only used to refer to the resource inside of your Terraform configuration. - The arguments inside the curly braces (
filenameandcontent). Which arguments are available and required is defined by the resource type1.
Together, the resource type and local name form a unique resource address: local_file.greeting. When you run terraform apply, Terraform creates the real object and keeps track of it in its state:
flowchart LR
subgraph config["Terraform configuration"]
block["resource #quot;local_file#quot; #quot;greeting#quot;"]
end
subgraph state["Terraform state"]
tracked["local_file.greeting"]
end
real["Real object:<br/>greeting.txt"]
block -- "terraform apply" --> real
block -.tracked as.-> tracked
tracked -.represents.-> real
From this point on, Terraform manages the full lifecycle of the object: changing the arguments updates it, and removing the block deletes it.
Referencing resources
Use the resource address followed by an attribute name (<TYPE>.<NAME>.<attribute>) to use values from one resource in another:
| |
The reference on line 7 also creates an implicit dependency: Terraform understands that it must create random_pet.server before local_file.server_config.
count, for_each, and lifecycle that change how Terraform manages the resource. These are covered in their own topics.Best practices
- Give resources descriptive local names based on their purpose (e.g.
web_server), not generic names likethisorresource1. - Do not repeat the resource type in the local name — prefer
local_file.greetingoverlocal_file.greeting_file. - Reference attributes of other resources instead of hardcoding values, so Terraform can track dependencies and keep values in sync.
Each provider documents its resource types and their arguments in the Terraform registry. ↩︎