liveBook · Manning

Impure function

As explained in Terraform in Depth: Infrastructure as Code with Terraform and OpenTofu

An impure function is a Terraform function whose result is not guaranteed to be known during planning or to remain fixed across evaluations.

An impure function can return a different value each time it runs. Common examples include random functions and functions that return the current time. Terraform makes this distinction operationally important because configuration values must remain stable across planning and application. section 4.3.3

Using an impure function in a resource configuration can make Terraform believe the resource needs updating after every apply. A configuration containing uuid() or timestamp() can therefore produce continual changes and apparent state drift. section 4.3.3

Account for impure functions in two important situations:

  • Avoid using timestamp or uuid where a value must be stable between runs. section 4.3.3
  • Treat impure functions as unsuitable for for_each or count values when Terraform cannot know them during the early planning phase. section 4.8.4
  • Use random-provider resources when generated data should persist, changing only when keepers change. section 6.8.1

A UUID that forces continual changes

In this resource, uuid() generates a new tag value during evaluation. Terraform consequently sees the instance configuration as changing after each apply. section 4.3.3

Listing 4.16 Example of UUID function forcing constant changes
resource "aws_instance" "example" {
  tags = {
    id = uuid()                                               #1
  }
}

Inspect the resource configuration that demonstrates how uuid() causes repeated changes. section 4.3.3

How Terraform in Depth: Infrastructure as Code with Terraform and OpenTofu covers it

How deep it goes
Defines purity, explains deployment consequences, and stops short of implementing function internals.
Examples
Uses uuid and timestamp expressions, resource tags, random resources, and early-planning collection arguments.
What it assumes
Assumes familiarity with Terraform resources, planning, applying, and collection meta-arguments.
What you can do after
Diagnose repeated Terraform changes and replace unstable expressions with persisted random-provider resources when appropriate.
How it connects
Connects impure functions to pure functions, state drift, for_each, count, random providers, and time providers.

Also explained in

Compare how 2 books explain impure function →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Terraform in Depth: Infrastructure as Code with Terraform and OpenTofu. The section links point to the parts of the book it draws on.