Skip to content

Terraform Resources, Data Sources, Variables and Outputs

Step 7 of 18

Terraform Resources, Data Sources, Variables and Outputs

Introduction

This guide to Terraform resources, data sources, variables and outputs belongs to the Terraform configuration area of the Terraform Associate (004) exam and covers objectives 4a to 4d. The official area contains eight objectives; their count does not establish an official question distribution. HashiCorp does not publish domain weights. The exam lasts one hour, tests Terraform 1.12, and mixes true/false, multiple-choice and multiple-answer questions.

A Terraform configuration is a set of blocks. The four block types you meet most often are resource, data, variable and output. Together they answer four questions: what do I build, what do I read from elsewhere, what can the user choose, and what do I report back. Almost every configuration on the exam is a combination of these blocks, so you must be able to read them fluently.

After this lesson you will be able to write resource and data blocks, reference attributes between resources, declare and set input variables in all the supported ways, use outputs, and choose among the complex types: list, set, map, object and tuple.

Learning objectives

  • Write resource and data blocks and explain the difference between managed resources and data sources.
  • Reference attributes of other resources, data sources, variables and locals.
  • Declare input variables with type, default, description and validation, and know the order in which values are assigned.
  • Declare outputs, and know how to read them with the CLI.
  • Choose between list, set, map, object and tuple, and use for_each and count.

The snippets below illustrate separate patterns. They assume installed providers, suitable credentials and a region; references to other resources or variables require the corresponding declarations. Do not concatenate alternatives that declare the same resource address into one module.

4a. Resource and data blocks

Resource blocks

A resource block declares an infrastructure object that Terraform manages: it creates, updates and deletes it.

HCL
resource "aws_s3_bucket" "logs" {
  bucket = "acme-prod-logs-2026"

  tags = {
    Team = "platform"
  }
}

The block has two labels: the resource type (aws_s3_bucket), which starts with the provider's local name, and the local name (logs), which is unique within the module for that type. The address of this resource is aws_s3_bucket.logs. Inside the block, arguments are what you set (bucket, tags), while attributes are what you can read afterwards, including values computed by the platform (arn, id).

Important points:

  • Terraform stores each resource under its address in state. Renaming the local name is seen as a delete and create unless you tell Terraform about the move with a moved block (covered in the state lesson).
  • Some arguments are required, some optional, some computed only (you cannot set them).
  • Meta-arguments available on any resource: depends_on, count, for_each, provider, and lifecycle.

Data blocks

A data block reads information that Terraform does not manage, from the provider's API or from another source. A data source never creates or modifies anything.

HCL
data "aws_ami" "ubuntu" {
  most_recent = true
  owners      = ["099720109477"]

  filter {
    name   = "name"
    values = ["ubuntu/images/hvm-ssd-gp3/ubuntu-noble-24.04-amd64-server-*"]
  }
}

resource "aws_instance" "web" {
  ami           = data.aws_ami.ubuntu.id
  instance_type = "t3.micro"
}

The AMI filter follows Canonical’s Ubuntu 24.04 gp3 image naming. Confirm availability in the selected AWS region. most_recent = true can select a newer image in a later plan; pin an approved AMI when repeatability requires it.

The address of a data source starts with data.: data.aws_ami.ubuntu. Data sources are read during plan when their arguments are known; if an argument depends on a resource not yet created, the read is deferred to apply and its result is (known after apply).

Example. A network team creates VPCs in one configuration. The application team, using a separate configuration, needs the VPC identifier. They use data "aws_vpc" "main" with a tag filter. They do not manage the VPC, so there is no risk of deleting it by mistake.

Aspect resource data
Purpose Create and manage an object Read an existing object
Address type.name data.type.name
Appears in state Yes Yes (as a cached read)
Destroyed by terraform destroy Yes No external effect
Typical use Instance, bucket, DNS record Latest AMI, existing VPC, current account ID

4b. Resource attributes and cross-resource references

Terraform builds its dependency graph from references. When one block uses RESOURCE_TYPE.NAME.ATTRIBUTE, Terraform knows the first must exist before the second.

HCL
resource "aws_vpc" "main" {
  cidr_block = "10.0.0.0/16"
}

