Mastering Terraform Slides
Mastering Terraform Slides
Terraform
Terraform
Benefits of Infrastructure as Code
Benefits of Infrastructure as Code
Improved Self
Better cost consistency & Fewer human documenting
management scalability errors infrastructure
Improved Improved
Improved deployment security
reliability process strategies
Terraform
Benefits of Infrastructure as Code
Improved Self
Better cost consistency & Fewer human documenting
management scalability errors infrastructure
Improved Improved
Improved deployment security
reliability process strategies
■ Resources, environments, and complex infrastructures can be easily created and destroyed.
■ Tagging strategies and requirements can be easily implemented across entire infrastructures.
■ It becomes much easier to obtain an overview of all resources created by a specific IaC project.
Terraform
Benefits of Infrastructure as Code
Improved Self
Better cost consistency & Fewer human documenting
management scalability errors infrastructure
Improved Improved
Improved deployment security
reliability process strategies
■ IaC tools provide multiple ways of deploying configurations: locally, as part of a CI/CD pipeline, triggered via API calls.
Terraform
Benefits of Infrastructure as Code
Improved Self
Better cost consistency & Fewer human documenting
management scalability errors infrastructure
Improved Improved
Improved deployment security
reliability process strategies
■ Infrastructure can be easily copied and deployed multiple times with the same structure.
■ Different environments can be created based on the same / similar configuration files.
Terraform
Benefits of Infrastructure as Code
Improved Self
Better cost consistency & Fewer human documenting
management scalability errors infrastructure
Improved Improved
Improved deployment security
reliability process strategies
■ Creating, updating and destroying resources becomes fully integrated with other CI/CD tasks.
■ Changes to infrastructure are version controlled, being easier to revert in case of incompatibility or error.
Terraform
Benefits of Infrastructure as Code
Improved Self
Better cost consistency & Fewer human documenting
management scalability errors infrastructure
Improved Improved
Improved deployment security
reliability process strategies
■ The planning stage shows all the changes that are expected to be carried out, and can be inspected by the engineers.
■ Connecting and integrating different resources becomes more intuitive due to developer-friendly identifiers.
■ Many IaC tools support validation and integrity checks with custom conditions.
■ Many IaC tools support protection rules against deletion of critical resources.
Terraform
Benefits of Infrastructure as Code
Improved Self
Better cost consistency & Fewer human documenting
management scalability errors infrastructure
Improved Improved
Improved deployment security
reliability process strategies
■ Validation and integrity checks can be used to ensure the infrastructure complies with security requirements.
■ Shared infrastructure modules are normally maintained by teams with a strong focus on securing these resources.
■ Security strategies (for example, IAM users, roles and their respective policies) can also be configured via IaC tools.
■ The infrastructure configuration files can be inspected by security software for vulnerabilities.
Terraform
Benefits of Infrastructure as Code
Improved Self
Better cost consistency & Fewer human documenting
management scalability errors infrastructure
Improved Improved
Improved deployment security
reliability process strategies
■ Run logs are normally stored for a period of time, allowing inspection in case of any errors or unwanted changes.
Terraform
Terraform
Why Terraform?
Why Terraform?
Advantages of Terraform over other Infrastructure-as-Code tools
Terraform can be used with Terraform can be used to We can create modules Terraform builds a dependency
multiple providers, both in the manage resources across grouping resources, and then graph of resources and
cloud and on-premises. multiple providers. combine and compose these supports parallel changes.
modules to build a bigger
solution.
We can execute only plan Terraform Provides several Terraform is very fast due to its
commands to inspect the ways to protect resources implementation of a state file,
potential changes before against accidental changes or saving the entire snapshot of
actually applying them. deletion, as well as ways of the current deployment.
validating the deployed
infrastructure.
Terraform
Terraform
Terraform's Architecture
Terraform's Architecture
How does Terraform manage resources in so many different places?
□ Read, create, update, and delete Amazon Web Services AWS API
resources through that provider’s API.
■ Anyone can write and publish a provider Google Cloud Google Cloud API
for a remote API, as long as it follows
Terraform
Terraform's specifications.
core Azure Azure API
■ We declare the necessary providers in the
Terraform project configuration, and
… …
Terraform installs those providers during
initialization.
Terraform
Terraform
Provisioning Infrastructure
Provisioning Infrastructure
How does Terraform provision and manage infrastructure?
1 3 1 3 1
State
Terraform
Terraform
Terraform Block
Terraform Block
Used for configuring the Terraform project (backend, providers, required versions)
Terraform
Terraform
Terraform State
Terraform State
Terraform State maps resources from the configuration to real-world objects
■ Before any planning operation, Terraform refreshes the state with the Binding to
information from the respective real-world objects. real-world
object
□ This is essential to avoid configuration drift. If a real-world object has been Resource Outputs
modified outside of Terraform and the respective configuration has not configuration
been updated, Terraform will revert the changes.
■ State can be either stored locally (default) or in several remote backends (S3,
Google Cloud Storage, Terraform Cloud, among others). Sensitive
Metadata
values
■ State locking: locks the state while executing write operations to prevent
concurrent modifications and state corruption.
Terraform
Terraform
Backends
Backends - Overview
Backends define where Terraform stores its state file
■ There are multiple types of backends, which can be place into three categories:
□ Terraform Cloud: the state file is stored in Terraform Cloud. Offers additional features.
□ Third-party remote backends: the state file is stored in a remote backend different from Terraform Cloud (for
example S3, Google Cloud Storage, Azure Resource Manager / Blob Storage, among others).
■ Different backends can offer different functionalities (for example, state locking is not available for all remote backends)
and require different arguments (we'll discuss more of that in the next slide).
■ The backend block cannot use any input variables, resource references, and data sources.
■ Remote backends require authentication credentials in order for Terraform to properly access the files.
■ When changes are made to the configured backend, we must rerun the terraform init command.
Terraform
Backends - Local and Remote
Terraform provides different options for backends, both local and remote
State
Terraform Terraform Terraform
Local backends: are stored in the same S3 backends: are stored in an S3 bucket Terraform Cloud backends: are stored
machine as the Terraform project. in AWS. in a Terraform Cloud project and
workspace.
Terraform
Terraform
Providers
Providers Overview
Providers are how Terraform interacts with remote APIs and platforms
Terraform
Terraform
Resources
Resource Blocks
Resources are used to configure real-world infrastructure objects
■ They are used to manage any infrastructure that we want to manage resource "aws_instance" "backend" {
with Terraform, and are the most important blocks within Terraform.
ami = "ami-12345"
■ Resource blocks represent things like virtual networks, compute instance_type = "t2.micro"
instances, DNS records, storage disks, among others.
}
■ The arguments depend on and vary based on the resource type.
■ The combination of resource type and resource name must be unique resource "aws_s3_bucket" "example" {
within a module. This is how Terraform links the resource to its bucket = "my-bucket-${random_id.suffix.id}"
respective real-world object.
tags = {
■ If no other provider is specified, Terraform will use the default Environment = "Dev"
provider to provision the infrastructure. We can use the provider }
meta-argument to explicitly pass a different provider.
}
■ Terraform offers a few local-only resources, such as generating
random strings or IDs, private keys, or self-issued TLS certificates. resource "random_id" "suffix" {
byte_length = 4
■ We can create multiple instances of resources by using Terraform }
loops (for_each, count).
Terraform
Terraform
Resource Dependencies
Resource Dependencies
Terraform supports both parallel and sequential creation of resources
Terraform apply
dependencies between resources.
■ If the operation on an upstream resource fails, Terraform will not continue the
operations on downstream resources.
■ We can also force Terraform to replace a parent resource in case a child resource
is modified by using the replace_triggered_by meta-argument.
Terraform
Terraform
Meta-Arguments
Meta-arguments
Meta-arguments allow us to configure Terraform's behavior in many ways
depends_on lifecycle
Terraform
Terraform
Data Sources
Data Sources
Query or retrieve data from APIs or other Terraform projects
Data source
Terraform
Terraform
Input Variables
Input Variables
Customize values based on variables to create reusable and composable code
Terraform
Terraform
Creating Multiple Resources
Creating Multiple Resources
Avoid code duplication by leveraging count and for_each meta-arguments
Terraform
Creating Multiple Resources
Avoid code duplication by leveraging count and for_each meta-arguments
Terraform
Terraform
Modules
Modules
Organize, encapsulate, and re-use Terraform components
■ Modules are used to combine different resources that are normally used together. They are just a collection of .tf files kept in the same
directory.
□ Root modules can then call other modules (child modules), defined either locally or remotely.
Group related parts of the Encapsulate sets of resources Modules make it much easier Provide configuration and
infrastructure to make the to prevent unintended to reuse entire sets of infrastructure best practices,
code easier to understand changes and mistakes that components, thus improving and publish modules both
and improve maintainability. can happen in complex code consistency, saving time, and publicly and privately for use
bases. preventing errors. by other teams.
Terraform
Terraform
Standard Module Structure
Standard Module Structure
Which files are recommended, and what they are used for
main.tf
Main entry point for module resources. More complex modules should split the resources into multiple
files with relevant names.
outputs.tf
File containing all outputs from the module. Used by Terraform Registry to generate documentation.
variables.tf
File containing all variables for the module. Used by Terraform Registry to generate documentation.
README.md
File containing documentation for the module. Used by Terraform Registry to generate documentation.
Terraform
Terraform
Building Modules
Building Modules
When to create modules and which best practices to follow?
■ Creating a module is as simple as creating a directory and a couple of terraform files within that directory.
□ Separate long-lived from short-lived infrastructure: resources that change rarely should not be grouped together with resources
that change often.
□ Do not try to cover every edge case: this can quickly lead to highly complex modules, which are difficult to maintain and configure.
Modules should be reusable blocks of infrastructure, and catering to edge cases goes against that purpose.
□ Support only the necessary configuration variables: do not expose all the internals of the module for configuration via variables.
This hurts encapsulation and makes the module harder to work with.
Terraform
Building Modules
When to create modules and which best practices to follow?
□ Output as much information as possible: even if there is no clear use for some information, providing it as an output will make the
module easier to use in future scenarios.
□ Define a stable input and output interface: All used variables and outputs create coupling to the module. The more coupling, the
harder it is to change the interface without breaking changes. Keep this in mind when designing the module's interface.
□ Extensively document variables and outputs: this helps the module's users to quickly understand the module's interface and to
work more effectively with it.
□ Favor a flat and composable module structure instead of deeply nested modules: deeply nested modules become harder to
maintain over time and increase the configuration complexity for the module's users.
□ Make assumptions and guarantees explicit via custom conditions: do not rely on the users always passing valid input values.
Thoroughly validate the infrastructure created by the module to ensure it complies with the requirements the module must fulfill.
□ Make a module's dependencies explicit via input variables: data sources can be used to retrieve information a module needs, but
they create implicit dependencies, which are much harder to identify and understand. Opt for making these dependencies explicit by
requiring the information via input variables.
□ Keep a module's scope narrow: do not try to do everything inside a single module.
Terraform
Terraform
Publishing Modules
Publishing Modules
Make your Terraform module available to others via Terraform Registry
■ Anyone can publish a module, as long as the following conditions are met:
□ The module must be on GitHub and must be a public repo. This is required only for using the public registry; for private ones, this can
be ignored.
□ Repositories must use a naming format: terraform-<PROVIDER>-<NAME>, where PROVIDER is the provider where resources are
created, and NAME is the type of infrastructure managed by the module.
□ The module repository must have a description, which is used to populate the short description of the module. This should be a simple
one sentence description of the module.
□ The module should adhere to the standard module structure (main.tf, outputs.tf, variables.tf). The registry uses this
information to inspect the module and generate documentation.
□ Uses x.y.z tags for releases. The registry uses these tags to identify module versions. Release tag names must be a semantic version,
and can be optionally prefixed with a "v".
■ Published modules support versioning, automatically generate documentation, allow browsing version histories, show examples and
READMEs, and more.
Terraform
Terraform
Object Validation
Object Validation
More reliable infrastructure through pre and postconditions, and check assertions
■ Used from within resources and data ■ Used from within resources and data ■ Used from outside resources and data
blocks blocks blocks
■ Cannot reference the resource itself. ■ Can reference the resource itself. ■ Can reference information from across
the current Terraform project.
■ Can be used to check the validity of data ■ Can be used to check the validity of the
blocks or variables that the resource resource's configuration. ■ Results only in a warning and does not
references. stop the apply process.
Terraform
Object Validation - Pre and Postconditions
No Terraform exits
without going into the
apply phase
Yes Validation
executed apply phase
Yes
Validation
successful?
Validation
successful? Terraform exits
Validation deferred Validation No without applying
No
plan phase until the apply executed downstream
phase resources
Yes
Information
already available?
The apply phase executes until there are no more
changes to be applied.
Terraform
Terraform
State Manipulation
State Manipulation
Recreate, import, refactor, and untrack infrastructure within Terraform
Force the recreation of a resource that is Import existing resources into a Rename resources without recreating
tracked by a Terraform configuration. Terraform project, and start managing them, and move them inside and outside
Can be used when a certain resource them with Infrastructure as Code. of modules whenever needed. Prevents
goes into an invalid state, but the recreation due to changing resource
configuration is correct and hasn't addresses in Terraform.
changed.
Remove a resource from a Terraform Leverage Terraform's code generation Force state unlocking, and pull and push
configuration without actually destroying feature to generate a best-effort the state file from remote backends to
that resource. Useful when we want to configuration based on existing perform careful, fine-grained editing in
manage the resource independently of resources. Can be used when importing case something is wrong with it.
the Terraform project. resources into Terraform.
Terraform
Terraform
Workspaces
Workspaces
Use a single code-base for different environments
■ Workspaces allow us to leverage the same configuration directory to create different environments.
□ As a result, we can reduce code duplication and avoid installing multiple copies of modules and providers.
■ When using the CLI in a workspace, resources from other workspaces are not considered.
■ Different workspaces correspond to different state data. Terraform stores them in different .tfstate files.
■ We can use terraform.workspace to access the current workspace, and change options based on the selected workspace.
□ Recommendation: do not use terraform.workspace for conditional operations. Instead, receive the information via variables.
Terraform
Terraform
Terraform Cloud
Terraform Cloud
Execute Terraform code in a secure remote environment instead of locally
■ Terraform Cloud is a solution from HashiCorp to manage Terraform projects remotely. It offers several features:
□ Run history
■ Resources are organized into workspaces, and workspaces can be organized into projects.
■ Workspaces store resource definitions, environment and input variables, and state files.
Terraform
Terraform Cloud - Workspaces
Organize workspace information in a single place
■ They are a required component of Terraform Cloud Local Terraform Terraform Cloud
projects.
Configuration Saved on disk VCS repository,
■ In addition to managing information in a central place, API/CLI
workspaces are also a major component of role-based
access to Terraform projects in Terraform Cloud.
Variables Passed via the different Saved in workspace
■ Paid plans offer workspace-based health checks that methods we explored
support drift detection and continuous infrastructure (.tfvars, CLI arguments,
validation, as well as other advanced features. etc.)
■ Workspaces can be linked to branches of VCS repositories, State file Saved locally or by using a Saved in workspace
and we can specify which files and directories within the remote backend
VCS repository trigger runs.
Secrets Passed via environment Saved in workspace
variables or through the
prompt
Terraform
Terraform
Terraform Cloud Workflows
Terraform Cloud Workflows
Trigger runs from the CLI, UI, connected VCS repositories, or the Terraform API
CLI-driven workflow: developers or UI or API-driven workflow: developers VCS-driven workflow: developers push
CI/CD systems login to Terraform Cloud or systems manually trigger and code to a remote repository, which then
via the CLI and interact with the remote manage runs by interacting with triggers the terraform plan and apply
environment via CLI commands. Terraform Cloud's UI or API. commands.
Terraform