DEV Community

Cover image for Terraform Tactics: A Guide to Mastering Terraform Commands for DevOps
Haytham Mostafa
Haytham Mostafa

Posted on • Edited on

Terraform Tactics: A Guide to Mastering Terraform Commands for DevOps

About Terraform

Terraform is an open-source IaC tool provided by by HashiCorp that enables users to define and provision infrastructure resources using a declarative configuration language. By defining infrastructure in code, Terraform automates the creation, modification, and deletion of resources across multiple cloud providers, data centers, and services. This approach enhances infrastructure scalability, repeatability, and consistency.

Why Terraform is Important

Terraform revolutionizes infrastructure management by offering several key advantages:

  • Scalability: Terraform facilitates the management of complex infrastructure setups through code, enabling scalability and efficient resource provisioning.
  • Consistency: Infrastructure configurations defined in Terraform ensure consistency across environments, reducing human error and enhancing reliability.
  • Collaboration: Teams can collaborate effectively by version-controlling Terraform configurations, enabling seamless infrastructure updates and tracking changes.
  • Flexibility: Terraform supports various cloud providers and services, allowing DevOps teams to work with diverse infrastructures using a unified tool.
  • Cost-Efficiency: By adopting Terraform, organizations can optimize resource usage, monitor costs, and automate resource lifecycle management.

Essential Terraform commands examples for Day-to-Day activities and deployments

Show version

  • terraform version

Description: Displays the currently installed version of Terraform and information about the Terraform installation.

Example:

terraform version
Enter fullscreen mode Exit fullscreen mode

Output:

Terraform v1.9.5
Enter fullscreen mode Exit fullscreen mode

Initialize Terraform configuration

The terraform init command is crucial for setting up a Terraform project. It downloads necessary plugins, initializes the backend, and ensures the project is ready for further Terraform operations.

  • terraform init

Description: Initializes a new or existing Terraform configuration. This command prepares the working directory for other Terraform commands by downloading and installing provider plugins.
Example:

terraform init
Enter fullscreen mode Exit fullscreen mode

Output:

Initializing the backend...

Initializing provider plugins...
- Checking for available provider plugins...
- Downloading plugin for provider "aws" (hashicorp/aws) 3.47.0...
- Downloading plugin for provider "null" (hashicorp/null) 3.1.0...
- Downloading plugin for provider "template" (hashicorp/template) 2.2.0...

Terraform has been successfully initialized!
Enter fullscreen mode Exit fullscreen mode
  • terraform init -migrate-state

Description: This command is used to migrate existing state files to a new state storage backend.

Example:

terraform init -migrate-state
Enter fullscreen mode Exit fullscreen mode

Output:

Migrating state...
Migration successful! State files have been moved to the new backend.
Enter fullscreen mode Exit fullscreen mode
  • terraform init -upgrade

Description: This command is used to upgrade the Terraform modules and plugins to the latest versions.

Example:

terraform init -upgrade
Enter fullscreen mode Exit fullscreen mode

Output:

Upgrading Terraform modules and plugins...
Upgrade successful! Modules and plugins are now up to date.
Enter fullscreen mode Exit fullscreen mode
  • terraform init -backend-config=backend.tf

Description: Initializes Terraform with backend configuration specified in a backend configuration file (e.g., backend.tf) allows you to specify backend configuration options during initialization, providing flexibility in how Terraform interacts with the backend for storing state data.

Example:

terraform init -backend-config=backend.tf
Enter fullscreen mode Exit fullscreen mode

Output:

Initializing Terraform with backend configuration from backend.tf...

Initializing the backend...
- Using backend configuration from backend.tf

Initializing provider plugins...
- Checking for available provider plugins...
- Downloading plugin for provider "aws" (hashicorp/aws) 3.47.0...
- Downloading plugin for provider "null" (hashicorp/null) 3.1.0...

Terraform has been successfully initialized with the specified backend configuration.
Enter fullscreen mode Exit fullscreen mode
  • terraform init -reconfigure

