Resource names must be unique globally, such as S3 buckets, across many environments and accounts. How do you generate them safely?
BeginnerScenarioResources Variables and Expressions
Answer
Situation read → Hardcoded names collide.
What I'd do →
- Build names from project, environment and account ID.
- Add a
random_idsuffix only where uniqueness can't be derived.
data "aws_caller_identity" "current" {}
resource "aws_s3_bucket" "logs" {
bucket = "${var.project}-${var.environment}-logs-${data.aws_caller_identity.current.account_id}"
}
Why → Derived names are predictable and discoverable, while random suffixes make things hard to find. Random values are stored in state, so they stay stable.
Interview tip → Use name_prefix for resources that must be replaced create-before-destroy.
More on Resources Variables and Expressions
You need three identical web servers. How do you declare them, and what is the catch with `count`?BeginnerYou manage subnets from a list of CIDRs. Someone removes the second CIDR and Terraform plans to recreate the third subnet. Why, and what do you change?IntermediateHow do you stop someone passing `environment = "production"` when only `dev`, `stage` and `prod` are valid?BeginnerA module takes a database password and exposes the connection string as an output. How do you stop them leaking into plan output?BeginnerA monitoring stack should only exist in prod. How do you create a resource conditionally?BeginnerYou have subnets defined as `{ web = {...}, db = {...} }` per VPC, nested two levels deep. How do you create them with `for_each`?Advanced