Use variables, data sources, and locals to assemble names, tags, and arguments dynamically so a single set of Terraform files can be reused across environments (dev/stage/prod), accounts, and regions.
- Reusability: One configuration can handle many environments.
- Maintainability: Update variable defaults or data lookups instead of editing every resource.
- Safety: Avoid accidental drift caused by manually changing literal values.
- Uniqueness: Build unique names (for S3, role names, etc.) programmatically.
-var/.tfvars files, or environment variables.


- The AMI is discovered via
data.aws_ami.ubuntu.idinstead of a literal AMI ID. - A
localholds the instance type so the value is defined once and reused. - Tags and names are assembled with interpolation to include variables, locals, and data source values.
${...} syntax to evaluate expressions and embed results into strings.
Simple interpolation examples
S3 bucket names must be globally unique across all AWS accounts. Include account IDs, environment prefixes (e.g.
dev, prod), or timestamps in bucket names to avoid naming collisions.- Use
localsfor values repeated across resources (instance types, common tags). - Use
datablocks for provider metadata (AMIs, regions, account IDs). - Prefer interpolation or the newer expression forms over hard-coded strings.
- Validate variable inputs with
validationblocks to prevent invalid configurations. - For global resources (S3), ensure deterministic uniqueness using account IDs, regions, timestamps, or hashes.
Practical next steps
- Practice by converting an existing static Terraform module into a dynamic one: replace literals with
var.*,local.*, anddata.*. - Create small lab folders for AWS, Azure, and GitHub:
- Add a README with instructions.
- Add starter Terraform files and exercises to modify interpolation and data lookups.
- Experiment with naming patterns to ensure uniqueness across accounts and regions.