Terraform CLI Commands Explained for Beginners (With Examples)

Terraform is a powerful tool used by developers and operations teams to manage infrastructure safely and efficiently. In this article, we list all the important Terraform commands you need to know. We explain each one in simple English with examples.

Essential Lifecycle Commands

We start with the core Terraform CLI commands used to manage the life of your infrastructure. These commands handle the initial setup, planning of changes, and applying those changes to the real world.

terraform init

This command prepares your working directory. It downloads the necessary provider plugins and sets up the backend for storing state data. We use it first when starting a new project or cloning an existing one. It creates a safe environment for Terraform to run.

Example:

terraform init

terraform plan

This command creates an execution plan. It compares your current configuration with the real state of your infrastructure and shows what will change. We use this to preview actions before they happen. It ensures we do not make mistakes.

Example:

terraform plan

terraform apply

This command executes the actions proposed in the plan. It creates, updates, or destroys real infrastructure resources to match your configuration files. We use it when we are ready to make changes. It results in a deployed environment.

Example:

terraform apply

terraform destroy

This command removes all the resources defined in your configuration. It reads the state file and deletes every object Terraform manages. We use this to clean up test environments or unused resources. It leaves your cloud account empty.

Example:

terraform destroy

terraform refresh

This command updates the state file with the real-world status of your infrastructure. It does not change the actual resources but checks for any changes made outside of Terraform. We use this to sync our records. It keeps the state file accurate.

Example:

terraform refresh

Configuration and Validation Commands

In this section, we look at Terraform commands that help us write clean and correct code. These tools check our files for errors and format them nicely.

terraform validate

This command checks whether your configuration files are syntactically valid and internally consistent. It looks for errors within the code itself without accessing remote services. We use this often during coding to catch mistakes early. It returns success or error messages.

Example:

terraform validate

terraform fmt

This command automatically rewrites your configuration files to a standard format. It adjusts indentation, spacing, and alignment to make the code readable. We use this to keep a consistent style in our team. It modifies the files in place.

Example:

terraform fmt

terraform fmt -check

This command checks if the files are formatted correctly. It does not change the files but returns a list of files that need formatting. We use this in automated pipelines to enforce style rules. It outputs the names of messy files.

Example:

terraform fmt -check

terraform fmt -recursive

This command formats all configuration files in the current directory and all sub-directories. It ensures the entire project structure looks clean and uniform. We use this on large projects with many modules. It saves time compared to formatting folders one by one.

Example:

terraform fmt -recursive

terraform show

This command provides a human-readable output of the state or plan file. It lets us see the details of the resources currently managed. We use this to inspect the state data without reading the raw JSON file. It prints a summary to the console.

Example:

terraform show

State Management Commands

Managing state is crucial for safety. These Terraform CLI commands help us inspect, move, and backup the state file that tracks our infrastructure.

terraform state list

This command lists all the resources currently tracked in the state file. It shows the addresses of every managed resource. We use this to see what Terraform knows about. It provides a simple list of names.

Example:

terraform state list

terraform state show

This command shows detailed attributes of a specific resource in the state. It requires the resource address as an argument. We use this to debug specific resource properties. It prints all the data associated with that resource.

Example:

terraform state show aws_instance.example

terraform state mv

This command moves an item in the state. It can rename a resource or move it to a different module. We use this when we refactor our code and need to update the state tracking. It keeps the history of the resource intact.

Example:

terraform state mv aws_instance.old aws_instance.new

terraform state rm

This command removes items from the state file. It does not destroy the actual resource but stops Terraform from managing it. We use this when we want to manually manage a resource. It deletes the record only.

Example:

terraform state rm aws_instance.example

terraform state pull

This command downloads the current state file from the backend and prints it to standard output. It is useful for backing up the state manually. We use this to save a snapshot of our records. It outputs the raw state data.

Example:

terraform state pull > terraform.tfstate

terraform state push

This command uploads a local state file to the configured backend. It overwrites the remote state. We use this carefully to restore a backup. It updates the remote records with the local file.

Example:

terraform state push terraform.tfstate

terraform force-unlock

This command manually unlocks the state if a previous apply failed and left it locked. It requires a unique lock ID. We use this rarely when something goes wrong. It allows other commands to run again.

Example:

terraform force-unlock LOCK_ID

Import and Infrastructure Commands

Sometimes we have resources outside of Terraform. These Terraform commands help us bring those existing resources under our control.

