Lesson 1 of 3 Resources, Data Sources and References

Resource Blocks and Meta-Arguments

Resource blocks are the most important element of the Terraform language. This lesson covers their syntax, the meta-arguments Terraform adds to every resource, and creating several instances with count and for_each.

Learning outcomes

After completing this lesson, you will be able to:

  • Describe the parts of a resource block and the meta-arguments.
  • Distinguish count from for_each and choose between them.

Anatomy of a resource block

A resource block declares one infrastructure object, or a group of similar objects, that Terraform manages through its whole lifecycle. The block has two labels: the resource type, defined by a provider, and a local name chosen by the author.

resource "aws_s3_bucket" "logs" {
  bucket        = "acme-logs-2026"
  force_destroy = false

  tags = {
    Environment = var.environment
  }
}

Together the labels form the address aws_s3_bucket.logs, which must be unique within the module. The body contains arguments defined by the provider's schema: some required, some optional, and some nested blocks. The provider also exports attributes, some of which are read-only and computed during creation, such as arn and id. The provider documentation for each resource type lists its arguments, attributes, which changes force replacement and how to import it.

Meta-arguments

Meta-arguments are defined by Terraform itself and work on every resource type. The following table lists the five meta-arguments, followed by the provisioner and connection blocks, which are also handled by Terraform rather than the provider but are not counted as meta-arguments.

Meta-argumentPurpose
countCreate a number of similar instances, addressed by index
for_eachCreate one instance per element of a map or set, addressed by key
depends_onDeclare dependencies that references do not express
providerSelect a non-default provider configuration, such as aws.dr
lifecycleChange create, update and destroy behaviour, and hold custom conditions
provisioner and connectionRun scripts on a created object; a last resort

Provisioners, such as local-exec and remote-exec, run commands after creation or before destruction. HashiCorp describes them as a last resort, because Terraform cannot model what they do in a plan. Prefer provider features such as user data, configuration management tools or machine images built in advance.

Match the pairs

Meta-arguments

Exam skills 4.1.1 · 4.1.3

Match each requirement with the meta-argument that meets it.

Log in to try this activity Interactive activities are free with an account.

count

count takes a whole number and creates that many instances. Inside the block, count.index is the instance's position, starting at zero. Instances are addressed aws_instance.web[0], aws_instance.web[1] and so on, and the whole resource is a list.

resource "aws_instance" "web" {
  count         = 3
  ami           = data.aws_ami.ubuntu.id
  instance_type = "t3.micro"
  tags          = { Name = "web-${count.index}" }
}

resource "aws_eip" "nat" {
  count  = var.create_eip ? 1 : 0
  domain = "vpc"
}

The second resource shows a common pattern: a conditional expression gives count a value of 1 or 0, so the resource exists only when a variable is true. The weakness of count is that instances are identified by position. If count is driven by a list such as ["a", "b", "c"] and "b" is removed, the instance for "c" moves from index 2 to 1, and Terraform plans to change or replace it.

for_each

for_each takes a map or a set of strings and creates one instance per element. Inside the block, each.key is the map key or set element and each.value is the map value (or the element again for a set). Instances are addressed by key, such as aws_iam_user.team["alice"], and the whole resource is a map.

variable "buckets" {
  type = map(string)
  default = {
    logs    = "STANDARD_IA"
    reports = "STANDARD"
  }
}

resource "aws_s3_bucket" "this" {
  for_each = var.buckets
  bucket   = "acme-${each.key}"
}

resource "aws_iam_user" "team" {
  for_each = toset(["alice", "bob"])
  name     = each.key
}

Removing a key affects only that instance, so for_each is the better choice when instances differ or have meaningful names. A list must be converted with toset() first, because lists can contain duplicates and have no stable keys. The keys of a for_each collection must be known during planning, so they cannot come from attributes that are computed during apply. A block cannot use both count and for_each.

count
InputA whole number
Instance addressresource[0]
Removing one elementCan shift and replace later instances
Choose when Identical instances, or 0/1 conditional creation
for_each
InputA map or a set of strings
Instance addressresource["key"]
Removing one elementAffects only that instance
Choose when Distinct, named instances

The following diagram compares removing an element with count and with for_each.

Removing eu-west-1b from three subnets. With count, instances are identified by index, so eu-west-1c moves from index 2 to index 1: Terraform sees index 1 change zone, which forces replacement, and index 2 disappear. With for_each over toset(var.azs), instances are keyed by zone name and only the eu-west-1b subnet is destroyed. moved blocks switch without recreating subnets.
The zones are illustrative.
Scenario questions

count or for_each?

Exam skills 4.1.3

Choose between count and for_each and predict their behaviour.

Log in to try this activity Interactive activities are free with an account.
Worked example

Count or for_each

A configuration creates three subnets with count = length(var.azs), where var.azs = ["eu-west-1a", "eu-west-1b", "eu-west-1c"]. The team wants to remove eu-west-1b. The plan shows the 1c subnet being replaced, which would disrupt its instances.

The decisive fact is that count identifies instances by index.

Removing the middle element moves eu-west-1c from index 2 to index 1, so Terraform sees index 1 changing zone, which forces replacement, and index 2 disappearing. With for_each = toset(var.azs), the instances would be addressed by zone name, and removing eu-west-1b would destroy only that subnet. To switch without recreating the existing subnets, the team adds moved blocks from aws_subnet.app[0] to aws_subnet.app["eu-west-1a"] and so on.

Check yourself

Which types of value does for_each accept?

Show answer

A map, or a set of strings. A list must be converted with toset() first.

Exam Tips

Remember for the exam

  • Resource address = type + local name; unique per module.
  • Meta-arguments: count, for_each, depends_on, provider, lifecycle.
  • for_each needs a map or set of strings; use toset() on lists.
  • Removing an item from a count list can replace later instances.