resource "aws_subnet" "app" {
  vpc_id     = aws_vpc.main.id          # implicit dependency
  cidr_block = "10.0.1.0/24"
}

Here Terraform creates the VPC first, because the subnet needs aws_vpc.main.id, which is unknown until the VPC exists. This is an implicit dependency; the next lesson covers explicit ones with depends_on.

Reference forms to know:

Reference Meaning
aws_vpc.main.id Attribute of a managed resource
data.aws_ami.ubuntu.id Attribute of a data source
var.region Input variable
local.name_prefix Local value
module.network.vpc_id Output of a child module
aws_instance.web[0] or aws_instance.web["a"] One instance of a resource that uses count or for_each
path.module, path.root, terraform.workspace Built-in values

Local values give a name to an expression so you can reuse it:

HCL
locals {
  name_prefix = "${var.project}-${var.environment}"
  common_tags = {
    Project     = var.project
    Environment = var.environment
  }
}

count and for_each

Both create several instances from one block.

HCL
resource "aws_subnet" "app" {
  for_each   = toset(["a", "b", "c"])
  vpc_id     = aws_vpc.main.id
  cidr_block = cidrsubnet(aws_vpc.main.cidr_block, 8, index(["a", "b", "c"], each.key))
}
Feature count for_each
Input A whole number A map or a set of strings
Instance key Integer index ([0]) The map key or set value (["a"])
Access to element count.index each.key, each.value
Effect of removing an item in the middle Later items shift and may be replaced Stable keys preserve addresses; other instances can still change if their configured arguments change
Recommended for Simple toggles (count = var.enabled ? 1 : 0) Collections of distinct objects

You cannot use count and for_each on the same block. The keys of for_each must be known at plan time, they cannot depend on attributes only known after apply. Keys and set members also cannot be sensitive values, because they appear in instance addresses. Stable keys do not by themselves stabilise attributes computed from changing list positions.

Worked example: choosing count or for_each

Scenario. A variable var.buckets = ["raw", "clean", "curated"] drives the creation of three S3 buckets. Later the team removes "clean". The bucket for "curated" must not be destroyed or recreated.

Step by step.

  1. With count = length(var.buckets) the buckets are addressed [0], [1], [2]. Removing "clean" makes the list ["raw", "curated"], so "curated" moves from [2] to [1]. Terraform sees index [1] change its name, and index [2] disappear, so it plans to modify or replace buckets that should remain.
  2. With for_each = toset(var.buckets) the buckets are addressed ["raw"], ["clean"], ["curated"]. Removing "clean" only destroys aws_s3_bucket.this["clean"].
  3. The second design isolates the change.

Solution. Use for_each = toset(var.buckets).

Why count is worse here. Index-based addresses depend on the order of the list, so any removal in the middle shifts the following instances. count remains the right tool for an on/off switch (0 or 1).

For the commands that evaluate and apply these declarations, revisit the Terraform init, plan and apply workflow.

4c. Input variables and outputs

Input variables