terraform import

This command imports existing resources into the Terraform state. It matches the real resource to a configuration block. We use this when we start managing old infrastructure with new code. It adds the resource to the state without creating it.

Example:

terraform import aws_instance.example i-1234567890abcdef0

terraform import -config

This command specifies a directory of configuration files to use during the import. It helps when the configuration is not in the current directory. We use this to point to the correct module. It reads the code from the specified path.

Example:

terraform import -config=modules/app aws_instance.example i-1234567890abcdef0

terraform taint

This command marks a resource as tainted. It forces the resource to be destroyed and recreated on the next apply. We use this when a resource is corrupted or needs a forced replacement. It flags the resource for renewal.

Example:

terraform taint aws_instance.example

terraform untaint

This command removes the tainted status from a resource. It cancels the plan to destroy and recreate the resource. We use this if we marked a resource by mistake. It restores the resource to a normal state.

Example:

terraform untaint aws_instance.example

Output and Graphing Commands

Visualising data is important. These Terraform CLI commands help us see the results of our work and understand the relationships between resources.

terraform output

This command extracts the values of output variables defined in your configuration. It shows the results after a successful apply. We use this to get IP addresses, DNS names, or other important data. It prints the values to the screen.

Example:

terraform output

terraform output -json

This command displays all output values in JSON format. It provides structured data that is easy for other programs to read. We use this in scripts or automation tools. It outputs a valid JSON object.

Example:

terraform output -json

terraform output -raw

This command displays the value of a specific output as a raw string. It is useful for piping a single value into another command. We use this to get clean text without special formatting. It prints the string directly.

Example:

terraform output -raw instance_ip

terraform graph

This command generates a visual graph of the resources in your configuration. It shows the dependencies and relationships between them. We use this to understand the structure of our infrastructure. It outputs data in the DOT format.

Example:

terraform graph

terraform graph -type=plan

This command generates a graph showing the plan execution steps. It visualizes the order in which Terraform will perform actions. We use this to see the workflow of changes. It produces a DOT graph of the plan.

Example:

terraform graph -type=plan

Workspace Management Commands

Workspaces allow us to manage multiple environments with one codebase. These Terraform CLI commands help us switch between different states.

terraform workspace list

This command lists all existing workspaces. It shows which workspace is currently active. We use this to see what environments we have. It prints a list of names.

Example:

terraform workspace list

terraform workspace show

This command displays the name of the current workspace. It tells us exactly which environment we are working in right now. We use this to verify we are in the right place. It outputs a single name.

Example:

terraform workspace show

terraform workspace new

This command creates a new workspace and switches to it. It sets up a separate state file for that environment. We use this to start a new staging or development environment. It results in a blank state for that workspace.

Example:

terraform workspace new dev

terraform workspace select

This command switches to an existing workspace. It changes the context to the chosen environment. We use this to move between development, testing, and production. It loads the state for the selected workspace.

Example:

terraform workspace select production

terraform workspace delete

This command deletes an existing workspace. It removes the state file for that environment. We use this to clean up old environments we no longer need. It deletes the workspace permanently.

Example:

terraform workspace delete dev

Provider and Module Commands

Dependencies are key in Terraform. These Terraform commands help us manage the providers and modules we use in our projects.

terraform providers

This command prints information about the providers required by the configuration. It shows the version constraints and source addresses. We use this to check which providers are needed. It lists them in a table format.

Example:

terraform providers

terraform providers lock

This command writes out dependency lock files for the configured providers. It ensures that every team member uses the exact same provider versions. We use this for consistency across teams. It creates lock files in the current directory.

Example:

terraform providers lock

terraform providers mirror

This command copies provider plugins to a local directory. It is useful for creating an offline cache of the providers. We use this in air-gapped environments. It downloads the plugins to the specified path.

Example:

terraform providers mirror /local/mirror/directory

terraform providers schema

This command prints out a JSON-formatted representation of the schemas for the providers. It shows the attributes and resources available. We use this to understand what a provider can do. It outputs a large JSON document.

Example:

terraform providers schema

terraform module install

This command installs the modules defined in the configuration. It downloads them from the specified sources. We use this to prepare local module copies. It downloads the modules to a local path.

Example:

terraform module install

Cloud and Collaboration Commands

Terraform Cloud offers remote features. These Terraform CLI commands connect our local CLI to the cloud platform.

terraform login

