Professional Documents
Culture Documents
HashiCorp Notes & Tips - Cheat Sheet
HashiCorp Notes & Tips - Cheat Sheet
A complete study guide for HashiCorp Terraform Associate Certification Exam (003).
About Exam
Exam Preparation
To be honest, their documentation is more than enough for this exam. They have a very good
Exam study guide and exam review guide. I would suggest you go through these links in
order and would highly recommend you practice while going through these materials.
• Exam Study Guide
• Sample Questions
• Exam Review Guide
Exam Notes
Infrastructure as Code
Terraform Workflow
Terraform Provider
Input Variables
1. The name of a variable can be any valid identifier except the following:- source,
version, providers, count, for_each, lifecycle, depends_on, locals.
2. The type of a variable can be string, number, bool, list, set, map, object, and tuple.
3. The nullable argument in variable block can be set to false to not allow null
values. Default is true.
4. The validation argument in variable block can be used to apply custom validation
on the value
5. The sensitive argument in variable block can be set to true to prevent from
showing its value in the plan and apply output
variable "image_id" {
type = string
description = "The id of the machine image (AMI) to use for the server."
default = ami-abc123
nullable = false
sensitive = false
validation {
condition = length(var.image_id) > 4 && substr(var.image_id, 0, 4) == "ami-"
error_message = "The image_id value must be a valid AMI id, starting with \"ami-\"."
}
}
The loading of a variable goes from highest precedence (1) to lowest (5):-
1. Command line flag - specify in command using -var e.g. terraform plan -
var=environment="prod"
2. Configuration file - set in your terraform.tfvars file
3. Environment variable - part of your shell environment
e.g. TF_VAR_environment=prod
4. Default Config - default value in variables.tf
5. User manual entry - if not specified, prompt the user for entry
Terraform Backend
• A backend defines where Terraform stores its state data files. There are two
backend types: local and remote.
• By default, Terraform uses a backend called local, which stores state as a local file
on disk.
• Terraform v1.4.x supports the following backend
types:- local, remote, azurerm, consul, cos, gcs, http, kubernetes, oss, pg, s3
• Terraform v1.2.x also supports following backend
types:- artifactory, etcd, etcdv3, manta, swift
• Backend types support state
locking:- local, remote, azurerm, consul, cos, gcs, http, kubernetes, oss, pg, s3,
etcdv3, manta, swift
• Backend types doesn’t support state locking:- artifactory, etcd
• A terraform configuration terraform block can only have one backend block.
terraform {
backend "remote" {
organization = "example_corp"
workspaces {
name = "my-app-prod"
}
}
}
terraform {
cloud {
organization = "example_corp"
## Required for Terraform Enterprise; Defaults to app.terraform.io for
Terraform Cloud
hostname = "app.terraform.io"
workspaces {
tags = ["app"]
}
}
}
Source: https://developer.hashicorp.com/terraform/language/expressions/type-constraints
Environment Variables
Environment
Example
Variable
TF_LOG=trace|debug|info|warn|error to enable logs at different log level
TF_LOG TF_LOG=off to disable logs
TF_LOG=json to generate logs in JSON format
to enable/disable logging separately for terraform core, values same as
TF_LOG_CORE
TF_LOG
to enable/disable logging separately for terraform providers, values same as
TF_LOG_PROVIDER
TF_LOG
to specify where the log should persist its output to
TF_LOG_PATH
e.g. TF_LOG_PATH=./terraform.log , by default logs appear on stderr
TF_VAR_name to set the variables e.g. region variable TF_VAR_region=us-east1
Terraform Commands
Command ▼ Description
1. First command to run. Safe to run it multiple times
2. Initialize a working directory that contains terraform configuration files:-
- create hidden .terraform directory
- configure backend, download and install provider plugins
into .terraform/providers
- download modules into .terraform/modules
terraform init
- create dependency lock file .terraform.lock.hcl
3. Use terraform init -from-module=MODULE-SOURCE to check out the
configuration from VCS and initialize the current working directory.
4. Use terraform init -backend-config=PATH for partial backend
configuration, in situations where the backend settings are dynamic or
sensitive and so cannot be statically specified in the configuration file.
Use to download and update modules mentioned into
terraform get
a .terraform subdirectory of the current working directory.
1. Creates an execution plan, which lets you preview the changes that
Terraform plans to make to your infrastructure
2. Reads the current state of any already-existing remote objects to make
sure that the Terraform state is up-to-date.
terraform plan 3. Compares the current configuration to the prior state and noting any
differences.
4. Proposes a set of change actions that should, if applied, make the remote
objects match the configuration.
5. You can use the optional -out=FILE option to save the generated plan to
Command ▼ Description
a file on disk
6. Terraform has two alernative planning modes: -destroy and -refresh-
only
7. Terraform has following planning options:- -refresh=false , -
replace=ADDRESS , -target=ADDRESS , -var 'NAME=VALUE' , and -var-
file=FILENAME
8. Terraform planning mode and planning options are available for
both terraform plan and terraform apply
1. Apply the execution plan to provision the resources
terraform apply 2. You can pass the -auto-approve option to instruct Terraform to apply
the plan without asking for confirmation.
1. Destroy all remote objects managed by a particular Terraform
terraform destroy configuration.
2. This command is effectively an alias for terraform apply -destroy
1. terraform login [hostname] is used to automatically obtain and save
an API token for Terraform Cloud, Terraform Enterprise, or any other host
terraform login that offers Terraform services.
2. If you don’t provide an explicit hostname, Terraform will assume you
want to log in to Terraform Cloud at app.terraform.io
1. terraform logout [hostname] is used to remove credentials stored
by terraform login . These credentials are API tokens for Terraform
terraform logout
Cloud, Terraform Enterprise, or any other host that offers Terraform
services.
2. If you don’t provide an explicit hostname, Terraform will assume you
want to log out of Terraform Cloud at app.terraform.io
Provides an interactive command-line console for evaluating and
terraform console
experimenting with expressions.
1. Format code in terrform style convention
2. Indent two space for each nesting level and align equals signs at
terraform fmt
same nesting level
3. terraform fmt -diff displays diff of formatting changes
1. Validates the configuration files in a directory, referring only to the
configuration and not accessing any remote services such as remote state,
provider APIs, etc.
terraform validate
2. Verify whether a configuration is syntactically valid and internally
consistent, regardless of any provided variables or existing state
3. terraform validate -json produce validation result in JSON format
1. Used to generate a visual representation of either a configuration or
execution plan. The output is in the DOT format, which can be used by
GraphViz to generate image or charts e.g. terraform graph | dot -Tsvg
terraform graph
> graph.svg
2. Use optional -plan tfplan option to render graph using specified plan
file
1. Used to extract the value of an output variable from the state file.
2. Use optional -json and -raw option for output to formatted as JSON
terraform output
and String format. Any sensitive values in Terraform state will be displayed
in plain text.
Command ▼ Description
1. Used to provide human-readable output from a state or plan file
terraform show 2. Use optional -json option for JSON representation of plan,
configuration, and current state
1. The terraform state command and its subcommands can be used for
various tasks related to the Terraform state.
2. The terraform state pull and terraform state push subcommands
terraform state
can be used to retrieve and upload the Terraform state from and to a remote
backend, respectively. This is useful when multiple users or systems are
working with the same Terraform configuration.
Used in the less common situation where you wish to retain an existing
remote object but track it as a different resource instance address in
terraform state mv
Terraform, such as if you have renamed a resource block or you have
moved it into a different module in your configuration.
Used in the less common situation where you wish to remove a binding to
an existing remote object without first destroying it, which will effectively
terraform state rm
make Terraform “forget” the object while it continues to exist in the remote
system.
Used to replace the provider for resources in a Terraform state
terraform state e.g. terraform state replace-provider hashicorp/aws
replace-provider registry.acme.corp/acme/aws replaces the hashicorp/aws provider
by achme
terraform state list Used to list resources within a Terraform state.
Used to show attributes of a single resource in the terraform state
terraform state show
e.g. terraform state show aws_instance.foo
1. This command read the remote infrastructure and update the terraform
state file to match with remote objects.
2. This won’t modify your real remote objects, but it will modify the
terraform state file.
3. This command is here primarily for backward compatibility, but we
don’t recommend using it because it provides no opportunity to review the
terraform refresh
effects of the operation before updating the state.
4. Equivalent command in Terraform v0.15.4 or later is terraform apply
-refresh-only -auto-approve
5. It is recommended to use terraform apply -refresh-
only or terraform plan -refresh-only instead, which gives an
opportunity to review the changes.
1. Informs Terraform that a particular object has become degraded or
damaged. Terraform represents this by marking the object as “tainted” in
the Terraform state, and Terraform will propose to replace it in the next
terraform taint
plan you create.
2. Use the -replace option with terraform apply For Terraform v0.15.2
and later
1. Manually unlock the state for the defined configuration.
terraform force- 2. This command removes the lock on the state for the current
unlock configuration. The behavior of this lock is dependent on the backend being
used
Command ▼ Description
1. Terraform workspace command is used to manage worsspaces
2. State files for each workspace are stored in the
directory terraform.tfstate.d
3. terraform workspace list to list all existing workspaces
4. terraform workspace select prod to switch to existing workspace
terraform workspace with name prod
5. terraform workspace new uat to create and switch to new workspace
with name uat
6. terraform workspace delete dev to delete existing workspace with
name dev and it must not be your current workspace
7. terraform workspace show to show current workspace
Used to import the existing remote resources into the Terraform state file.
terraform import This allows Terraform to manage resources that were created outside of
Terraform.
//2. then run command to import existing remote aws instance with id i-abcd1234 to state
*.tfstate* file
$ terraform import aws_instance.example i-abcd1234
//3. copy the required configuration manually from state .tfstate file to config *.tf*
file
Source: https://developer.hashicorp.com/terraform/cli
Terraform Functions
Function
Function Name
Type
abs(-12.4) = 12.4
ceil(5.1) = 6
floor(4.9) = 4
log(16, 2) = 4
Numeric max(12, 54, 3) = 54
min(12, 54, 3) = 3
parseint("100", 10) = 100 and parseint("FF", 16) = 255
pow(3, 2) = 9
signum(-13) = -1 , signum(0) = 0 , and signum(344) = 1
chomp("hello\r\n") = hello
startswith("hello world", "hello") = true
String
endswith("hello world", "world") = true
format("There are %d lights", 4) = There are 4 lights
Function
Function Name
Type
formatlist("Hello, %s!", ["Olivia", "Sam"]) = ["Hello, Olivia!", "Hello,
Sam!"]
indent(5, "hello") = ・・・・・"hello"
join("-", ["foo", "bar", "baz"]) = foo-bar-baz
lower("HELLO") = hello
upper("hello") = HELLO
regex("[a-z]+", "53453453.345345aaabbbccc23454") = aaabbbccc
regexall("[a-z]+", "1234abcd5678efgh9") = ["abcd", "efgh"]
replace("1 + 2 + 3", "+", "-") = 1-2-3
split(",", "foo,bar,baz") = ["foo","bar","baz"]
strrev("hello") = olleh
substr("hello world", 1, 4) = ello
title("hello world") = Hello World
trim("foobar", "far") = oob
trimprefix("helloworld", "hello") = world
trimsuffix("helloworld", "world") = hello
trimspace(" hello\n\n") = hello
abspath(path.root) = /home/user/some/terraform/root
dirname("foo/bar/baz.txt") = foo/bar
pathexpand("~/.ssh/id_rsa") = /home/steve/.ssh/id_rsa
basename("foo/bar/baz.txt") = baz.txt
file("${path.module}/hello.txt") = Hello World
Filesystem
fileexists("${path.module}/hello.txt") = true
fileset(path.module, "files/*.txt") = ["files/hello.txt",
"files/world.txt"]
filebase64("${path.module}/hello.txt") = SGVsbG8gV29ybGQ=
templatefile(path, vars)
Source: https://developer.hashicorp.com/terraform/language/functions
Terraform Tiers
Source: https://www.hashicorp.com/products/terraform/pricing
Get Help
terraform -help — Get a list of available commands for execution with descriptions. Can be
terraform fmt -help — Display help options for the fmt command.
Show Your Terraform Version
terraform version — Show the current version of your Terraform and notifies you if there is a
newer version available for download.
Format Your Terraform Code
This should be the first command you run after creating your configuration files to ensure
your code is formatted using the HCL standards. This makes it easier to follow and aids
collaboration.
terraform fmt — Format your Terraform configuration files using the HCL language standard.
terraform fmt --diff — Display differences between original configuration files and
formatting changes.
terraform fmt --check — Useful in automation CI/CD pipelines, the check flag can be used to
ensure the configuration files are formatted correctly, if not the exit status will be non-zero. If
files are formatted correctly, the exit status will be zero.
Initialize Your Directory
terraform init — In order to prepare the working directory for use with Terraform,
the terraform init command performs Backend Initialization, Child Module Installation, and
Plugin Installation.
plugins.
terraform init -lock=false — Initialize the working directory, don’t hold a state lock during
backend migration.
terraform init -input=false — Initialize the working directory, and disable interactive
prompts.
terraform init -migrate-state — Reconfigure a backend, and attempt to migrate any existing
state.
terraform get — Download and installs modules needed for the configuration.
terraform get -update — Check the versions of the already installed modules against the
terraform validate -json — To see easier the number of errors and warnings that you have.
terraform plan -out=<path> — Save the plan file to a given path. Can then be passed to
terraform plan -destroy — Create a plan to destroy all objects rather than the usual actions.
default, a plan will be generated first and will need to be approved before it is applied.
terraform apply -auto-approve — Apply changes without having to interactively type ‘yes’ to
terraform apply <planfilename> — Provide the file generated using the terraform plan -
out command. If provided, Terraform will take the actions in the plan without any
confirmation prompts.
terraform apply -lock=false — Do not hold a state lock during the Terraform apply
operation. Use with caution if other engineers might run concurrent commands against the
same workspace.
the resources being managed in Terraform. Will not modify your infrastructure.
View Your State File
terraform show — Show the state file in a human-readable format.
terraform show <path to statefile> — If you want to read a specific state file, you can
provide the path to it. If no path is provided, the current state file is shown.
Manipulate Your State File
terraform state — One of the following subcommands must be used with this command in
order to manipulate the state file.
terraform state list — Lists out all the resources that are tracked in the current state file.
terraform state mv — Move an item in the state, for example, this is useful when you need to
tell Terraform that an item has been renamed, e.g. terraform state mv vm1.oldname
vm1.newname
terraform state pull > state.tfstate — Get the current state and outputs it to a local file.
terraform state push — Update remote state from the local state file.
terraform state rm — Remove the specified instance from the state file. Useful when a
terraform state show <resourcename> — Show the specified resource in the state file.
Import Existing Infrastructure into Your Terraform
State
terraform import vm1.name -i id123 — Import a VM with id123 into the configuration
requirements.
Manage Your Workspaces
terraform workspace — One of the following subcommands must be used with the workspace
command. Workspaces can be useful when an engineer wants to test a slightly different
version of the code. It is not recommended to use Workspaces to isolate or separate the same
infrastructure between different development stages, e.g. Dev / UAT / Production, or different
internal teams.
terraform workspace new <workspace name> — Create a new workspace with a specified name.
by default at the end of a terraform apply, this command can be useful if you want to view
them independently.
terraform output -state=<path to state file> — List the outputs held in the specified state
machine-readable.
terraform output vm1_public_ip — List a specific output held in your state file.
workspace. Useful when a lock has become ‘stuck’, usually after an incomplete Terraform run.
Log In and Out to a Remote Host (Terraform Cloud)
terraform login — Grab an API token for Terraform cloud (app.terraform.io) using your
browser.
terraform logout — Remove the credentials that are stored locally after logging in, by default
terraform logout <hostname> — Remove the credentials that are stored locally after logging in
terraform graph -plan=tfplan — Produce a dependency graph using a specified plan file
terraform graph -type=plan — Specify the type of graph to output, either plan, plan-refresh-
terraform graph -draw-cycles — You can see if there are any dependency cycles between the
resources.
Test Your Expressions
terraform console — Allow testing and exploration of expressions on the interactive console
With the terraform console command, you have the ability to test different pieces of code. All
you have to do is write terraform console, and then you can write HCL code.
terraform console
# The below command will merge list elements into a string, separating them with
commas.
> join(",",["foo","bar"])
"foo,bar"
# You can use resource parameters to get details about them. With the below command, we
will get the public ip of an ec2 instance called my_ec2
> aws_instance.my_ec2.public_ip
3.153.2.10
Shell Tab-completion
Terraform also comes with an optional Shell Tab-completion. It can be useful if you are just
starting out with Terraform. However, Terraform CLI is pretty lightweight, and you won’t
usually reach very long commands.
terraform -install-autocomplete
After that you will need to resource your profile. This is done by either closing and opening
the terminal, or by running source path_to_your_profile.
What is Terraform?
Terraform is an infrastructure as code (IaC) tool developed by HashiCorp, which was initially
open-source but recently switched to a BSL. It uses a declarative language called HashiCorp
Configuration Language (HCL) to define infrastructure resources. Terraform supports a wide
variety of cloud providers such as AWS, Microsoft Azure, Google Cloud, or Oracle Cloud
Infrastructure, but it can also be used with Kubernetes, Helm, and many others. It is stateful,
keeping track of the deployed infrastructure using a state file.
The Terraform Command Line Interface (CLI), is a command-line tool that provides a simple
way for users to interact with the infrastructure components defined in the Terraform
configuration. It offers multiple commands, from initializing your terraform directory to
planning, applying, and destroying infrastructure resources. With the Terraform CLI, you also
have the ability to check outputs, do state-related operations, and even test different
expressions.