A variable block declares a parameter of the module (the root module's variables are what the user supplies).

HCL
variable "environment" {
  type        = string
  description = "Deployment environment"
  default     = "dev"

  validation {
    condition     = contains(["dev", "staging", "prod"], var.environment)
    error_message = "environment must be dev, staging or prod."
  }
}

variable "db_password" {
  type      = string
  sensitive = true
}

Arguments: type, description, default, sensitive, nullable, ephemeral and validation. A variable without a default is required: Terraform asks for it interactively or fails in non-interactive runs. You refer to a variable as var.environment, never as a plain name.

Ways to set a value, and precedence

For a local Terraform CLI run, from lowest to highest precedence:

  1. The default in the variable block.
  2. Environment variables named TF_VAR_name.
  3. terraform.tfvars, then terraform.tfvars.json.
  4. *.auto.tfvars and *.auto.tfvars.json, in alphabetical order.
  5. -var and -var-file options on the command line, in the order they appear (later wins).

If a variable has no value after all this, Terraform prompts for it. HCP Terraform has additional workspace and variable-set precedence rules, including priority sets that can override run-level values. Do not treat every workspace variable as equivalent to a local -var option; consult the HCP rules for the chosen workflow.

Bash
export TF_VAR_environment=staging
terraform plan -var-file=prod.tfvars -var='environment=prod'

In this example -var wins: the effective value is prod.

Worked example: which value wins?

Scenario. A configuration declares this variable:

HCL
variable "instance_count" {
  type    = number
  default = 1
}

The directory contains terraform.tfvars with instance_count = 2 and prod.auto.tfvars with instance_count = 3. The shell has TF_VAR_instance_count=4 exported. The engineer runs terraform plan -var-file=override.tfvars, and override.tfvars contains instance_count = 5. A resource uses count = var.instance_count. How many instances does the plan request?

Step by step.

  1. List every source: default 1, environment 4, terraform.tfvars 2, prod.auto.tfvars 3, -var-file 5.
  2. Apply the order from lowest to highest: default, then environment variable, then terraform.tfvars, then *.auto.tfvars, then command-line options.
  3. The command-line -var-file is the last and highest, so its value 5 wins.

Solution. Five instances.

Why the others are wrong. 4 would be correct if no higher-priority source supplied this variable; a tfvars file that sets only other variables would not override it. 3 would win if the command had no -var-file. 1 is only the fallback when nothing else sets the variable. If the engineer had also passed -var='instance_count=6' after the -var-file, 6 would win, because later command-line options override earlier ones.

Type errors and conversion

Terraform reports a clear error when a value cannot be converted to the declared type, for example passing "many" to a number variable, or a list where a map is expected. A practical consequence: always give variables explicit type constraints, so mistakes surface at plan time with a message naming the variable, instead of later in a provider error that is harder to trace. When a variable is list(string) and a user supplies ["a", 1], Terraform converts the number to the string "1" because the conversion is safe; for an object type, extra attributes in the supplied value are discarded and missing non-optional attributes produce an error.

Outputs

An output block exposes a value after apply. It is used to print results for humans, to pass values from a child module to its parent, and to let other configurations read the value through terraform_remote_state or HCP Terraform.

HCL
output "bucket_arn" {
  description = "ARN of the log bucket"
  value       = aws_s3_bucket.logs.arn
}

output "db_password" {
  description = "Illustrative sensitive output; prefer not to expose passwords."
  value       = var.db_password
  sensitive   = true
}

Reading outputs: terraform output lists them, terraform output bucket_arn prints one, terraform output -raw bucket_arn removes quotes (good for scripts), and terraform output -json is machine-readable. An output marked sensitive = true is hidden in the plan and apply display but is still stored in plain text in the state file, and terraform output -json, terraform output -raw NAME or terraform output NAME can reveal it. Avoid writing those results to shared logs. Outputs from a child module are not displayed at the root unless the root re-exports them with its own output.

4d. Complex types

Terraform has primitive types (string, number, bool) and two groups of complex types.

Collections hold values of one type:

Type Description Example
list(type) Ordered, indexed from 0, duplicates allowed ["a", "b", "a"]
set(type) Unordered, unique values toset(["a", "b"])
map(type) Key to value, all values of one type { env = "prod", team = "net" }

Structural types hold values of different types:

Type Description Example
object({...}) Named attributes, each with its own type object({ name = string, size = number })
tuple([...]) Ordered elements with a type per position tuple([string, number, bool])
HCL
variable "servers" {
  type = map(object({
    instance_type = string
    disk_gb       = number
    public        = optional(bool, false)
  }))
  default = {
    web = { instance_type = "t3.small", disk_gb = 30, public = true }
    db  = { instance_type = "t3.large", disk_gb = 200 }
  }
}

resource "aws_instance" "srv" {
  for_each      = var.servers
  ami           = data.aws_ami.ubuntu.id
  instance_type = each.value.instance_type
  root_block_device {
    volume_size = each.value.disk_gb
  }
  tags = { Name = each.key, Public = tostring(each.value.public) }
}

The optional(type, default) modifier supplies a fallback for an omitted object attribute. Both instance types above use x86_64 images, matching the amd64 AMI lookup. Here public is descriptive metadata used in a tag; it does not assign a public IP or configure network access.

any is a type-inference placeholder, not a separate type. For list(any), Terraform must still find one common element type; it can convert ["a", 1] to strings but cannot necessarily unify unrelated structured values. Prefer explicit constraints when inspecting a value’s contents. Terraform converts types automatically where it is safe (the string "5" to the number 5).

Access patterns: var.list[0], var.map["key"], var.map.key, var.object.attribute. A splat expression such as aws_instance.web[*].id works for a count-based list of instances. A for_each resource is a map: use [for s in aws_instance.srv : s.id] or a keyed for expression instead.

Case comparison: which type?

Need Best type
Ordered list of availability zones list(string)
Unique set of allowed CIDR blocks set(string)
Tags map(string)
One server definition with name, size and flag object({...})
A fixed pair such as [name, port] tuple([string, number])

Common pitfalls and exam tips

  • Pitfall: treating a data source as something Terraform creates. It only reads.
  • Pitfall: using count for a list of named things and being surprised by replacements when an item in the middle is removed.
  • Pitfall: thinking sensitive = true encrypts anything. It only hides values in CLI output; state still contains them.
  • Pitfall: forgetting that a variable without a default is required.
  • Pitfall: passing an unknown value (for example the id of a resource not yet created) to for_each keys.
  • Exam tip: the order of precedence puts -var and -var-file above environment variables, which sit above the default.
  • Exam tip: terraform.tfvars and files ending .auto.tfvars load automatically; any other .tfvars file needs -var-file.
  • Exam tip: terraform output -raw for a string without quotes; -json for scripts.
  • Exam tip: an object has named attributes of different types; a map has keys with values of one type.

For custom conditions and secrets that should not persist, continue with Terraform validation and sensitive data.

Mini case study

Situation. A media company wants one module-less configuration that prepares the S3 buckets for a future CloudFront-backed website in each environment. The requirements: the environment name must be one of dev, staging, prod; the bucket list is given as a map from name to a settings object; the bucket ARNs must be printed after apply; the site must use the latest approved AMI for a build host looked up by tag.

Proposed design.

HCL
variable "environment" {
  type = string
  validation {
    condition     = contains(["dev", "staging", "prod"], var.environment)
    error_message = "Unknown environment."
  }
}

variable "sites" {
  type = map(object({ tags = map(string) }))
}

resource "aws_s3_bucket" "site" {
  for_each = var.sites
  bucket   = "media-${var.environment}-${each.key}"
  tags     = each.value.tags
}

resource "aws_s3_bucket_public_access_block" "site" {
  for_each = var.sites
  bucket   = aws_s3_bucket.site[each.key].id

  block_public_acls       = true
  block_public_policy     = true
  ignore_public_acls      = true
  restrict_public_buckets = true
}

data "aws_ami" "builder" {
  most_recent = true
  owners      = ["self"]
  filter {
    name   = "tag:Approved"
    values = ["true"]
  }
}

output "site_arns" {
  value = { for k, b in aws_s3_bucket.site : k => b.arn }
}

This partial design prepares tagged buckets, explicit public-access blocks and an AMI lookup. It does not create a CloudFront distribution, grant origin access or launch a build host; those need additional configuration. Choose globally unique bucket names. Keep the buckets private and grant CloudFront origin access separately.

Questions. (1) Why for_each rather than count? (2) Which block reads the AMI, and does Terraform manage that AMI? (3) How would you pass environment=prod without editing code?

Solution. (1) The sites are named, and removing one must not shift the others. (2) The data block reads it; Terraform does not create or delete it. (3) Use -var 'environment=prod', a prod.tfvars file with -var-file, or TF_VAR_environment=prod. Because aws_s3_bucket_public_access_block.site references aws_s3_bucket.site[each.key].id, Terraform creates each bucket before configuring its public-access block without an extra depends_on.

Key terms

  • Resource: a managed infrastructure object.
  • Data source: a read-only lookup.
  • Argument / attribute: input to a block / value you can read.
  • Implicit dependency: created by a reference.
  • Input variable: parameter of a module.
  • Output: value exposed after apply.
  • Collection / structural type: list, set, map / object, tuple.

Summary checklist

  • I can write a resource block and name its address.
  • I can explain why data sources do not change infrastructure.
  • I can reference attributes and understand implicit dependencies.
  • I know when to use count and for_each.
  • I know the precedence of variable values.
  • I can read outputs with the CLI.
  • I can tell list, set, map, object and tuple apart.

Official sources