Terraform Cheat Sheet: Terraform Command Guide

Terraform is an open-source infrastructure-as-code tool that users can use to define, provision, and manage cloud infrastructure using declarative configuration files. It supports multiple cloud providers, such as AWS, Cherry Servers, Azure, Google Cloud and more. In this regard, Terraform commands are highly important and enable users to efficiently initialize and apply resources. Knowing these commands improves workflow automation, reduces manual errors, and simplifies infrastructure deployment. This article is a guide to Terraform commands, which will provide you with a cheat sheet to manage your infrastructure effectively, with clear examples and explanations for common use cases.
#Getting started with Terraform
First, we'll explain the installation process and introduce the basic structure of Terraform configuration files.
#Installing Terraform
To get started with Terraform, the first step is to install it on your system. Terraform is compatible with Windows, macOS, and Linux.
-
Windows: Download the Terraform binary from the official Terraform website, extract it to a directory, and add the path to your system’s environment variables.
-
macOS: Use Homebrew by running brew install terraform in your terminal.
-
Linux: Download the appropriate package from the official website or use a package manager like apt or yum.
After installation, you can verify the installation by running terraform --version
in your terminal to display the installed version of Terraform.
#Terraform configuration files
Terraform configuration files, usually with a .tf extension, are used to describe the infrastructure you want to set up. These files are written in HashiCorp Configuration Language and are easy to read and understand.
A basic Terraform configuration file includes the following.
- Provider block: Specifies the cloud service provider.
- Resource block: Defines the infrastructure resources.
- Variables and outputs: Used for parameterizing configurations and displaying results.
This structure allows for clear and organized management of infrastructure as code.
#Terraform CLI commands overview
The Terraform Command Line Interface is a tool that helps manage and automate resources. It lets users interact with Terraform configurations, apply changes, and maintain the desired state of their infrastructure. The CLI is the primary interface for performing tasks such as initializing a working directory, validating configurations, and executing the creation or modification of infrastructure resources.
The Terraform CLI is highly important as it is very efficient and simple to use. Users can use it to run commands that easily create, update, and delete resources. terraform plan
and terraform apply
, for example, allow users to preview and execute changes, respectively. To guarantee consistency and lower human error, users may automate and repeat infrastructure setups with the Terraform CLI.
#Terraform initialization (terraform init)
The terraform init
command is the first step in working with Terraform. It initializes the Terraform working directory, downloads the necessary provider plugins, and sets up the backend for storing state files. This command is required to configure the working directory so Terraform can manage infrastructure effectively.
For example, when you start a new Terraform project, you would run terraform init
to initialize the working directory and download the required plugins. In cases of modifying the configuration or adding new providers, re-running the command ensures that all dependencies are updated. Some of the more common use cases are given below.
- Initializing a new project.
- Reinitializing a project after changing provider versions.
- Setting up a backend to store state remotely for team collaboration.
#Terraform validation (terraform validate)
The terraform validate
command checks the syntax and logical integrity of the Terraform configuration without making any changes to the infrastructure. It finds errors such as incorrect syntax, missing required arguments, or resource definitions that are incompatible with others. While terraform validate
does not access external resources or the state, it ensures the configuration is syntactically correct and logically sound.
If the configuration is valid and error-free, you will get the following output.
Success! The configuration is valid.
If a user mistakenly omits a required argument in a resource block or defines an invalid value, running terraform validate
will highlight the issue. This command is particularly useful in the early stages of development or during code reviews, as it helps catch configuration mistakes early, reduces the chances of errors during deployment, and makes infrastructure management easier.
#Terraform plan (terraform plan)
The terraform plan
commands preview the changes Terraform wants to make in the infrastructure as per the present configuration. An execution plan is developed by comparing the configuration files to the present state of the infrastructure and describes what resources will be added, updated, or destroyed. This allows users to review the changes before applying them and provides a clear understanding of the potential impact of the proposed modifications.
Here are some flags you can pass to the terraform plan
command to modify its behavior.
-out=<file>
: Saves the execution plan to a file, allowing for future application.-var and -var-file
: Used to pass variables and variable files for parameterized configurations.
Example use case: Before applying changes to a live environment, a user runs terraform plan
to review modifications such as adding new resources or updating existing ones. This step helps avoid unintended changes so that the infrastructure is managed safely and predictably.
#Terraform apply (terraform apply)
The terraform apply
command is used to execute the changes proposed by the terraform plan
command. It applies the infrastructure modifications, creating, updating, or destroying resources as defined in the configuration files. After running terraform plan
to preview the changes, terraform apply
makes the actual changes to reach the desired infrastructure state.
When running terraform apply
, Terraform will prompt user confirmation to approve the planned changes. Users can approve interactively by typing "yes" or automatically bypass this prompt by using the -auto-approve
flag.
Example: If you saved a plan with terraform plan -out=tfplan
, you can apply that specific plan using the following command.
terraform apply tfplan
This command applies only the changes specified in the saved plan and makes the infrastructure update controlled and predictable while reducing the risk of unwanted changes.
#Terraform refresh (terraform refresh)
The terraform refresh
command syncs the Terraform state file with the current state of the infrastructure resources. It updates the state by querying the provider for the present status of the resources and then comparing this information with the existing state file. If discrepancies are found, the state file will be updated to reflect the current infrastructure.
This command is particularly useful after external changes to the infrastructure, such as manual modifications or updates made directly through a cloud provider’s console, of which Terraform may not be aware.
For example, if a resource was modified outside of Terraform, running terraform refresh
ensures that Terraform has the most up-to-date state before applying further changes. It helps maintain consistency between the configuration files and actual infrastructure to prevent potential issues in future terraform apply
actions.
#Terraform state commands
Terraform state commands provide critical functionality for managing and interacting with the state file, which tracks the resources Terraform manages. These commands help you inspect, modify, and synchronize the state file, with Terraform correctly applying changes to the infrastructure.
-
State List (
terraform state list
): This command lists all the resources that Terraform tracks in the current state file. It is required to get an overview of all managed resources or identify a specific resource for further action. -
State Show (
terraform state show
): This command displays detailed information about a specific resource in the state file and includes its attributes and current values. It helps you inspect a resource’s state without applying any changes. -
State Pull/Push (
terraform state pull
,terraform state push
): These commands allow you to manually retrieve or upload the state file to and from a remote backend. They are helpful in scenarios where state synchronization with a backend is required but not done automatically. -
State RM (
terraform state rm
): This command removes a resource from the Terraform state file, without affecting the actual infrastructure. It’s used to stop managing a resource without deleting it. This can be useful when you want Terraform to forget about a resource while keeping it intact.
#Terraform destroy (terraform destroy)
The terraform destroy
command removes all Terraform-managed resources in the current configuration. The command reads the Terraform state and destroys the infrastructure by removing the resources specified in the configuration files. It is the final step in decommissioning infrastructure managed by Terraform.
Before applying the destruction, Terraform will prompt the user for confirmation that resources are intentionally being destroyed. Users can interactively bypass this confirmation by using the -auto-approve
flag, which will automatically approve the destruction without user input.
Below is an example with a confirmation flag.
terraform destroy -auto-approve
This command is useful when you need to clean up or decommission an entire infrastructure setup to ensure all resources are properly destroyed and no longer incur costs. It’s especially helpful in testing or temporary environments.
#Terraform output (terraform output)
The terraform output
command is used to offer the values of output variables defined in the Terraform configuration files. Output variables are used to share information across different parts of your infrastructure or to provide valuable data after the application of a configuration. This can include details such as the IP address of a provisioned instance or a generated URL.
Running terraform output
retrieves and displays the values of the defined output variables in the terminal. To export the information in JSON format for additional processing, you can also use the '-json' flag.
There are a few use cases for the terraform output command.
- Displaying the public IP of a provisioned server after running
terraform apply
. - Retrieving the URL of a deployed service or application.
- Using output values to pass information between Terraform modules or external systems.
#Terraform import (terraform import)
terraform import
is a command that imports existing infrastructure resources into the Terraform state file and brings them under Terraform management. This is especially helpful if you have resources that Terraform did not previously control or that you have manually developed outside of it. After importing, Terraform can track and manage those resources so you can modify or delete them through Terraform configurations.
To import a resource, enter the resource type, name, and ID. For example, use the following command to import a Cherry Servers server with ID 136254.
terraform import cherry_server.my_server 136254
This command imports the specified EC2 instance into the state file and makes it possible for Terraform to manage it like any other resource defined in the configuration.
#Terraform workspace (terraform workspace)
Terraform workspaces can manage multiple environments or configurations in one Terraform configuration. Each workspace will maintain its own state and will therefore allow you to separate and manage infrastructure for different environments like development, staging, and production without having to create separate Terraform configurations.
terraform workspace new
: This command creates a new workspace, which sets up a separate environment. For example, to create a "staging" workspace, you must run this command.
terraform workspace new staging
terraform workspace select
: This command allows you to switch between existing workspaces. For example, to switch to the "production" workspace, use the below command.
terraform workspace select production
terraform workspace show
: This command shows the current workspace you are working in and allows you to confirm which environment’s state file is active.
Workspaces help manage different configurations for various environments while maintaining a consistent workflow and reducing the risk of mixing configurations.
#Managing providers and modules
Providers and modules are key components in Terraform that support efficient infrastructure management by interacting with cloud platforms and promoting reusable, modular configurations.
#Providers
Providers are responsible for managing the lifecycle of infrastructure resources in Terraform. To add a provider, you configure it in the Terraform configuration file and specify details such as credentials and region. For example, a basic Cherry Servers provider configuration looks like this.
provider "cherryservers" {
auth_token = "your_api_token"
}
#Modules
Terraform modules are reusable, self-contained packages of Terraform configurations that can be shared across different projects. Modules help organize infrastructure code and make it easier to maintain and scale. You can use modules by referencing them in your main configuration file or create custom ones for common patterns. For example, to use a module to create a Cherry Servers instance, you can define the module in your Terraform configuration, as shown below.
module "cherry_server" {
source = "./modules/cherry_server"
server_plan = "vps-small"
image = "ubuntu-20.04"
project_id = "123456"
}
Modules promote best practices by reducing repetition and improving maintainability.
#Advanced Terraform commands
Now, we'll discuss some advanced Terraform commands that increase the functionality and management of your infrastructure. These commands provide interactive environments, collaboration features, and more powerful ways to manage and inspect your Terraform configurations.
#Terraform console (terraform console)
The terraform console
command opens an interactive console where users can evaluate expressions, inspect resource values, and experiment with Terraform configurations directly. It’s useful for debugging or testing how certain expressions or variables behave without applying them to the actual infrastructure. For example, you can query the values of output variables or perform calculations within the console.
#Terraform cloud and enterprise
Terraform Cloud and Terraform Enterprise are managed services that provide a collaborative platform for Terraform users. They offer advanced features such as remote state management, version control integration, team access management, and secure variable storage. These platforms help teams manage infrastructure at scale by centralizing Terraform operations and improving automation and governance. They are ideal for large organizations with complex infrastructure requirements. Terraform Enterprise includes additional features for on-premises installations, while Terraform Cloud is a cloud-based solution.
#Best practices for using Terraform CLI
To use the Terraform CLI effectively, following best practices is important for achieving consistency, security, and maintainability:
-
First, always version control your Terraform configuration files to track changes and collaborate efficiently. Use remote backends to store the state file securely and enable team collaboration.
-
Next, write modular, reusable code by using Terraform modules, which improves organization and reduces redundancy. Always run the
terraform plan
before applying changes to preview modifications and avoid unintended consequences. Additionally, use workspaces to manage different environments within the same configuration. -
For security, store sensitive data, such as API keys, in environment variables or secure vaults instead of hardcoding them in configuration files. Finally, regularly run
terraform validate
to catch syntax or configuration errors early in the development process. These practices improve efficiency and ensure safe and effective infrastructure management.
#Conclusion
Terraform is a tool that simplifies and automates the management of infrastructure using code. Its CLI commands help users efficiently initialize, validate, plan, apply, and destroy infrastructure configurations. Terraform’s ability to manage resources across multiple cloud providers, along with its use of workspaces, modules, and providers, makes it a good choice for all types of enterprise environments. Following best practices, such as using remote backends, modular configurations, and secure management of sensitive data, keeps Terraform effective for infrastructure automation. Understanding these key Terraform commands and concepts will help simplify your infrastructure management and lead to better, more manageable infrastructure deployment.
Cloud VPS Hosting
Starting at just $3.24 / month, get virtual servers with top-tier performance.