Advanced Terraform · Module 03
Environments, Import and Drift
Run the same code for dev, staging and prod with workspaces or separate folders, know which variable value wins, bring existing resources under management with import blocks, and catch drift with refresh-only plans, scheduled checks and check blocks.
What you will learn
- Compare CLI workspaces with one folder per environment and choose the right one
- Lay out environments that share modules and explain variable precedence
- Import existing resources with import blocks and generate their configuration
- Detect and handle drift with refresh-only plans, -detailed-exitcode, -replace and check blocks
Lessons
- Workspaces or One Folder per Environment
CLI workspaces keep several states for one configuration; separate folders give each environment its own code, backend and permissions. Most teams use folders for environments.
- Environment Layout and Variable Precedence
Keep logic in versioned modules, keep each environment a thin root folder with its own tfvars and backend, and know the order in which variable values override each other.
- Importing Existing Resources
import blocks bring objects created by hand under Terraform management through a normal plan and apply, and -generate-config-out writes a first draft of their configuration.
- Detecting and Handling Drift
Drift is any difference between real infrastructure and state; find it with refresh-only plans and scheduled -detailed-exitcode runs, decide whether to accept or revert it, and add check blocks for ongoing health.