Refactor the Terraform Script — Restoring Balance
Source: Dev.to
Problem with Manual LocalStack Configuration
When using Terraform with LocalStack, many developers add a lot of provider settings that are only needed for the local environment, such as custom endpoints and flags like skip_credentials_validation. These settings increase maintenance overhead and make the Terraform code diverge from the configuration used in a real AWS environment.
Solution: Use the tflocal Wrapper
LocalStack provides a wrapper (tflocal) that lets you run Terraform against LocalStack without embedding LocalStack‑specific settings in your .tf files. By using tflocal, the Terraform configuration stays clean and mirrors real AWS usage.
Benefits
- Cleaner code – No need for conditional endpoints or validation flags.
- Easier maintenance – The same files work both locally and in production.
- Simplified workflow – LocalStack details are handled at runtime, not in the code.
Example Provider Configuration (No LocalStack Overrides)
provider "aws" {
profile = "localstack"
region = "us-east-1"
default_tags {
tags = {
Environment = "tutorial"
Project = "terraform-configure-providers"
}
}
}
Note: The
profileandregionvalues can be adjusted for your environment. No endpoint overrides orskip_*flags are required.
Running Terraform with tflocal
Initialize the working directory
tflocal init
Apply the configuration
tflocal apply
These commands automatically configure Terraform to communicate with LocalStack, keeping your .tf files free of environment‑specific tweaks.