Modules and Reading, Generating, and Modifying Configuration
This chapter covers how to structure reusable configuration with modules, pass data in and out with variables and outputs, read existing infrastructure with data sources, and create multiple resources with meta-arguments. It also explains how Terraform orders resource creation.
Modules, variables, and outputs
A module is a container for related resources defined in a set of .tf files; every configuration has a root module and can call child modules for reuse. Input variables define what a module accepts, and output values expose results to the caller. Together they form a module's public interface.
Data sources and references
A data source reads information about existing infrastructure Terraform does not manage, such as an existing image or network, so it can be referenced elsewhere. Referencing one resource's attribute in another creates an implicit dependency, which Terraform uses to order operations.
count, for_each, and dependencies
count creates multiple instances keyed by numeric index, while for_each creates one instance per element of a map or set with stable keys, reducing churn when the collection changes. Terraform builds a dependency graph from references and creates dependencies first; depends_on is reserved for dependencies Terraform cannot infer automatically.