Terraform Tactics: A Guide to Mastering Terraform Commands for DevOps
Haytham Mostafa
Posted on September 8, 2024
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
Output:
Terraform v1.9.5
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
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!
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
Output:
Migrating state...
Migration successful! State files have been moved to the new backend.
terraform init -upgrade
Description: This command is used to upgrade the Terraform modules and plugins to the latest versions.
Example:
terraform init -upgrade
Output:
Upgrading Terraform modules and plugins...
Upgrade successful! Modules and plugins are now up to date.
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
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.
terraform init -reconfigure
Description: This command is used to force reconfiguration of the backend, even if it's already configured.
Example:
terraform init -reconfigure
Output:
Reconfiguring backend...
Backend reconfiguration successful! Ready for deployment.
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
Output:
Created and switched to workspace "staging".
terraform workspace list
Description: Lists all available workspaces.
Example:
terraform workspace list
Output:
default
staging
production
terraform workspace select
Description: Switches to a specific workspace.
Example:
terraform workspace select production
Output:
Switched to workspace "production".
terraform workspace show
Description: Displays the current workspace.
Example:
terraform workspace show
Output:
Current workspace: production
terraform workspace delete
Description: Deletes a specific workspace.
Example:
terraform workspace delete staging
Output:
Deleted workspace "staging" and switched to "default" workspace.
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
Output:
Refreshing Terraform state...
...
Plan: 3 to add, 0 to change, 0 to destroy.
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"
Output:
Refreshing Terraform state...
...
Plan: 15 to add, 3 to change, 5 to destroy.
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"
Output:
Refreshing Terraform state...
...
Plan: 4 to add, 0 to change, 0 to destroy.
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"
Output:
Refreshing Terraform state...
...
Plan: 4 to add, 0 to change, 0 to destroy.
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
Output:
Saving a plan to tfplan
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
Output:
Refreshing Terraform state...
...
Plan: 10 to add, 2 to change, 0 to destroy.
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
Output:
Refreshing Terraform state...
...
Apply complete! Resources: 7 added, 0 changed, 0 destroyed.
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"
Output:
Refreshing Terraform state...
...
Apply complete! Resources: 15 added, 3 changed, 5 destroyed.
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"
Output:
Refreshing Terraform state...
...
Apply complete! Resources: 4 added, 0 changed, 0 destroyed.
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"
Output:
Refreshing Terraform state...
...
Apply complete! Resources: 5 added, 0 changed, 0 destroyed.
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
Output:
...
Destroy complete! Resources: 3 destroyed.
terraform destroy -target="aws_instance.my_ec2"
Description: Destroy only the targeted infrastructure resource.
Example:
terraform destroy -target="aws_instance.my_ec2"
Output:
...
Destroy complete! Resources: 1 destroyed.
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"
Output:
...
Destroy complete! Resources: 1 destroyed.
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
Output:
Resource instance aws_instance.my_ec2 has been marked as tainted.
terraform untaint aws_instance.my_ec2
Description: Remove taint from the tainted resource.
Example:
terraform untaint aws_instance.my_ec2
Output:
Resource instance aws_instance.my_ec2 has been successfully untainted.
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
Output:
aws_instance.foo
aws_instance.bar[0]
aws_instance.bar[1]
module.elb.aws_elb.main
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
Output:
aws_instance.bar[0]
aws_instance.bar[1]
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
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
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
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>
Output:
Lock ID LOCK_ID released
terraform show -json
Description: This command will show a JSON representation of the plan, configuration, and current state.
Example:
terraform show -json
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"
}
}
}
}
}
Posted on September 8, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.