Resource blocks

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:

main.tf
1
2
3
4
resource "local_file" "greeting" {
  filename = "greeting.txt"
  content  = "hello world!"
}

A resource block consists of four parts:

  • The resource keyword.
  • The resource type (local_file). The prefix before the first underscore tells you which provider the resource belongs to (here the local provider).
  • 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 (filename and content). 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:

main.tf
1
2
3
4
5
6
7
8
resource "random_pet" "server" {
  length = 2
}

resource "local_file" "server_config" {
  filename = "server.conf"
  content  = "server_name = ${random_pet.server.id}"
}

The reference on line 7 also creates an implicit dependency: Terraform understands that it must create random_pet.server before local_file.server_config.

Resource blocks support meta-arguments such as 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 like this or resource1.
  • Do not repeat the resource type in the local name — prefer local_file.greeting over local_file.greeting_file.
  • Reference attributes of other resources instead of hardcoding values, so Terraform can track dependencies and keep values in sync.

  1. Each provider documents its resource types and their arguments in the Terraform registry↩︎