Terraform is a powerful tool for managing infrastructure as code (IaC), enabling you to define, provision, and manage cloud resources efficiently. However, its extensive features and syntax can be overwhelming. Whether you’re provisioning a new environment, managing state, or troubleshooting issues, having a Terraform cheat sheet at your fingertips can save you time and effort.
This guide expands on the basics, providing detailed tables of commands, advanced tips, and FAQs to help you become a Terraform expert.
Essential Terraform Commands
1. Initialization and Workspace Commands
| Command | Description |
|---|---|
terraform init | Initializes a Terraform working directory, downloading providers and modules. |
terraform workspace new <name> | Creates a new workspace for managing multiple environments. |
terraform workspace select <name> | Switches to a different workspace. |
terraform workspace list | Lists all available workspaces. |
terraform workspace delete <name> | Deletes a specific workspace. |
terraform init -upgrade | Upgrades modules and providers to the latest versions. |
terraform init -backend-config=<file> | Configures the backend during initialization. |
terraform init -reconfigure | Reconfigures the backend without migrating state. |
terraform init -migrate-state | Migrates the state to a new backend. |
2. Planning and Applying Changes
| Command | Description |
|---|---|
terraform plan | Generates an execution plan, showing what changes will be made. |
terraform apply | Applies the changes required to reach the desired state. |
terraform apply -auto-approve | Applies changes without requiring manual approval. |
terraform plan -out=<file>.tfplan | Saves the execution plan to a file for later use. |
terraform apply <file>.tfplan | Applies changes using a saved execution plan. |
terraform validate | Validates the configuration files for syntax errors. |
terraform fmt | Rewrites configuration files to a canonical format. |
terraform plan -destroy | Generates a plan to destroy all resources. |
terraform apply -refresh-only | Updates the state file without making changes to resources. |
terraform plan -detailed-exitcode | Returns a detailed exit code when changes are detected. |
terraform apply -parallelism=<n> | Limits the number of concurrent operations during apply. |
3. State Management Commands
| Command | Description |
|---|---|
terraform state list | Lists all resources in the Terraform state. |
terraform state show <resource> | Displays detailed information about a specific resource. |
terraform state mv <src> <dest> | Moves a resource within the state file. |
terraform state rm <resource> | Removes a resource from the state file. |
terraform refresh | Updates the state file with real-world infrastructure. |
terraform state pull | Pulls the current state from the remote backend. |
terraform state push <file> | Pushes a local state file to the remote backend. |
terraform state replace-provider | Replaces the provider in the state file. |
terraform state list <address> | Lists resources matching a specific address. |
terraform state show <address> | Shows details of a resource at a specific address. |
4. Destroying Resources
| Command | Description |
|---|---|
terraform destroy | Destroys all resources managed by the current configuration. |
terraform destroy -target=<resource> | Destroys a specific resource. |
terraform destroy -auto-approve | Destroys resources without requiring manual approval. |
terraform destroy -refresh=false | Skips refreshing the state before destroying resources. |
5. Output and Input Variables
| Command | Description |
|---|---|
terraform output | Displays the values of output variables. |
terraform output <variable> | Displays the value of a specific output variable. |
terraform apply -var="key=value" | Sets an input variable during apply. |
terraform apply -var-file=<file> | Applies variables from a specific file. |
terraform output -json | Outputs the variables in JSON format. |
terraform output -raw <variable> | Outputs the value of a variable without additional formatting. |
terraform output -no-color | Disables colorized output. |
6. Module Management
| Command | Description |
|---|---|
terraform get | Downloads and updates modules in the working directory. |
terraform init -upgrade | Upgrades modules and providers to the latest versions. |
terraform init -backend-config=<file> | Configures the backend during initialization. |
terraform get -update | Updates all modules to the latest versions. |
7. Importing Existing Resources
| Command | Description |
|---|---|
terraform import <resource> <id> | Imports an existing resource into the Terraform state. |
terraform import module.<name>.<resource> <id> | Imports a resource into a module. |
8. Debugging and Logging
| Command | Description |
|---|---|
TF_LOG=DEBUG terraform apply | Enables debug logging for detailed troubleshooting. |
TF_LOG_PATH=<file> | Saves logs to a specific file. |
TF_LOG=TRACE terraform plan | Enables trace logging for even more detailed output. |
TF_LOG_CORE=DEBUG terraform apply | Enables debug logging for Terraform core. |
9. Remote State Management
| Command | Description |
|---|---|
terraform state pull | Pulls the current state from the remote backend. |
terraform state push <file> | Pushes a local state file to the remote backend. |
terraform force-unlock <lock-id> | Manually unlocks the state file if locking fails. |
10. Provider Management
| Command | Description |
|---|---|
terraform providers | Displays information about the providers used in the configuration. |
terraform providers lock | Locks the provider versions to ensure consistency. |
terraform providers mirror <path> | Mirrors providers to a local directory for offline use. |
11. Tainting and Untainting Resources
| Command | Description |
|---|---|
terraform taint <resource> | Marks a resource as tainted, forcing it to be recreated on the next apply. |
terraform untaint <resource> | Removes the taint from a resource. |
12. Graph Visualization
| Command | Description |
|---|---|
terraform graph | Generates a visual representation of the configuration or execution plan. |
terraform graph | dot -Tpng > graph.png | Creates a PNG image of the dependency graph. |
terraform graph -type=plan | Generates a graph for the execution plan. |
13. Output Filtering
| Command | Description |
|---|---|
terraform output -json | Outputs the variables in JSON format. |
terraform output -raw <variable> | Outputs the value of a variable without additional formatting. |
14. Resource Targeting
| Command | Description |
|---|---|
terraform plan -target=<resource> | Limits the plan to a specific resource. |
terraform apply -target=<resource> | Limits the apply to a specific resource. |
15. State Locking
| Command | Description |
|---|---|
terraform force-unlock <lock-id> | Manually unlocks the state file if locking fails. |
16. Importing Modules
| Command | Description |
|---|---|
terraform import module.<name>.<resource> <id> | Imports a resource into a module. |
17. Managing Backends
| Command | Description |
|---|---|
terraform init -reconfigure | Reconfigures the backend without migrating state. |
terraform init -migrate-state | Migrates the state to a new backend. |
18. Resource Targeting
| Command | Description |
|---|---|
terraform plan -target=<resource> | Limits the plan to a specific resource. |
terraform apply -target=<resource> | Limits the apply to a specific resource. |
19. State Locking
| Command | Description |
|---|---|
terraform force-unlock <lock-id> | Manually unlocks the state file if locking fails. |
20. Importing Modules
| Command | Description |
|---|---|
terraform import module.<name>.<resource> <id> | Imports a resource into a module. |
21. Managing Backends
| Command | Description |
|---|---|
terraform init -reconfigure | Reconfigures the backend without migrating state. |
terraform init -migrate-state | Migrates the state to a new backend. |
Common Terraform Challenges and Solutions
| Challenge | Solution |
|---|---|
| State file conflicts | Use terraform state commands to manually resolve conflicts. |
| Provider version issues | Pin provider versions in required_providers block. |
| Resource dependency errors | Use depends_on to explicitly define dependencies. |
| Debugging plan errors | Enable debug logging with TF_LOG=DEBUG. |
| Managing large configurations | Break configurations into reusable modules. |
| Handling secrets securely | Use tools like HashiCorp Vault or environment variables. |
| Managing multiple environments | Use Terraform workspaces or separate directories for each environment. |
| State locking issues | Use terraform force-unlock to resolve state lock conflicts. |
FAQs About Terraform
terraform plan and terraform apply? terraform plan generates an execution plan to show what changes will be made. terraform apply executes the plan and applies the changes to the infrastructure.
Use tools like HashiCorp Vault or environment variables to manage secrets securely. Avoid hardcoding secrets in Terraform files.
Yes, Terraform supports multi-cloud deployments by allowing you to define resources for different cloud providers in the same configuration.
A workspace is an isolated environment for managing different states of the same configuration, useful for managing multiple environments (e.g., dev, staging, prod).
Use terraform state commands to manually adjust the state or revert to a previous state file stored in version control.
terraform refresh? terraform refresh updates the state file to match the real-world infrastructure, ensuring the state is accurate.
Use terraform force-unlock <lock-id> to manually unlock the state file if locking fails.
Must-Know Terraform Tips
- Use Version Control: Store your Terraform configurations in version control systems like Git to track changes and collaborate effectively.
- Leverage Modules: Create reusable modules to simplify complex configurations and promote consistency.
- Enable Remote State: Use remote backends like S3 or Terraform Cloud to store state files securely and enable team collaboration.
- Validate Configurations: Use
terraform validateto check for syntax errors before applying changes. - Automate with CI/CD: Integrate Terraform into CI/CD pipelines to automate infrastructure provisioning and updates.
- Use Sentinel Policies: Implement policy-as-code with Sentinel to enforce governance and compliance.
- Monitor Drift: Regularly run
terraform planto detect and address configuration drift. - Use Resource Targeting: Use
-targetto apply changes to specific resources during development and testing. - Backup State Files: Regularly back up your state files to prevent data loss.
- Use Workspaces: Use workspaces to manage multiple environments (e.g., dev, staging, prod) within the same configuration.
This Terraform cheat sheet is your ultimate guide to mastering infrastructure as code. With detailed tables, advanced tips, and FAQs, you’ll be able to tackle any challenge with confidence. Bookmark this page for quick reference, and happy provisioning! 🚀