Terraform Cheat Sheet: Quick Reference Guide

blank
blank

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

CommandDescription
terraform initInitializes 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 listLists all available workspaces.
terraform workspace delete <name>Deletes a specific workspace.
terraform init -upgradeUpgrades modules and providers to the latest versions.
terraform init -backend-config=<file>Configures the backend during initialization.
terraform init -reconfigureReconfigures the backend without migrating state.
terraform init -migrate-stateMigrates the state to a new backend.

2. Planning and Applying Changes

CommandDescription
terraform planGenerates an execution plan, showing what changes will be made.
terraform applyApplies the changes required to reach the desired state.
terraform apply -auto-approveApplies changes without requiring manual approval.
terraform plan -out=<file>.tfplanSaves the execution plan to a file for later use.
terraform apply <file>.tfplanApplies changes using a saved execution plan.
terraform validateValidates the configuration files for syntax errors.
terraform fmtRewrites configuration files to a canonical format.
terraform plan -destroyGenerates a plan to destroy all resources.
terraform apply -refresh-onlyUpdates the state file without making changes to resources.
terraform plan -detailed-exitcodeReturns a detailed exit code when changes are detected.
terraform apply -parallelism=<n>Limits the number of concurrent operations during apply.

3. State Management Commands

CommandDescription
terraform state listLists 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 refreshUpdates the state file with real-world infrastructure.
terraform state pullPulls the current state from the remote backend.
terraform state push <file>Pushes a local state file to the remote backend.
terraform state replace-providerReplaces 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

CommandDescription
terraform destroyDestroys all resources managed by the current configuration.
terraform destroy -target=<resource>Destroys a specific resource.
terraform destroy -auto-approveDestroys resources without requiring manual approval.
terraform destroy -refresh=falseSkips refreshing the state before destroying resources.

5. Output and Input Variables

CommandDescription
terraform outputDisplays 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 -jsonOutputs the variables in JSON format.
terraform output -raw <variable>Outputs the value of a variable without additional formatting.
terraform output -no-colorDisables colorized output.

6. Module Management

CommandDescription
terraform getDownloads and updates modules in the working directory.
terraform init -upgradeUpgrades modules and providers to the latest versions.
terraform init -backend-config=<file>Configures the backend during initialization.
terraform get -updateUpdates all modules to the latest versions.

7. Importing Existing Resources

CommandDescription
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

CommandDescription
TF_LOG=DEBUG terraform applyEnables debug logging for detailed troubleshooting.
TF_LOG_PATH=<file>Saves logs to a specific file.
TF_LOG=TRACE terraform planEnables trace logging for even more detailed output.
TF_LOG_CORE=DEBUG terraform applyEnables debug logging for Terraform core.

9. Remote State Management

CommandDescription
terraform state pullPulls 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

CommandDescription
terraform providersDisplays information about the providers used in the configuration.
terraform providers lockLocks the provider versions to ensure consistency.
terraform providers mirror <path>Mirrors providers to a local directory for offline use.

11. Tainting and Untainting Resources

CommandDescription
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

CommandDescription
terraform graphGenerates a visual representation of the configuration or execution plan.
terraform graph | dot -Tpng > graph.pngCreates a PNG image of the dependency graph.
terraform graph -type=planGenerates a graph for the execution plan.

13. Output Filtering

CommandDescription
terraform output -jsonOutputs the variables in JSON format.
terraform output -raw <variable>Outputs the value of a variable without additional formatting.

14. Resource Targeting

CommandDescription
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

CommandDescription
terraform force-unlock <lock-id>Manually unlocks the state file if locking fails.

16. Importing Modules

CommandDescription
terraform import module.<name>.<resource> <id>Imports a resource into a module.

17. Managing Backends

CommandDescription
terraform init -reconfigureReconfigures the backend without migrating state.
terraform init -migrate-stateMigrates the state to a new backend.

18. Resource Targeting

CommandDescription
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

CommandDescription
terraform force-unlock <lock-id>Manually unlocks the state file if locking fails.

20. Importing Modules

CommandDescription
terraform import module.<name>.<resource> <id>Imports a resource into a module.

21. Managing Backends

CommandDescription
terraform init -reconfigureReconfigures the backend without migrating state.
terraform init -migrate-stateMigrates the state to a new backend.

Common Terraform Challenges and Solutions

ChallengeSolution
State file conflictsUse terraform state commands to manually resolve conflicts.
Provider version issuesPin provider versions in required_providers block.
Resource dependency errorsUse depends_on to explicitly define dependencies.
Debugging plan errorsEnable debug logging with TF_LOG=DEBUG.
Managing large configurationsBreak configurations into reusable modules.
Handling secrets securelyUse tools like HashiCorp Vault or environment variables.
Managing multiple environmentsUse Terraform workspaces or separate directories for each environment.
State locking issuesUse terraform force-unlock to resolve state lock conflicts.

FAQs About Terraform

What is the Difference Between 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.

How Do I Manage Secrets in Terraform?

Use tools like HashiCorp Vault or environment variables to manage secrets securely. Avoid hardcoding secrets in Terraform files.

Can I Use Terraform for Multi-Cloud Deployments?

Yes, Terraform supports multi-cloud deployments by allowing you to define resources for different cloud providers in the same configuration.

What is a Terraform Workspace?

A workspace is an isolated environment for managing different states of the same configuration, useful for managing multiple environments (e.g., dev, staging, prod).

How Do I Roll Back Changes in Terraform?

Use terraform state commands to manually adjust the state or revert to a previous state file stored in version control.

What is the Purpose of terraform refresh?

terraform refresh updates the state file to match the real-world infrastructure, ensuring the state is accurate.

How Do I Handle State Locking Issues?

Use terraform force-unlock <lock-id> to manually unlock the state file if locking fails.


Must-Know Terraform Tips

  1. Use Version Control: Store your Terraform configurations in version control systems like Git to track changes and collaborate effectively.
  2. Leverage Modules: Create reusable modules to simplify complex configurations and promote consistency.
  3. Enable Remote State: Use remote backends like S3 or Terraform Cloud to store state files securely and enable team collaboration.
  4. Validate Configurations: Use terraform validate to check for syntax errors before applying changes.
  5. Automate with CI/CD: Integrate Terraform into CI/CD pipelines to automate infrastructure provisioning and updates.
  6. Use Sentinel Policies: Implement policy-as-code with Sentinel to enforce governance and compliance.
  7. Monitor Drift: Regularly run terraform plan to detect and address configuration drift.
  8. Use Resource Targeting: Use -target to apply changes to specific resources during development and testing.
  9. Backup State Files: Regularly back up your state files to prevent data loss.
  10. 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! 🚀

Total
0
Shares
Leave a Reply

Your email address will not be published. Required fields are marked *

Previous Post
Kubernetes cheat sheet

Kubernetes Cheat Sheet: Essential Commands

Next Post
Git cheat sheet

Git Cheat Sheet: Essential Commands and Tips

Related Posts