This command retrieves an API token for Terraform Cloud and saves it locally. It authenticates the CLI with the remote service. We use this to enable cloud operations. It opens a browser window for authentication.

Example:

terraform login

terraform logout

This command removes the stored API token for Terraform Cloud. It logs the user out from the CLI. We use this when we are finished working on a shared machine. It deletes the saved credentials.

Example:

terraform logout

terraform cloud

This command provides various subcommands for working with Terraform Cloud. It helps manage workspace tags and settings. We use this to control cloud-specific features. It groups several cloud management tasks.

Example:

terraform cloud

Testing and Debugging Commands

Testing is vital for reliability. These Terraform CLI commands help us verify our code works as expected.

terraform test

This command executes tests written in the Terraform language. It validates the logic of our modules and configurations. We use this to ensure our code behaves correctly. It runs the tests defined in test files.

Example:

terraform test

terraform console

This command starts an interactive console for evaluating expressions. It allows us to test functions and variable values. We use this to experiment with Terraform syntax quickly. It opens an interactive shell.

Example:

terraform console

terraform version

This command displays the current version of Terraform installed. It also shows the provider versions and protocol versions. We use this to check our installation status. It prints version information to the screen.

Example:

terraform version

Advanced Operation Flags

While not separate commands, these flags act as distinct operations for Terraform commands to handle specific scenarios.

terraform plan -out

This flag saves the execution plan to a file. It allows us to apply the exact same plan later. We use this for safety reviews before making changes. It creates a binary plan file.

Example:

terraform plan -out=tfplan

terraform apply -auto-approve

This flag applies the plan without asking for manual confirmation. It skips the interactive yes/no prompt. We use this in automated scripts and pipelines. It runs the apply automatically.

Example:

terraform apply -auto-approve

terraform apply -target

This flag restricts the operation to a specific resource. It only applies changes to the target address. We use this to fix broken resources in a large set. It focuses the action on one item.

Example:

terraform apply -target=aws_instance.example

terraform apply -replace

This flag forces Terraform to replace a specific resource. It destroys and recreates the resource even if no configuration changes exist. We use this to recover from failures. It ensures a fresh resource is created.

Example:

terraform apply -replace=aws_instance.example

terraform plan -destroy

This flag generates a plan for destroying all resources. It is the same as running the destroy command but allows a preview. We use this to see what will be deleted. It shows a destruction plan.

Example:

terraform plan -destroy

terraform plan -refresh-only

This flag updates the state file to match real resources without proposing changes. It is useful for detecting drift. We use this to sync state without modifying infrastructure. It updates the state records.

Example:

terraform plan -refresh-only

terraform init -upgrade

This flag installs the latest compatible provider and module versions. It ignores the existing lock file constraints. We use this to update our dependencies to the newest versions. It upgrades the plugins.

Example:

terraform init -upgrade

terraform init -reconfigure

This flag ignores any existing backend configuration and forces a new configuration. We use this when we change the backend settings. It reinitializes the backend completely.

Example:

terraform init -reconfigure

terraform init -migrate-state

This flag attempts to copy the existing state file to the new backend. We use this when moving from local to remote state. It migrates the data automatically.

Example:

terraform init -migrate-state

terraform output -state

This flag specifies the location of the state file to read outputs from. We use this when the state is in a non-standard place. It reads outputs from the given path.

Example:

terraform output -state=/path/to/statefile

terraform show -json

This flag prints the state or plan in a machine-readable JSON format. We use this to parse Terraform data with other tools. It outputs a structured JSON string.

Example:

terraform show -json

terraform destroy -target

This flag destroys only the specified resource and its dependencies. It limits the scope of the destroy command. We use this to remove specific items safely. It targets a single resource for deletion.

Example:

terraform destroy -target=aws_instance.example

terraform fmt -write=false

This flag checks if formatting is needed without actually writing changes to files. We use this to verify code style in CI/CD pipelines. It returns an exit code based on the check.

Example:

terraform fmt -write=false

terraform state mv -dry-run

This flag simulates the move operation without actually making changes. We use this to ensure the move command will do what we expect. It prints what would happen.

Example:

terraform state mv-dry-run aws_instance.old aws_instance.new

terraform state mv -lockout

This flag disables the state lock for the duration of the move operation. We use this only if the state lock is stuck. It performs the move without locking.

Example:

terraform state mv-lockout aws_instance.old aws_instance.new

