Prompt
How do I keep dev and prod infrastructure separate in code?
Latest observation
A good way to keep dev and prod infrastructure separate in code is to use shared modules/components for the common pieces, and environment-specific stacks/config for anything that differs.
Recommended approach
1) Use a layered structure
Organize code into:
- Reusable modules: VPC, database, app service, IAM, etc.
- Environment definitions:
dev,staging,prod - Shared configuration: tagging, naming, defaults
Example layout:
infra/
modules/
vpc/
app/
database/
envs/
dev/
main.tf
variables.tf
terraform.tfvars
prod/
main.tf
variables.tf
terraform.tfvars
2) Keep env-specific values in separate files
Do not hardcode environment differences in module code. Put them in:
- separate variable files
- separate config files
- separate parameter sets
Examples of values that usually differ:
- instance sizes
- replica counts
- autoscaling thresholds
- feature flags
- logging/monitoring levels
- DNS names
- secrets references
3) Use separate state for each environment
This is critical. Dev and prod should not share the same state.
For example:
devstate file / backend keyprodstate file / backend key
That prevents accidental cross-environment changes.
4) Use separate accounts/subscriptions/projects if possible
Best practice is:
- separate AWS accounts
- separate GCP projects
- separate Azure subscriptions
This gives you a real boundary beyond just code.
5) Use workspaces only if they fit your workflow
Terraform workspaces can separate environments, but many teams prefer:
- separate directories per environment, or
- separate state files/accounts
Workspaces are fine for simple cases, but they can become confusing for production-grade setups.
6) Parameterize modules
Your modules should accept inputs like:
environmentinstance_typedesired_countenable_debugdomain_name
Then the environment layer decides the values.
Example:
module "app" {
source = "../../modules/app"
environment = "dev"
instance_type = "t3.small"
desired_count = 1
}
and in prod:
module "app" {
source = "../../modules/app"
environment = "prod"
instance_type = "m6i.large"
desired_count = 3
}
7) Use validation and policy checks
Add safeguards like:
- naming conventions
- required tags
- policy-as-code
- approval gates for prod
- CI checks that prevent applying prod from a dev pipeline
8) Use separate CI/CD pipelines
Have:
- dev pipeline
- prod pipeline
Common pattern:
- dev auto-deploys on merge
- prod requires manual approval
9) Keep secrets separate
Use separate secret stores or secret namespaces per environment:
- dev secrets
- prod secrets
Never reuse prod secrets in dev.
10) Make prod harder to modify
For prod:
- stricter IAM
- fewer write permissions
- manual approvals
- drift detection
- more conservative change windows
Rule of thumb
Shared code, separate configuration, separate state, separate permissions.
If you want, I can show you a concrete example for:
- Terraform
- Pulumi
- AWS CDK
- Kubernetes/Helm