Terraform Knowledge
Kip Landergren
(Updated: )
My Terraform knowledge base that evolves as I learn more.
Contents#
Motivation#
Infrastructure—the compute, I/O, and networking components used by an organization—exists with some state S that is itself comprised of the states of the individual infrastructure components:
Importantly, S is:
- remote
- mutable through multiple vectors (APIs, CLIs, web interfaces, and remote access)
- known definitively only through interrogation
Consider the following operations done at the same time:
What should the correct new state be? S′? S″? Something else?
Manual management—making adhoc changes based on needs—has some operational problems:
- concurrent operations are fraught:
- breakage
- unintentional reversions
- and more
- the actions have state themselves and necessitate adhoc management of:
- success
- failure modes
- unknown states
- review of state requires queries (and knowing what and where to query!)
- determining what exactly changed
- ensuring the intended modification stays applied
- difficult to audit:
- what actions were actually performed?
- where?
- on what?
- by whom?
- difficult to enforce consistency (e.g. provisioning a VM with the correct properties)
- difficult to scale changes (e.g. adjusting the VM size of all web frontends)
As well as institutional and development problems:
- hard to know why something exists, or exists in a certain way
- work is duplicated across solutions
- reusability is more difficult than with a consistent interface
- bespoke solutions beget bespoke failures which require bespoke debugging
So how can we address these operational and development problems while being bound by the realities of remotely managing state?
Three realizations:
- the “how” of managing infrastructure lifecycles is actually pretty standard: it can be solved once and reused (with sufficient escape hatches for customizations)
- we need a local representation of remote state that:
- can be easily shared, reviewed, and audited
- offers rich context for why something exists, or will change
- we need a single interface through which to manage state changes that:
- locks operations
- enforces consistency
Terraform offers a solution via:
- Hashicorp Configuration Language (HCL) for describing resources—infrastructure components—that:
- is declarative rather than imperative
- may be stored as human-readable text in files which can then be version controlled (and shared, reviewed, audited...)
- allows for the definition and use of an abstraction over infrastructure provider APIs—a
provider—that contains hardened logic for lifecycle management - permits reusable modules that contain:
- standardized descriptions of infrastructure
- easily accessible customization
terraform, a CLI tool, that:- acts as the interface to provider infrastructure
- can evaluate the local configuration into a representation of the desired infrastructure state
- can compare that desired state to the actual remote state
- can compute the steps necessary to transition the remote state to the desired one (using
providerlogic) - can apply those steps in a deterministic and consistent manner
- offers interception points to hook in automated checks (compliance, auditing, best practices)
Overview#
Infrastructure lifecycle can be thought of as:
- “Day 0”: “landing zone” establishment (the core accounts, permissions, and metadata established with the infrastructure provider) and foundation building
- “Day 1”: initial deployment
- “Day 2+”: modification:
- scaling
- patching
- “right-sizing”
- changing resource types
- compliance and audit
- general care and feeding
- cost analysis (e.g. per team) and optimization
- “Day N”: decommissioning
Terraform#
Workflow#
- write: express your desired infrastructure state via HCL
- plan: use Terraform to compare the desired state against the real one and create an execution plan of operations to perform
- apply: tell Terraform to perform the execution plan
Terraform compares the evaluated form of the configuration, not the configuration file itself. Edits to files do not necessarily require a change in state.
State Management#
Defaults to local .tfstate file but can be configured for remote storage enabling collaboration and extra features (like locking).
Hashicorp Configuration Language (HCL)#
HCL’s sole purpose is to describe resources. All other language features exist to make that declaration more flexible and convenient.
The ordering of blocks within a file is not significant: only the implicit and explicit dependencies between them.
<BLOCK TYPE> "<BLOCK LABEL>" "<BLOCK LABEL>" {
# block body
<IDENTIFIER> = <EXPRESSION> # argument
}
Modules#
A collection of resources that Terraform manages together.
Providers#
Libraries abstracting an infrastructure platform that provide:
- resource types
- data sources
- local utilities
Terraform can then use to implement functionality.
Meta Arguments#
Special block arguments that control how Terraform works with a resource.
Variables#
Variables allow for modules to be reused in different contexts with different runtime data without modifying configuration files.
Can be passed at invocation via:
-varflag- .tfvars file
TF_VAR_-prefixed environment variables
And accessed via:
var.<NAME>
Locals#
Function-scoped variables.
Outputs#
Exposure of information about infrastructure.
Core Idea#
Operationalize and automate infrastructure lifecycle management.
Key Concepts#
Infrastructure as Code (IaC)#
- reusable: repeated patterns can be applied to multiple situations
- modular: can package related functionality together
- reproducible: can apply the same configuration in a different environment
- consistent: each step is deterministic
Immutable Infrastructure#
- removes the skew between what is initially configured and what is running now: they are the same
Terminology#
- argument#(term argument)
- 1.
An assignment of a value to a name within a block.
<BLOCK TYPE> "<BLOCK LABEL>" "<BLOCK LABEL>" { # Block body <IDENTIFIER> = <EXPRESSION> # Argument } - block#(term block)
- 1.
Containers for other content—typically representing the configuration of an object.
<BLOCK TYPE> "<BLOCK LABEL>" "<BLOCK LABEL>" { # Block body <IDENTIFIER> = <EXPRESSION> # Argument } - CFT (Cloud Foundation Toolkit)#(term Cloud Foundation Toolkit)(term CFT)
- 1.
- child module#(term child module)
- 1.
Modules configured with
moduleblocks. - create before destroy#(term create before destroy)
- 1.
+/-. spreads through the dependency tree to all resources directly or indirectly depended on. - data source#(term data source)
- 1.
- destroy#(term destroy)
- 1.
- expression#(term expression)
- 1.
A representation of a value.
<BLOCK TYPE> "<BLOCK LABEL>" "<BLOCK LABEL>" { # Block body <IDENTIFIER> = <EXPRESSION> # Argument } - Fabric FAST#(term Fabric FAST)
- 1.
Part of
cloud-foundation-fabric, which is:- a collection of Terraform modules that can be extended and reused
- intended to be forked and maintained
Fabric FAST pulls together lessons learned from Google’s professional services division who essentially consult with companies on how to properly set up IAM and orgs and infra within GCP.
- FAST is not an acronym: it just represents moving fast
- broken into stages:
- 0 where the org is set up
- 1 where VPC is set up
- 2 where networking and the rest
- each stage
- generates files that are consumed by the downstream stage
- has dedicated service accounts attached to perform the operations
- the idea here is that it limits scope of an operation to an SA with only permissions to perform that operation: no way for that SA to accidentally change more than intended
Stages are not one-off operations:
Think of them as the locks in a canal where you place your changes. The metaphor is a bit tortured but like if you need to make a change that affects everyone you need to make it at 0 (the highest) which flows down to all the other locks. And they themselves may need to process it so they also run plan and if non-empty they run apply.
- landing zone#(term landing zone)
- 1.
The core accounts, permissions, and metadata established with the infrastructure provider, often set on “Day 0”.
- meta-argument#(term meta-argument)
- 1.
Argument that affects how Terraform controls the resource.
- module#(term module)
- 1.
Reusable configuration component that define configuable collections of infrastructure.
- module composition#(term module composition)
- 1.
The process of keeping the module hierarchy as flat as possible.
Example:
module "network" { source = "./modules/aws-network" base_cidr_block = "10.0.0.0/8" } module "consul_cluster" { source = "./modules/aws-consul-cluster" vpc_id = module.network.vpc_id subnet_ids = module.network.subnet_ids } - output#(term output)
- 1.
Data designated for display or availability for query.
- registry#(term registry)
- 1.
- resource#(term resource)
- 1.
“Anything that you can create, modify or delete from an infrastructure perspective...”
- resource graph#(term resource graph)
- 1.
The dependency graph of resources Terraform uses to determine what needs to happen sequentially and what can be parallelized.
- root module#(term root module)
- 1.
The Terraform configuration files in the workspace’s root directory. (?? is not defined with
moduleblocks ??) - speculative plan#(term speculative plan)
- 1.
Running
terraform planto see what changes may happen (without necessarily intending to runterraform apply). - state file#(term state file)
- 1.
Terraform’s source of truth for the environment. Defaults to local .tfstate file but can be configured for remote storage and access.
- workspace#(term workspace)
- 1.
A Terraform configuration captured into a single state file. Multiple workspaces may be captured in a single working directory. Think of workspaces as 1:1 with states.
Env var:
TF_WORKSPACE.