Download as pdf or txt
Download as pdf or txt
You are on page 1of 21

Terraform Cheat Sheet – 23 Terraform CLI

Commands & Examples

A complete study guide for HashiCorp Terraform Associate Certification Exam (003).

Real Exam Questions: -


https://certyiq.com/papers?provider=hashicorp&exam=terraform-associate

About Exam

• Terraform Associate certification is a specialty certification in Terraform


conducted by Hashicorp.
• This exam is recommended for Cloud, DevOps, and SRE engineers.
• The Terraform Associate 003 exam detail is available here
• You have to answer 57 questions within 60 minutes from your laptop under the
supervision of an online proctor.
• You need to get “around” 70% to pass the exam so you can afford to get 17
questions wrong.
• The exam costs you 70 USD and there is no free retake.
• The exam can be taken in English language only.
• You should expect different types of questions format such as Multiple Choice,
Multiple Answers, True or false, and Text Match where you have to type the answer
to fill in the blank.
• You get the exam result instantly and receive an email with the same result.
• This certification is valid for 2 years.
• This exam is targeted for Terraform version 1.0 and higher.
• Recommended studying for 1-2 hours a day for 2-4 weeks depending upon your
daily commitment.
• You can register for the exam here

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 is an Infrastructure as Code (IaC) tool that is Declarative and Cloud


Agnostic
• Infrastructure lifecycle:-
1. “Day 0” code provisions and configures your initial infrastructure.
2. “Day 1” refers to OS and application configurations you apply after
you’ve initially built your infrastructure.
• IaC enhances the Infrasture lifecycle:
1. Reliability: IaC makes changes idempotent, consistent, repeatable,
and predicable
2. Manageability
3. Sensibility
• Popular Infrastructure as Code (IaC) tools:
Tool Supports
ARM Templates, Azure Blueprints only Microsoft Azure
CloudFormation only Amazon AWS
Cloud Deployment Manager only Google Cloud Platform GCP
Terraform AWS, Azure, GCP, and on-prem

• Terraform is written in HashiCorp Configuration Language (HCL). HCL is designed


to strike a balance between human-readable and machine-parsable

Terraform Workflow

The core Terraform workflow consists of these stages:-

1. Write: Define infrastructure in a configuration file e.g. main.tf


2. Initialize: Prepares the working directory so Terraform can run the configuration
using terraform init command
3. Plan: Review the changes Terraform will make to your infrastructure
using terraform plan command
4. Apply: Terraform provisions your infrastructure and update the state file
using terraform apply command

Terraform Provider

• Provider is a plugin that allows Terraform to interact with a specific cloud


provider or service
• Provider provides abstraction above the upstream API and is responsible for
understanding API interactions and exposing resources.
• Major cloud vendors and non-cloud vendors can write, maintain, or collaborate
on Terraform providers
• At least one provider block is required in terraform configuration.
• Supports multiple provider instances using alias e.g. multiple aws provides with
a different region

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 automatically manages state in the workspaces. If your


configuration includes a cloud block, it cannot include a backend block.

terraform {
cloud {
organization = "example_corp"
## Required for Terraform Enterprise; Defaults to app.terraform.io for
Terraform Cloud
hostname = "app.terraform.io"

workspaces {
tags = ["app"]
}
}
}

• It is recommended to provide credentials and sensitive data using the credential


file or environment variable supported by the remote backend type.
• You must run terraform init when you change backend configuration or backend
type. Terraform auto-detects the changes and can migrate from existing state to
new configuration.

Terraform Type Constraints

Category Type Example Reference Value


variable "image_id" { type=string
Primitive string var.image_id
default="ami-abc123"}

Primitive number variable "threads" { type=number default=10 } var.threads

variable "set_password" { type=bool


Primitive bool var.set_password
default=false }

variable "az_names" { type=list(string)


Collection list var.az_names[0]
default=["us-west-1a", "us-west-2a"]}