Description: This command is used to force reconfiguration of the backend, even if it's already configured.

Example:

terraform init -reconfigure
Enter fullscreen mode Exit fullscreen mode

Output:

Reconfiguring backend...
Backend reconfiguration successful! Ready for deployment.
Enter fullscreen mode Exit fullscreen mode

Manage workspaces

Managing workspaces in Terraform allows you to segregate your infrastructure configurations into different environments or stages, making it easier to maintain and manage your infrastructure deployments.

  • terraform workspace new

Description: Creates a new Terraform workspace.
Example:

terraform workspace new staging
Enter fullscreen mode Exit fullscreen mode

Output:

Created and switched to workspace "staging".
Enter fullscreen mode Exit fullscreen mode
  • terraform workspace list

Description: Lists all available workspaces.
Example:

terraform workspace list
Enter fullscreen mode Exit fullscreen mode

Output:

default
staging
production
Enter fullscreen mode Exit fullscreen mode
  • terraform workspace select

Description: Switches to a specific workspace.
Example:

terraform workspace select production
Enter fullscreen mode Exit fullscreen mode

Output:

Switched to workspace "production".
Enter fullscreen mode Exit fullscreen mode
  • terraform workspace show

Description: Displays the current workspace.
Example:

terraform workspace show
Enter fullscreen mode Exit fullscreen mode

Output:

Current workspace: production
Enter fullscreen mode Exit fullscreen mode
  • terraform workspace delete

Description: Deletes a specific workspace.
Example:

terraform workspace delete staging
Enter fullscreen mode Exit fullscreen mode

Output:

Deleted workspace "staging" and switched to "default" workspace.
Enter fullscreen mode Exit fullscreen mode

Plan Infrastructure/Resources Changes

When you provision infrastructure, Terraform creates an execution plan before it applies any changes to allow you to preview the changes Terraform will make to your infrastructure before you apply them.

  • terraform plan

Description: creates an execution plan, which lets you preview the changes that Terraform plans to make to your infrastructure.
Example:

terraform plan
Enter fullscreen mode Exit fullscreen mode

Output:

Refreshing Terraform state...
...
Plan: 3 to add, 0 to change, 0 to destroy.
Enter fullscreen mode Exit fullscreen mode
  • terraform plan -var-file="prod.tfvars"

Description: creates an execution plan using tfvars file, which lets you preview the changes that Terraform plans to make in specific environment (e.g. prod) to your infrastructure.
Example:

terraform plan -var-file="prod.tfvars"
Enter fullscreen mode Exit fullscreen mode

Output:

Refreshing Terraform state...
...
Plan: 15 to add, 3 to change, 5 to destroy.
Enter fullscreen mode Exit fullscreen mode
  • terraform plan -target="aws_instance.my_ec2"

Description: creates an execution plan using -target option to target specific resources, modules, or collections of resources.
Example:

terraform plan -target="aws_instance.my_ec2"
Enter fullscreen mode Exit fullscreen mode

Output:

Refreshing Terraform state...
...
Plan: 4 to add, 0 to change, 0 to destroy.
Enter fullscreen mode Exit fullscreen mode
  • terraform plan -target="aws_instance.my_ec2" -var-file="prod.tfvars"

Description: creates an execution plan to your infrastructure using -target option and tfvars file to target specific resources, modules, or collections of resources in specific environment (e.g. prod).
Example:

terraform plan -target="aws_instance.my_ec2" -var-file="prod.tfvars"
Enter fullscreen mode Exit fullscreen mode

Output:

Refreshing Terraform state...
...
Plan: 4 to add, 0 to change, 0 to destroy.
Enter fullscreen mode Exit fullscreen mode
  • terraform plan -out=tfplan

Description: save a plan with the -out flag. Later, you can apply the saved plan, and Terraform will only perform the changes listed in the plan. In an automated Terraform pipeline, applying a saved plan file ensures that Terraform only makes the changes you expect, even if your pipeline runs across multiple machines at different times.
Example:

terraform plan -out=tfplan
Enter fullscreen mode Exit fullscreen mode

Output:

Saving a plan to tfplan
Enter fullscreen mode Exit fullscreen mode

Apply Infrastructure/Resources Changes

When you apply changes to your infrastructure, Terraform uses the providers and modules installed during initialization to execute the steps stored in an execution plan.

  • terraform apply

Description: makes the changes defined by your plan to create or update resources.
Example:

terraform apply
Enter fullscreen mode Exit fullscreen mode

Output:

Refreshing Terraform state...
...
Plan: 10 to add, 2 to change, 0 to destroy.
Enter fullscreen mode Exit fullscreen mode
  • terraform apply tfplan

Description: Apply a specific plan file, by providing the plan file which generated using the terraform plan -out command.
Example:

terraform apply tfplan
Enter fullscreen mode Exit fullscreen mode

Output:

Refreshing Terraform state...
...
Apply complete! Resources: 7 added, 0 changed, 0 destroyed.
Enter fullscreen mode Exit fullscreen mode
  • terraform apply -var-file="prod.tfvars"

Description: Similar to the terraform plan -var-file="prod.tfvars" command except it will apply the configuration using the tfvars file.
Example:

terraform apply -var-file="prod.tfvars"
Enter fullscreen mode Exit fullscreen mode

Output:

Refreshing Terraform state...
...
Apply complete! Resources: 15 added, 3 changed, 5 destroyed.
Enter fullscreen mode Exit fullscreen mode
  • terraform apply -target="aws_instance.my_ec2"

Description: Similar to the terraform plan -target="aws_instance.my_ec2" command except it will apply changes to specific resources using Targeting.
Example:

terraform apply -target="aws_instance.my_ec2"
Enter fullscreen mode Exit fullscreen mode

Output:

Refreshing Terraform state...
...
Apply complete! Resources: 4 added, 0 changed, 0 destroyed.
Enter fullscreen mode Exit fullscreen mode
  • terraform apply -target="aws_instance.my_ec2" -var-file="prod.tfvars"

Description: Apply changes to specific resources using Targeting in specific environment (e.g. prod).
Example:

terraform apply -target="aws_instance.my_ec2" -var-file="prod.tfvars"
Enter fullscreen mode Exit fullscreen mode

Output:

Refreshing Terraform state...
...
Apply complete! Resources: 5 added, 0 changed, 0 destroyed.
Enter fullscreen mode Exit fullscreen mode

Destroy Infrastructure/Resources

Once you no longer need infrastructure, you may want to destroy it to reduce your security exposure and costs.

  • terraform destroy

Description: Terminates the infrastructure resources managed by your Terraform project.
Example:

terraform destroy
Enter fullscreen mode Exit fullscreen mode

Output:

...
Destroy complete! Resources: 3 destroyed.
Enter fullscreen mode Exit fullscreen mode
  • terraform destroy -target="aws_instance.my_ec2"

Description: Destroy only the targeted infrastructure resource.
Example:

terraform destroy -target="aws_instance.my_ec2"
Enter fullscreen mode Exit fullscreen mode

Output:

...
Destroy complete! Resources: 1 destroyed.
Enter fullscreen mode Exit fullscreen mode
  • terraform destroy -target="aws_instance.my_ec2" -var-file="prod.tfvars"

Description: Destroy only the targeted infrastructure resource in specific environment (e.g. prod).
Example:

terraform destroy -target="aws_instance.my_ec2" -var-file="prod.tfvars"
Enter fullscreen mode Exit fullscreen mode

Output:

...
Destroy complete! Resources: 1 destroyed.
Enter fullscreen mode Exit fullscreen mode

Taint/Untaint Resources

Terraform has a marker called "tainted" which it uses to track that an object might be damaged and so a future Terraform plan ought to replace it.

  • terraform taint aws_instance.my_ec2

Description: This command informs Terraform that a particular object has become degraded or damaged to be recreated on next apply.
Example:

terraform taint aws_instance.my_ec2
Enter fullscreen mode Exit fullscreen mode

Output:

Resource instance aws_instance.my_ec2 has been marked as tainted.
Enter fullscreen mode Exit fullscreen mode
  • terraform untaint aws_instance.my_ec2

Description: Remove taint from the tainted resource.
Example:

terraform untaint aws_instance.my_ec2
Enter fullscreen mode Exit fullscreen mode

Output:

Resource instance aws_instance.my_ec2 has been successfully untainted.
Enter fullscreen mode Exit fullscreen mode

Manage State File

Terraform must store state about your managed infrastructure and configuration. This state is used by Terraform to map real world resources to your configuration, keep track of metadata, and to improve performance for large infrastructures. This state is stored by default in a local file named "terraform.tfstate".

  • terraform state list

Description: This command is used to list resources within a State file.
Example:

terraform state list
Enter fullscreen mode Exit fullscreen mode

Output:

aws_instance.foo
aws_instance.bar[0]
aws_instance.bar[1]
module.elb.aws_elb.main
Enter fullscreen mode Exit fullscreen mode
  • terraform state list aws_instance.bar

Description: This command is used to filer by resource by only list resources for the given name.
Example:

terraform state list aws_instance.bar
Enter fullscreen mode Exit fullscreen mode

Output:

aws_instance.bar[0]
aws_instance.bar[1]
Enter fullscreen mode Exit fullscreen mode
  • terraform state pull > example.tfstate

Description: This command is used to manually download and output the state from remote state to a local file. This command also works with local state.
Example:

terraform state pull > example.tfstate
Enter fullscreen mode Exit fullscreen mode
  • terraform state push

Description: This command is used to manually upload a local state file to remote state. This command also works with local state. This command should rarely be used. It is meant only as a utility in case manual intervention is necessary with the remote state.
Example:

terraform state push
Enter fullscreen mode Exit fullscreen mode
  • terraform state rm aws_instance.bar

Description: Terraform will search the state for any instances matching the given resource address, and remove the record of each one so that Terraform will no longer be tracking the corresponding remote objects
Example:

terraform state rm aws_instance.bar
Enter fullscreen mode Exit fullscreen mode

Other Commands

  • terraform force-unlock <LOCK_ID>

Description: This will not modify your infrastructure. This command removes the lock on the state for the current configuration. The behavior of this lock is dependent on the backend being used. Local state files cannot be unlocked by another process.
Example:

terraform force-unlock <LOCK_ID>
Enter fullscreen mode Exit fullscreen mode

Output:

Lock ID LOCK_ID released
Enter fullscreen mode Exit fullscreen mode
  • terraform show -json

Description: This command will show a JSON representation of the plan, configuration, and current state.
Example:

terraform show -json
Enter fullscreen mode Exit fullscreen mode

Output:

{
  "aws_instance.example": {
    "type": "aws_instance",
    "depends_on": [],
    "primary": {
      "id": "i-1234567890abcdef0",
      "attributes": {
        "ami": "ami-0c55b159cbfafe1f0",
        "instance_type": "t2.micro",
        "tags": {
          "Name": "example-server"
        }
      }
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (8)

Collapse
 
venky_soma profile image
Venkatesh Soma

Nice write up! One more command which is quite useful terraform validate. Primarily helpful when you use terraform to deploy using CI/CD

Collapse
 
haythammostafa profile image
Haytham Mostafa

Nice catch, thank you for bringing to my attention. I will manage to add it.

Collapse
 
shivamsoni1995 profile image
ShivamSoni1995

Nice read!

Collapse
 
haythammostafa profile image
Haytham Mostafa

Thanks, I hope it will be helpful :)

Collapse
 
hectorlaris profile image
Héctor Serrano

Thank you, so useful!.

Collapse
 
haythammostafa profile image
Haytham Mostafa

My pleasure

Collapse
 
serhiyandryeyev profile image
Serhiy

Great!

Collapse
 
haythammostafa profile image
Haytham Mostafa

Thanks