Skip to main content
Terraform, despite its powerful infrastructure as code capabilities, has several common anti-patterns that can lead to maintainability issues, security risks, and operational problems. Here are the most important anti-patterns to avoid when writing Terraform code.
Hardcoding sensitive values like passwords, API keys, and tokens in your Terraform code is a security risk. Use variables marked as sensitive, environment variables, or secret management solutions like HashiCorp Vault.
Not using modules leads to code duplication and maintenance challenges. Use modules to encapsulate and reuse infrastructure patterns.
Storing state locally prevents collaboration and can lead to state file loss. Use remote state backends like AWS S3, Azure Storage, or Terraform Cloud for team environments.
Without state locking, multiple users can modify infrastructure simultaneously, leading to conflicts and corruption. Use state locking mechanisms like DynamoDB for AWS or Azure Blob Storage leases.
Using separate directories for environments leads to code duplication. Use Terraform workspaces or separate state files with shared modules for environment separation.
Hardcoding IDs of resources not managed by Terraform leads to brittle code. Use data sources to reference external resources dynamically.
Duplicating resource blocks for similar resources leads to maintenance issues. Use count or for_each to create multiple instances of a resource dynamically.
Not specifying version constraints can lead to unexpected behavior when provider versions change. Always specify version constraints for Terraform and providers.
Frequently using targeted applies can lead to state inconsistencies. Use targeted applies sparingly and prefer organizing resources into logical modules.
Not using output values makes it difficult to retrieve important resource attributes. Use outputs to expose important information for use in other configurations or for users.
Inconsistent formatting makes code harder to read and review. Use terraform fmt to automatically format your code according to the standard style.
Skipping validation can lead to errors during apply. Use terraform validate to check for syntax errors and other issues before running terraform plan or terraform apply.
Vague resource names make it difficult to understand the purpose of resources. Use descriptive names that indicate the resource’s purpose.
Not handling potential errors can lead to failed applies. Use conditional logic with count or for_each to handle potential errors.