variable "az_names" { type=set(string)


Collection set var.az_names[0]
default=["us-west-1a", "us-west-2a"]}

variable "amis" { type="map" default={ "us-


var.amis["us-east-
Collection map east-1"="ami-b374d5a5" "us-west-2"="ami-
1"]
4b32be2b" }}

variable "user_info" { type=object({


Structural object var.user_info.name
name=string address=string })}

variable "var1" { type=tuple([string, number,


Structural tuple var.var1[0]
bool]) default=["a", 15, true] }

Source: https://developer.hashicorp.com/terraform/language/expressions/type-constraints

References to Named Values

Type Expression Example


Input Variable var.<NAME> var.ami

Local Values local.<NAME> local.ami

Resources <RESOURCE TYPE>.<NAME>.<ATTRIBUTE> aws_instance.example.ami

Data Sources data.<DATA TYPE>.<NAME>.<ATTRIBUTE> data.aws_ami.ubuntu.id

Child Module Outputs module.<MODULE NAME>.<OUTPUT NAME> module.prod_subnet.subnet_id


Source: https://developer.hashicorp.com/terraform/language/expressions/references

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.

terraform import command used using below three steps:-

//1. first write empty resource block in config *.tf* file


resource "aws_instance" "example" {
# ...instance configuration...
}

//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

alltrue(["true", true]) = true


anytrue([true, false]) = true
chunklist
coalesce("a", "b") = a and coalesce("", "b") = b
coalescelist(["a", "b"], ["c", "d"]) = ["a", "b"] and coalescelist([],
["c", "d"]) = ["c", "d"]
compact(["a", "", "b", "c"]) = ["a", "b", "c"]
concat(["a", ""], ["b", "c"]) = ["a", "", "b", "c"]
contains(["a", "b", "c"], "a") = true
distinct(["a", "b", "a", "c", "d", "b"]) = ["a", "b", "c", "d"]
element(["a", "b", "c"], 1) = b
flatten([["a", "b"], [], ["c"]]) = ["a", "b", "c"]
index(["a", "b", "c"], "b") = 1
keys({a=1, c=2, d=3}) = ["a", "b", "d"]
length(["a", "b"]) = 2
tolist([a, b, c]) converts to list
Collection lookup
tomap({a = "b" c = "d"}) converts to map
matchkeys
merge
one
range(3) = [0, 1, 2] and range(1, 4) = [1, 2, 3]
reverse([1, 2, 3]) = [3, 2, 1]
setintersection(["a", "b"], ["b", "c"], ["b", "d"]) = ["b"]
setproduct
setsubtract(["a", "b", "c"], ["a", "c"]) = ["b"]
setunion(["a", "b"], ["b", "c"], ["d"]) = ["d", "b", "c", "a"]
slice(["a", "b", "c", "d"], 1, 3) = ["b", "c"]
sort(["e", "d", "a", "x"]) = ["a", "b", "e", "x"]
sum([10, 13, 6, 4.5]) = 33.5
transpose
values({a=3, c=2, d=1}) = [3, 2, 1]
zipmap(["a", "b"], [1, 2]) = {"a"=1 "b"=2}
Function
Function Name
Type
base64encode("Hello World") = SGVsbG8gV29ybGQ=
base64decode("SGVsbG8gV29ybGQ=") = Hello World
base64gzip
textencodebase64("Hello World", "UTF-16LE") =
SABlAGwAbABvACAAVwBvAHIAbABkAA==
textdecodebase64("SABlAGwAbABvACAAVwBvAHIAbABkAA==", "UTF-16LE") = Hello
Encoding World
csvdecode
jsondecode
jsonencode
urlencode("Hello World!") = Hello+World%21
yamldecode
yamlencode

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)

formatdate("DD MMM YYYY hh:mm ZZZ", "2018-01-02T23:12:01Z") = 02 Jan 2018


23:12 UTC
Date and
timeadd("2017-11-22T00:00:00Z", "10m") = 2017-11-22T00:10:00Z
Time
timecmp("2017-11-22T00:00:00Z", "2017-11-22T01:00:00Z") = -1
timestamp() = 2023-05-13T07:44:12Z

base64sha256("hello world") = uU0nuZNNPgilLlLX2n2r+sSE7+N6U4DukIj3rOLvzek=


filebase64sha256()
base64sha512("hello world") =
MJ7MSJwS1utMxA9QyQLytNDtd+5RGnx6m808qG1M2G+YndNbxf9JlnDaNCVbRbDP2DDoH2Bdz3
3FVC6TrpzXbw==
filebase64sha512()
md5("hello world") = 5eb63bbbe01eeed093cb22bb8f5acdc3
filemd5()
sha1("hello world") = 2aae6c35c94fcfb415dbe95f408b9ce91ee846ed
filesha1()
Hash and C
sha256("hello world") =
rypto
b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9
filesha256()
sha512("hello world") =
309ecc489c12d6eb4cc40f50c902f2b4d0ed77ee511a7c7a9bcd3ca86d4cd86f989dd35bc5
ff499670da34255b45b0cfd830e81f60
filesha512()
bcrypt("hello world") =
$2a$10$D5grTTzcsqyvAeIAnY/mYOIqliCoG7eAMX0/oFcuD.iErkksEbcAa
rsadecrypt(filebase64("${path.module}/ciphertext"),
file("privatekey.pem")) = hello world
Function
Function Name
Type
uuid() = b5ee72a3-54dd-c4b8-551c-4bdc0204cedb
uuidv5("dns", "www.terraform.io") = a5008fae-b28c-5ba5-96cd-82b4c53552d6

IP Network cidrhost, cidrnetmask, cidrsubnet, cidrsubnets


Type Conv
can, nonsensitive, sensitive, tobool, tolist, tomap, tonumber, toset, tostring, try, type
ersion

Source: https://developer.hashicorp.com/terraform/language/functions

Terraform Tiers

OSS (Open Cloud Cloud Team & Cloud


Feature ▼ Enterprise
Source) Free Governance Business
Infrastructure as code
(HCL)
Workspaces
Variables
Runs (separate plan and
apply)
Resource graph
Providers
Modules
Public registry
Remote state storage
Secure variable storage
Remote runs (plan &
apply)
Private registry
Projects
Dynamic provider
credentials
Run triggers
VCS connection
Workspace
management
Team management
OSS (Open Cloud Cloud Team & Cloud
Feature ▼ Enterprise
Source) Free Governance Business
Cost estimation
Policy as code
(Sentinel)
Policy as code (OPA)
Run tasks: Advisory
enforcement
Run tasks: Hard
enforcement
Policy enforcement level:
Advisory
Policy enforcement level:
Soft/hard mandatory
No-code provisioning
Configuration designer
SSO (Single Sign On)
Support for ServiceNow
integration
Drift detection
Audit logging
Pay to
Concurrent Runs 1 2(Add-on)
customize
Pay to
Self-hosted agents
customize
Cross-organization
registry sharing
Runtime metrics
(Prometheus)
Air gap network
deployment
Application-level logging
Log forwarding
Clustered Horizontal
Scaling

Source: https://www.hashicorp.com/products/terraform/pricing

Get Help
terraform -help — Get a list of available commands for execution with descriptions. Can be

used with any other subcommand to get more information.

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 --recursive — Also format files in subdirectories

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.

terraform init -get-plugins=false — Initialize the working directory, do not download

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 init -verify-plugins=false — Initialize the working directory, do not verify

plugins for Hashicorp signature

Download and Install Modules


Note this is usually not required as this is part of the terraform init command.

terraform get — Download and installs modules needed for the configuration.

terraform get -update — Check the versions of the already installed modules against the

available modules and installs the newer versions if available.


Validate Your Terraform Code
terraform validate — Validate the configuration files in your directory and does not access
any remote state or services. terraform init should be run before this command.

terraform validate -json — To see easier the number of errors and warnings that you have.

Plan Your Infrastructure


terraform plan — Plan will generate an execution plan, showing you what actions will be

taken without actually performing the planned actions.

terraform plan -out=<path> — Save the plan file to a given path. Can then be passed to

the terraform apply command.

terraform plan -destroy — Create a plan to destroy all objects rather than the usual actions.

Deploy Your Infrastructure


terraform apply — Create or update infrastructure depending on the configuration files. By

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

the plan. Useful in automation CI/CD pipelines.

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.

terraform apply -parallelism=<n> — Specify the number of operations run in parallel.

terraform apply -var="environment=dev" — Pass in a variable value.

terraform apply -var-file="varfile.tfvars" — Pass in variables contained in a file.

terraform apply -target=”module.appgw.0" — Apply changes only to the targeted resource.

Destroy Your Infrastructure


terraform destroy — Destroy the infrastructure managed by Terraform.

terraform destroy -target=”module.appgw.0" — Destroy only the targeted resource.

terraform destroy --auto-approve — Destroy the infrastructure without having to

interactively type ‘yes’ to the plan. Useful in automation CI/CD pipelines.

terraform destroy -target="module.appgw.resource[\"key\"]" — Destroy an instance of a

resource created with for_each.


‘Taint’ or ‘Untaint’ Your Resources
Use the taint command to mark a resource as not fully functional. It will be deleted and re-
created.
terraform taint vm1.name — Taint a specified resource instance.

terraform untaint vm1.name — Untaint the already tainted resource instance.

Refresh the State File


terraform refresh — Modify the state file with updated metadata containing information on

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 replace-provider hashicorp/azurerm customproviderregistry/azurerm —

Replace a provider, useful when switching to using a custom provider registry.

terraform state rm — Remove the specified instance from the state file. Useful when a

resource has been manually deleted outside of Terraform.

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

defined in the configuration files under vm1.name.

Get Provider Information


terraform providers — Display a tree of providers used in the configuration files and their

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 show — Show the name of the current workspace.

terraform workspace list — List your workspaces.

terraform workspace select <workspace name> — Select a specified workspace.

terraform workspace new <workspace name> — Create a new workspace with a specified name.

terraform workspace delete <workspace name> — Delete a specified workspace.

View Your Outputs


terraform output — List all the outputs currently held in your state file. These are displayed

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

file. -state option is ignored when the remote state is used.


terraform output -json — List the outputs held in your state file in JSON format to make them

machine-readable.

terraform output vm1_public_ip — List a specific output held in your state file.

Release a Lock on Your Workspace


terraform force-unlock <lock_id> — Remove the lock with the specified lock ID from your

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 login <hostname> — Log in to a specified host.

terraform logout — Remove the credentials that are stored locally after logging in, by default

for Terraform Cloud (app.terraform.io).

terraform logout <hostname> — Remove the credentials that are stored locally after logging in

for the specified hostname.


Produce a Dependency Diagram
terraform graph — Produce a graph in DOT language showing the dependencies between
objects in the state file. This can then be rendered by a program called Graphwiz (amongst
others).

terraform graph -plan=tfplan — Produce a dependency graph using a specified plan file

(generated using terraform plan -out=tfplan).

terraform graph -type=plan — Specify the type of graph to output, either plan, plan-refresh-

only, plan-destroy, or apply.

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

using the command line. e.g. 1+2 🙂

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"

# The below command will do math operations


> 1 + 5
6

# 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

Switch Working Directory


You also have the ability to run Terraform from another directory if the need arises. This is
particularly useful when you are using different automations and you don’t want to change
directory. This is done by:

terraform -chdir=”../dev” apply

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.

To install the Shell Tab-completion you will need to first run:

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.

What is Terraform CLI?

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.

Real Exam Questions: -


https://certyiq.com/papers?provider=hashicorp&exam=terraform-associate

You might also like