terraform providers lock -net-mirror

This flag uses a network mirror to download provider signatures. We use this in air-gapped environments with a custom mirror. It contacts the specified mirror URL.

Example:

terraform providers lock -net-mirror=http://example.com/mirror

terraform providers lock -fs-mirror

This flag uses a local filesystem mirror to find providers. We use this when we have providers stored on a local disk. It scans the local directory for plugins.

Example:

terraform providers lock -fs-mirror=/local/mirror

terraform test -verbose

This flag prints the output of the test execution in detail. It shows all logs and steps during the test. We use this to debug failing tests. It provides extra information.

Example:

terraform test -verbose

terraform test -json

This flag prints the results of the tests in JSON format. It allows automated systems to parse the test results easily. We use this for reporting in CI tools. It outputs structured JSON.

Example:

terraform test -json

terraform import -allow-missing-config

This flag allows importing resources even if the configuration block is not present yet. We use this to bring resources into state before writing the code. It imports without a config block.

Example:

terraform import -allow-missing-config aws_instance.example i-1234567890abcdef0

terraform workspace show -state

This flag prints the workspace for a specific state file. We use this when checking workspaces in a different directory. It reads the workspace from the given state path.

Example:

terraform workspace show -state=/path/to/terraform.tfstate

terraform validate -json

This flag prints the validation results in a machine-readable JSON format. We use this to integrate validation checks into scripts. It outputs success or errors in JSON.

Example:

terraform validate -json

terraform version -json

This flag prints the version information in JSON format. We use this for scripts that need to know the exact version number. It outputs the version data as a JSON object.

Example:

terraform version -json

terraform apply -backup

This flag specifies a path to save a backup of the state file before applying. We use this to keep a copy of the state prior to changes. It creates a backup file at the path.

Example:

terraform apply -backup=/path/to/backup

terraform apply -state

This flag specifies the path to the state file to read and write. We use this for local state management in non-standard locations. It uses the specified state file.

Example:

terraform apply -state=/path/to/terraform.tfstate

terraform destroy -backup

This flag specifies a path to save a backup of the state file before destroying. We use this to ensure we have a backup before deletion. It saves the state to the specified path.

Example:

terraform destroy -backup=/path/to/backup

terraform plan -input=false

This flag disables interactive prompts for input variables. We use this when running plans in automation. It runs without asking for missing variables.

Example:

terraform plan -input=false

terraform apply -input=false

This flag disables interactive prompts for input variables during the apply. We use this to ensure scripts do not hang waiting for user input. It proceeds without asking.

Example:

terraform apply -input=false

terraform plan -var

This flag passes a variable directly on the command line. We use this to set specific values without a var file. It sets the variable for the plan.

Example:

terraform plan -var="instance_size=t2.micro"

terraform apply -var

This flag passes a variable directly on the command line during apply. We use this to override values for a single run. It sets the variable for the apply.

Example:

terraform apply -var="instance_size=t2.micro"

terraform plan -var-file

This flag loads variable values from a specific file. We use this to apply a set of variables defined in a file. It reads the variables from the given path.

Example:

terraform plan -var-file="testing.tfvars"

terraform apply -var-file

This flag loads variable values from a specific file during apply. We use this to ensure the apply uses the same variables as the plan. It reads variables from the file.

Example:

terraform apply -var-file="testing.tfvars"

terraform destroy -var

This flag passes a variable to the destroy command. We use this if destroy requires specific variable values. It sets the variable for the destruction.

Example:

terraform destroy -var="force_destroy=true"

terraform destroy -var-file

This flag loads variables from a file for the destroy command. We use this to match the configuration context when destroying. It reads variables from the file.

Example:

terraform destroy -var-file="testing.tfvars"

Conclusion

So that’s it for this Terraform CLI command tutorial. I hope I explained everything in detail, along with clear and practical examples.

Just remember, in production environments, don’t just run any of these commands blindly. Always use the -out flag with terraform plan to save your execution plan to a file, and then provide that file to terraform apply. This ensures that the exact changes you reviewed are the ones being implemented, preventing “race conditions” where the infrastructure state might change between your plan and your apply. In the real world, predictability is your best friend. For more details, you can always visit the official Terraform documentation.

Also Read: What You Need to Know About Terraform Security

Aditya Gupta
Aditya Gupta
Articles: 487
Review Your Cart
0
Add Coupon Code
Subtotal