Terraform General Command
Initialization & Setup​
- Initialize a Terraform project:
terraform init
- Reinitialize and upgrade providers:
terraform init -upgrade
- Validate the Terraform configuration:
terraform validate
- Format Terraform files:
terraform fmt
- Check the execution plan:
terraform plan
Applying & Destroying Resources​
- Apply changes to the infrastructure:
terraform apply
- Auto-approve an apply:
terraform apply -auto-approve
- Destroy resources:
terraform destroy
- Auto-approve a destroy:
terraform destroy -auto-approve
- Remove resources that were deleted outside Terraform:
terraform refresh
Resource & State Management​
- Show Terraform state:
terraform show
- Show state of a specific resource:
terraform state show <resource_type>.<resource_name>
- List all resources in state:
terraform state list
- Remove a resource from state (without deleting it in the cloud):
terraform state rm <resource_type>.<resource_name>
- Import an existing resource into Terraform state:
terraform import <resource_type>.<resource_name> <resource_id>
- Refresh terraform state to match real-world infrastructure:
terraform refresh
- Mark a resource for recreation:
terraform taint <resource_type>.<resource_name>
- Remove the taint from a resource:
terraform untaint <resource_type>.<resource_name>
Output & Variables Management​
- View Terraform outputs:
terraform output
- Get a specific output:
terraform output <output_name>
- Set environment variables for Terraform:
export TF_VAR_<variable_name>=<value>
- Use a
.tfvars
file:terraform apply -var-file="config.tfvars"
Debugging & Logging​
- Enable debugging logs:
export TF_LOG=DEBUG
- Enable logging to a file:
export TF_LOG_PATH="terraform.log"
Workspace Management​
- List all Terraform workspaces:
terraform workspace list
- Show the current workspace:
terraform workspace show
- Create a new workspace:
terraform workspace new <workspace_name>
- Switch to a different workspace:
terraform workspace select <workspace_name>
- Delete a workspace:
terraform workspace delete <workspace_name>
Remote State Management​
- Enable remote backend configuration:
terraform {
backend "s3" {
bucket = "my-tf-state-bucket"
key = "terraform.tfstate"
region = "us-east-1"
}
} - Pull latest remote state:
terraform state pull
- Push local state to remote backend:
terraform state push
Cleanup & Maintenance​
- Remove all generated files:
rm -rf .terraform/
- Remove the state file (use with caution!):
rm terraform.tfstate*