Scenario Questions
Real-world "what would you do" situations on Terraform and IaC, from first deploys to multi-account platforms
Workflow and Providers
๐ฅ Learn this hands-on with DevOps Shack โ YouTube @devopsshack ยท Hindi @shackverse ยท Courses at devopsshack.com
Q1 A new teammate is about to run Terraform for the first time against a shared dev account. Which commands do you walk them through, and in what order?
Beginner
Situation read โ Someone with no muscle memory for the workflow, a shared account, and a real chance of an accidental change.
What I'd do โ
terraform initto download providers and configure the backend.terraform fmt -recursiveandterraform validateto catch syntax problems early.terraform plan -out=tfplanand read every line of the diff.terraform apply tfplanso only the reviewed plan is applied.
Why โ Plan-then-apply with a saved plan guarantees what was reviewed is what runs, and the teammate learns that plan is free while apply is not.
Interview tip โ Say "apply a saved plan file", not just "run apply"; it signals you think about review and staleness.
Q2 Your manager asks why we bother with terraform plan when apply shows the same diff before asking for confirmation. What do you say?
Beginner
terraform plan when apply shows the same diff before asking for confirmation. What do you say?Situation read โ A fair question; interactive apply does print a plan, but it re-computes it at that moment.
What I'd do โ
- Run
terraform plan -out=tfplanin the PR pipeline and attach the human-readable output to the PR. - After approval, run
terraform apply tfplanwhich applies exactly that artifact.
Why โ A separate plan lets reviewers approve a concrete diff, and a saved plan fails if state changed in between (stale plan). Interactive apply re-plans, so the diff you approved could differ from what runs.
Interview tip โ Mention that plan files can contain secrets, so treat the artifact as sensitive.
Q3 Two engineers get different provider versions and see different plans for the same code. How do you stop this?
Beginner
Situation read โ Provider versions are floating and nobody is committing the dependency lock file.
What I'd do โ
- Declare constraints in
required_providers. - Commit
.terraform.lock.hclto Git. - Upgrade deliberately with
terraform init -upgradein a dedicated PR.
terraform {
required_version = ">= 1.9.0, < 2.0.0"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.80"
}
}
}Why โ Constraints define the allowed range; the lock file pins the exact version and its checksums, so every machine and CI run uses identical providers.
Interview tip โ "Constraint says what is allowed, lock file says what is used."
Q4 Someone committed the .terraform/ directory to the repo. What should be in version control and what should not?
Beginner
.terraform/ directory to the repo. What should be in version control and what should not?Situation read โ Classic repo hygiene problem; .terraform/ holds downloaded provider binaries and backend cache.
What I'd do โ
- Remove it from Git with
git rm -r --cached .terraform. - Add a
.gitignore. - Keep
.terraform.lock.hclcommitted.
.terraform/
*.tfstate
*.tfstate.*
crash.log
*.tfplan
override.tf
*.auto.tfvars # only if they hold secretsWhy โ Provider binaries are large and platform-specific, and state or plan files can contain secrets. The lock file is the one generated file that must be shared.
Interview tip โ If a state file was ever committed, treat every secret in it as leaked and rotate.
Q5 The same configuration must create a VPC in us-east-1 and a DR copy of a bucket in eu-west-1. How do you do it with one root module?
Intermediate
us-east-1 and a DR copy of a bucket in eu-west-1. How do you do it with one root module?Situation read โ One root module, two regions: that's the textbook use for provider aliases.
What I'd do โ
- Define a default provider and an aliased one.
- Point specific resources at the alias with
provider =.
provider "aws" {
region = "us-east-1"
}
provider "aws" {
alias = "dr"
region = "eu-west-1"
}
resource "aws_s3_bucket" "dr" {
provider = aws.dr
bucket = "acme-logs-dr"
}Why โ Each provider configuration is bound to one region/account; aliases let one run manage both without separate stacks.
Interview tip โ Mention that if modules need the alias, you pass it explicitly via the providers map.
Q6 You must deploy the same stack into 12 AWS accounts. How do you handle credentials and provider configuration?
Intermediate
Situation read โ Many accounts means one identity assuming a role per target account, not 12 sets of keys.
What I'd do โ
- Authenticate once (SSO or OIDC) into a tooling account.
- Configure
assume_rolein the provider, with the account ID as a variable. - Run one state per account (separate backend key or workspace per account), driven by a pipeline matrix.
provider "aws" {
region = var.region
assume_role {
role_arn = "arn:aws:iam::${var.account_id}:role/terraform-deploy"
session_name = "tf-${var.account_id}"
}
}Why โ Short-lived role sessions mean no long-lived keys, and per-account state keeps blast radius small.
Interview tip โ Avoid for_each over providers in one state; provider aliases can't be dynamic in standard Terraform, so use one state per account.
Q7 How do you make sure nobody runs your code with a Terraform version it wasn't tested against?
Beginner
Situation read โ Different CLI versions can rewrite state in incompatible ways.
What I'd do โ
- Set
required_versionin theterraformblock. - Pin the CLI in CI with
hashicorp/setup-terraformor a.terraform-versionfile fortfenv/mise.
terraform {
required_version = "~> 1.9.0"
}Why โ Once a newer Terraform writes state, older versions refuse to read it. Pinning avoids a surprise "state was created by a newer version" for the rest of the team.
Interview tip โ Upgrade the CLI as a deliberate change, one environment at a time.
Q8 Developers use macOS laptops while CI runs on Linux, and terraform init in CI complains about missing checksums. What's wrong?
Intermediate
terraform init in CI complains about missing checksums. What's wrong?Situation read โ The lock file only has hashes for the platform that generated it.
What I'd do โ
- Regenerate hashes for every platform in use.
- Commit the updated lock file.
terraform providers lock \
-platform=linux_amd64 -platform=linux_arm64 \
-platform=darwin_arm64 -platform=darwin_amd64Why โ init verifies downloaded provider archives against h1:/zh: hashes. A lock file generated on a Mac lacks the Linux archive hash, so verification fails or warns.
Interview tip โ Add this to the contributing guide so provider bumps always include all platforms.
Q9 The AWS provider has a new minor release you need. How do you upgrade without breaking production?
Intermediate
Situation read โ A provider upgrade can change defaults and cause diffs even with unchanged code.
What I'd do โ
- Read the provider CHANGELOG for the version range.
- Bump the constraint in a branch and run
terraform init -upgrade. - Run
terraform planin dev, then stage, expecting zero or understood diffs. - Merge the updated
.terraform.lock.hcland promote through environments.
Why โ The plan is the safety net: an upgrade that shows unexpected replacements is stopped before any apply.
Interview tip โ For a major version upgrade, do it alone in its own PR, never mixed with feature work.
Q10 Before tearing down a short-lived test environment, how do you see exactly what will be destroyed?
Beginner
Situation read โ Destroy is irreversible, so preview it.
What I'd do โ
terraform plan -destroy -out=destroy.tfplan- Review the list; check for shared or
prevent_destroyresources. terraform apply destroy.tfplan
Why โ terraform destroy is just a plan with destroy mode plus an apply. Running it as two steps gives a review point, and the same pattern works in CI.
Interview tip โ Never use -auto-approve on destroy against anything resembling production.
Q11 How would you design the plan/apply split in CI so the apply uses exactly what a reviewer approved?
Intermediate
Situation read โ Review must be tied to an immutable artifact.
What I'd do โ
- In the PR job:
terraform plan -out=tfplan, thenterraform show -no-color tfplanfor the PR comment andterraform show -json tfplan > plan.jsonfor policy checks. - Upload
tfplanas an encrypted artifact. - After approval, a gated job downloads it and runs
terraform apply tfplan.
Why โ The apply refuses a plan whose base state serial has changed ("Saved plan is stale"), so a drifted world fails safe instead of applying something nobody reviewed.
Interview tip โ Pin the same Terraform and provider versions in both jobs, since a plan file is version-specific.
Q12 A scheduled job should alert when infrastructure differs from code, without changing anything. What do you use?
Intermediate
Situation read โ You want a read-only drift check with machine-readable results.
What I'd do โ
- Run
terraform plan -detailed-exitcode -lock=false -input=falseon a schedule with a read-only role. - Exit code
0means no change,1means error,2means changes pending. - On
2, post the plan summary to Slack or open a ticket.
terraform plan -detailed-exitcode -input=false -lock=false
case $? in 2) echo "DRIFT";; 1) echo "ERROR"; exit 1;; esacWhy โ The exit code makes drift detection scriptable without parsing text.
Interview tip โ Note that pending code changes also produce exit 2, so run drift jobs against the main branch only.
Q13 You have dev, stage and prod using the same code but different sizes and counts. How do you feed per-environment values?
Beginner
Situation read โ Same code, different inputs.
What I'd do โ
- Keep one
variables.tfwith sensible defaults. - Create
envs/dev.tfvars,envs/stage.tfvars,envs/prod.tfvars. - Run with
terraform plan -var-file=envs/prod.tfvars, combined with a separate backend key per environment.
Why โ Values are data, not code; the code path is identical across environments, which is what makes promotion trustworthy.
Interview tip โ Pair the tfvars file with its own state, otherwise a -var-file mix-up can plan prod values into dev state.
Q14 The EKS cluster and the Kubernetes/Helm providers are in the same root module, and first apply fails with "connection refused" on localhost. How do you fix the design?
Advanced
Situation read โ Provider configuration depends on resource attributes that don't exist at plan time, so the Kubernetes provider falls back to defaults.
What I'd do โ
- Split into two stacks:
clustercreates EKS,cluster-addonsconfigures the Kubernetes/Helm providers from a data source. - In the second stack, read the cluster with
data "aws_eks_cluster"and use an exec-based token.
provider "kubernetes" {
host = data.aws_eks_cluster.this.endpoint
cluster_ca_certificate = base64decode(data.aws_eks_cluster.this.certificate_authority[0].data)
exec {
api_version = "client.authentication.k8s.io/v1beta1"
command = "aws"
args = ["eks", "get-token", "--cluster-name", var.cluster_name]
}
}Why โ Provider blocks are evaluated before resources are applied; splitting by lifecycle removes the chicken-and-egg.
Interview tip โ Mention that deleting the cluster and its in-cluster resources in the same state is the other reason to split.
Q15 How do you keep formatting and basic quality consistent across a team without arguing in code review?
Beginner
Situation read โ Style and trivial errors should be automated, not reviewed.
What I'd do โ
- Add
pre-commitwithterraform_fmt,terraform_validate,tflintandterraform_docshooks. - Repeat the same checks in CI as the enforcement point.
- Use
terraform fmt -check -recursiveas a failing CI step.
Why โ Local hooks give fast feedback; CI is the source of truth because hooks can be skipped.
Interview tip โ TFLint's AWS ruleset catches invalid instance types and deprecated syntax that validate can't.
Q16 A production network has no internet access. How do you make terraform init work?
Intermediate
terraform init work?Situation read โ Providers are downloaded from the registry by default, which an air-gapped runner can't reach.
What I'd do โ
- On a connected machine run
terraform providers mirror ./mirror. - Host that directory internally (filesystem or HTTPS network mirror).
- Point the CLI at it in
~/.terraformrc.
provider_installation {
filesystem_mirror {
path = "/opt/terraform/providers"
include = ["registry.terraform.io/*/*"]
}
}Why โ A mirror gives reproducible, offline installs, and also protects you from a registry outage or a withdrawn release.
Interview tip โ Mention that modules need a mirror too (internal Git or private registry), since terraform init fetches those separately.
Q17 CI runs terraform init for 30 stacks and downloads the 400 MB AWS provider every time. How do you speed it up?
Intermediate
terraform init for 30 stacks and downloads the 400 MB AWS provider every time. How do you speed it up?Situation read โ Repeated downloads waste time and bandwidth.
What I'd do โ
- Set
TF_PLUGIN_CACHE_DIRto a persistent directory on the runner. - Cache that directory between jobs (for example
actions/cachekeyed on the lock file hash).
export TF_PLUGIN_CACHE_DIR="$HOME/.terraform.d/plugin-cache"
mkdir -p "$TF_PLUGIN_CACHE_DIR"
terraform init -input=falseWhy โ Terraform symlinks cached provider binaries instead of redownloading, so 30 inits share one copy.
Interview tip โ The lock file still verifies checksums, so caching doesn't weaken integrity.
Q18 How should an engineer authenticate Terraform to AWS from a laptop? Someone suggests hardcoding keys in the provider block.
Intermediate
Situation read โ Hardcoded keys end up in Git and in state-adjacent files.
What I'd do โ
- Reject the hardcoded keys.
- Use AWS IAM Identity Center:
aws sso login --profile dev, thenexport AWS_PROFILE=dev. - Leave the provider block credential-free and let the default credential chain resolve identity.
provider "aws" {
region = "ap-south-1"
}Why โ Short-lived SSO credentials expire on their own and are tied to a person, which also helps CloudTrail attribution.
Interview tip โ Say "the provider block should contain no secrets, ever."
Q19 A plan on a 2,000-resource state takes 25 minutes. What do you look at?
Advanced
Situation read โ Time goes to refreshing every resource via cloud APIs, often throttled.
What I'd do โ
- Confirm with
TF_LOG=DEBUGor timing which provider calls dominate. - Short term:
terraform plan -refresh=falsefor quick local iteration, and raise-parallelismcarefully (default 10). - Medium term: split the state by lifecycle and ownership (network, data, apps).
- Check for API throttling and tune provider
max_retries.
Why โ Plan time is roughly linear in state size, so the structural fix is smaller states, not flags.
Interview tip โ -target is not a performance tool; it hides drift and leaves partial applies.
Q20 The pipeline fails with "Saved plan is stale" after approval. Why did it happen and is it a bug?
Advanced
Situation read โ Not a bug; it's the protection working.
What I'd do โ
- Check what changed state between plan and apply: another run, a manual
stateedit, or a refresh by a second pipeline. - Re-run the plan job on the current commit and get a new approval.
- Prevent recurrence with a CI concurrency group so only one run per stack executes.
concurrency:
group: tf-prod-network
cancel-in-progress: falseWhy โ A plan records the state serial and lineage it was built from. If state moved, applying it could undo someone else's change.
Interview tip โ Short gaps between plan and apply reduce this; long-lived approvals make it worse.
Q21 A resource needs a provider whose configuration comes from another resource's output in the same apply (for example a DB provider pointed at a new RDS endpoint). How do you handle it?
Advanced
Situation read โ Same chicken-and-egg as Kubernetes, but for a database or Vault provider.
What I'd do โ
- Separate the stacks: stack A creates the RDS instance and outputs the endpoint.
- Stack B reads it with
terraform_remote_stateor an SSM parameter and configures the provider. - For a one-off bootstrap, use two-phase apply with
-targetand document it as an exception.
Why โ Provider configuration must be known when the provider initializes. Unknown values at that moment produce errors or silently wrong defaults.
Interview tip โ "Providers configured from resource attributes are a code smell; split by lifecycle."
Q22 When is -target acceptable, and when is it a red flag?
Intermediate
-target acceptable, and when is it a red flag?Situation read โ An engineer wants to apply one resource to "save time".
What I'd do โ
- Allow it for recovery, such as fixing a broken dependency or getting past an error to unblock the graph.
- Follow every targeted apply with a full
terraform planthat must converge to no changes. - Refuse it as a routine workflow or in pipelines.
terraform apply -target=aws_iam_role.deploy
terraform plan # must be clean afterwardsWhy โ Terraform itself warns that targeting is for exceptional situations; it skips parts of the graph, so outputs and dependent resources can go stale.
Interview tip โ Offer the real fix for slow plans: smaller states.
Q23 You want to manage Datadog monitors with Terraform. How do you add a third-party provider correctly?
Beginner
Situation read โ Non-HashiCorp providers need an explicit source address.
What I'd do โ
- Declare it in
required_providerswith the namespace. - Configure credentials via environment variables.
- Run
terraform init.
terraform {
required_providers {
datadog = {
source = "DataDog/datadog"
version = "~> 3.0"
}
}
}
provider "datadog" {} # reads DD_API_KEY and DD_APP_KEYWhy โ Since 0.13, providers are namespaced (registry.terraform.io/DataDog/datadog); without a source, Terraform assumes hashicorp/.
Interview tip โ Mention keeping API keys in env vars or a secrets store, never in .tf files.
Q24 After enabling default_tags on the AWS provider, every plan shows tag changes on Auto Scaling groups or some resources. What do you do?
Advanced
default_tags on the AWS provider, every plan shows tag changes on Auto Scaling groups or some resources. What do you do?Situation read โ Some resources manage tags in a different way (inline tag blocks, or tags applied by another system), and default_tags overlaps with them.
What I'd do โ
- Look at the plan to see whether the diff is on
tagsortags_all. - For ASGs, use
tagblocks withpropagate_at_launchor exclude the key from defaults. - Use the provider's
ignore_tagsfor tags owned by other tooling.
provider "aws" {
default_tags { tags = { Team = "platform", ManagedBy = "terraform" } }
ignore_tags { key_prefixes = ["kubernetes.io/cluster/"] }
}Why โ Two writers of the same tag key produce a permanent diff; define one owner per key.
Interview tip โ Same-key conflict between default_tags and resource tags can cause errors; keep keys disjoint.
Q25 A new SaaS feature has no Terraform provider resource yet. What are your options?
Intermediate
Situation read โ Providers lag behind APIs; you still want it in code.
What I'd do โ
- Check whether the newer
awsccprovider (Cloud Control API) already supports it. - For AWS, wrap a CloudFormation template with
aws_cloudformation_stack. - As a last resort use
terraform_datawithlocal-execcalling the CLI/API, making it idempotent. - Open an issue or PR with the provider, and leave a TODO to migrate.
Why โ You keep the lifecycle and dependency graph in Terraform while waiting for first-class support.
Interview tip โ Explain that local-exec hacks don't track drift, so label them clearly.
Resources Variables and Expressions
๐ฅ Learn this hands-on with DevOps Shack โ YouTube @devopsshack ยท Hindi @shackverse ยท Courses at devopsshack.com
Q26 You need three identical web servers. How do you declare them, and what is the catch with count?
Beginner
count?Situation read โ Simple repetition, but index-based identity is fragile.
What I'd do โ
- Use
count = 3and reference instances asaws_instance.web[0]. - Prefer
for_eachif instances need individual identities.
resource "aws_instance" "web" {
count = 3
ami = data.aws_ami.al2023.id
instance_type = "t3.micro"
tags = { Name = "web-${count.index}" }
}Why โ With count, removing item 1 from a list shifts later indexes, so Terraform wants to destroy and recreate resources that didn't really change.
Interview tip โ "Count for N identical things, for_each for named things."
Q27 You 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?
Intermediate
Situation read โ count keyed by list index; the list shifted.
What I'd do โ
- Switch to
for_eachover a map keyed by a stable name. - Add
movedblocks to avoid recreating existing subnets.
variable "subnets" {
type = map(string) # { a = "10.0.1.0/24", b = "10.0.2.0/24" }
}
resource "aws_subnet" "this" {
for_each = var.subnets
vpc_id = aws_vpc.main.id
cidr_block = each.value
}Why โ Keys are identities. Removing key b only affects b.
Interview tip โ Choose keys that never change (names, not IPs).
Q28 How do you stop someone passing environment = "production" when only dev, stage and prod are valid?
Beginner
environment = "production" when only dev, stage and prod are valid?Situation read โ You want to fail early with a clear message.
What I'd do โ Add a validation block to the variable.
variable "environment" {
type = string
validation {
condition = contains(["dev", "stage", "prod"], var.environment)
error_message = "environment must be one of: dev, stage, prod."
}
}Why โ Validation runs at plan time before any API call, so bad input never reaches the cloud.
Interview tip โ Since Terraform 1.9, validation conditions can reference other variables and data sources, not just the variable itself.
Q29 A module takes a database password and exposes the connection string as an output. How do you stop them leaking into plan output?
Beginner
Situation read โ Values are printed in plan/apply logs by default.
What I'd do โ
- Mark the variable
sensitive = true. - Mark any output derived from it
sensitive = true(Terraform will require it). - Read it explicitly with
terraform output -raw db_urlwhen needed.
Why โ Sensitive values are redacted in the CLI output, but they are still stored in plain text in the state file. This is redaction, not encryption.
Interview tip โ Always follow up with "so state itself must be encrypted and access-controlled".
Q30 A monitoring stack should only exist in prod. How do you create a resource conditionally?
Beginner
Situation read โ On/off switch for a resource or module.
What I'd do โ
- Use
countwith a conditional. - Reference safely with
one()ortry().
resource "aws_cloudwatch_dashboard" "main" {
count = var.environment == "prod" ? 1 : 0
dashboard_name = "app"
dashboard_body = local.dashboard_json
}
output "dashboard_arn" {
value = one(aws_cloudwatch_dashboard.main[*].dashboard_arn)
}Why โ one() returns null for an empty list and the element for a single item, which avoids [0] index errors when count is 0.
Interview tip โ Prefer a boolean enable_x variable over environment-name checks inside modules.
Q31 You have subnets defined as { web = {...}, db = {...} } per VPC, nested two levels deep. How do you create them with for_each?
Advanced
{ web = {...}, db = {...} } per VPC, nested two levels deep. How do you create them with for_each?Situation read โ for_each needs a flat map, but data is nested.
What I'd do โ Flatten with a for expression and build composite keys.
locals {
subnet_list = flatten([
for vpc_name, vpc in var.vpcs : [
for sn_name, sn in vpc.subnets : {
key = "${vpc_name}/${sn_name}"
vpc = vpc_name
cidr = sn.cidr
}
]
])
subnet_map = { for s in local.subnet_list : s.key => s }
}
resource "aws_subnet" "this" {
for_each = local.subnet_map
vpc_id = aws_vpc.this[each.value.vpc].id
cidr_block = each.value.cidr
}Why โ Composite string keys are stable, human-readable in state (aws_subnet.this["prod/web"]), and make diffs predictable.
Interview tip โ Avoid keys that include values known only after apply.
Q32 A security group needs 15 ingress rules read from a variable. How do you avoid 15 copy-pasted blocks?
Intermediate
Situation read โ Repeated nested blocks: use dynamic.
What I'd do โ
resource "aws_security_group" "app" {
name = "app"
vpc_id = var.vpc_id
dynamic "ingress" {
for_each = var.ingress_rules # map(object({port=number, cidrs=list(string)}))
content {
description = ingress.key
from_port = ingress.value.port
to_port = ingress.value.port
protocol = "tcp"
cidr_blocks = ingress.value.cidrs
}
}
}Why โ dynamic generates blocks from a collection. For larger rule sets, I prefer separate aws_vpc_security_group_ingress_rule resources so rules have their own state addresses.
Interview tip โ Overusing dynamic hurts readability; use it only where the structure is genuinely variable.
Q33 A teammate puts everything in variables.tf, including values computed from other variables. What's the right place for computed values?
Beginner
variables.tf, including values computed from other variables. What's the right place for computed values?Situation read โ Confusion between inputs and internal values.
What I'd do โ Keep caller-supplied inputs in variable blocks and derived values in locals.
locals {
name_prefix = "${var.project}-${var.environment}"
common_tags = merge(var.tags, { Project = var.project })
}Why โ Variables form the module's public interface and can be overridden; locals are private, can't be set from outside, and remove repeated expressions.
Interview tip โ A new reader should learn the interface from variables.tf and outputs.tf alone.
Q34 Every resource needs a base set of tags plus its own. How do you combine them cleanly?
Beginner
Situation read โ Tag drift and inconsistent tagging.
What I'd do โ
- Use provider
default_tagsfor organisation-wide tags. - Use
merge()for resource-specific additions.
resource "aws_s3_bucket" "logs" {
bucket = "${local.name_prefix}-logs"
tags = merge(local.common_tags, { DataClass = "internal" })
}Why โ default_tags applies uniformly with no per-resource code; merge handles the cases that need extras. Later maps override earlier keys.
Interview tip โ Not every resource supports tags, so I validate coverage with a policy check rather than trusting convention.
Q35 A script needs the load balancer DNS name after apply. How do you expose it?
Beginner
Situation read โ Outputs are the interface between Terraform and the outside world.
What I'd do โ
output "alb_dns_name" {
value = aws_lb.main.dns_name
description = "Public DNS name of the ALB"
}terraform output -raw alb_dns_name
terraform output -json | jq .Why โ -raw prints a bare string suitable for shell use; -json is for structured data.
Interview tip โ Outputs from the root module are also what other stacks read through terraform_remote_state, so treat them as a contract.
Q36 A YAML file lists 40 IAM users with groups. How do you create users and memberships without hand-writing 40 blocks?
Intermediate
Situation read โ Data-driven infrastructure from a file.
What I'd do โ
locals {
users = yamldecode(file("${path.module}/users.yaml")) # list of {name, groups}
memberships = flatten([
for u in local.users : [for g in u.groups : { user = u.name, group = g }]
])
}
resource "aws_iam_user" "this" {
for_each = { for u in local.users : u.name => u }
name = each.key
}
resource "aws_iam_user_group_membership" "this" {
for_each = { for m in local.memberships : "${m.user}/${m.group}" => m }
user = aws_iam_user.this[each.value.user].name
groups = [each.value.group]
}Why โ Onboarding becomes a one-line YAML PR, reviewed and audited like code.
Interview tip โ Validate the YAML with a variable validation or precondition so typos fail early.
Q37 When should you add depends_on, and what can go wrong with it?
Advanced
depends_on, and what can go wrong with it?Situation read โ Terraform infers most dependencies from references; explicit ones are for hidden dependencies.
What I'd do โ
- Use it only when the dependency isn't visible in an attribute reference, such as an IAM policy that must exist before an instance starts.
- Avoid
depends_onon modules or data sources unless essential.
resource "aws_instance" "app" {
# ...
depends_on = [aws_iam_role_policy.app]
}Why โ depends_on on a data source defers its read to apply time, so values become unknown at plan time and downstream diffs get noisy. On modules it makes everything in the module wait.
Interview tip โ Prefer expressing the dependency through a real reference.
Q38 Every AMI refresh recreates the fleet, and you want a pinned and a "latest" option. How do you look up AMIs?
Beginner
Situation read โ A most_recent data source changes results over time.
What I'd do โ
- Use a data source with explicit filters, or an SSM public parameter.
- Offer an
ami_idvariable that overrides the lookup for prod.
data "aws_ssm_parameter" "al2023" {
name = "/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64"
}
resource "aws_instance" "app" {
ami = coalesce(var.ami_id, data.aws_ssm_parameter.al2023.value)
}Why โ Dev follows latest, prod is pinned and promoted explicitly, so an AMI release never surprises a production plan.
Interview tip โ Better still: bake AMIs with Packer and pass the ID in.
Q39 User data scripts are long inline strings. How do you manage them?
Beginner
Situation read โ Unreadable heredocs inside HCL.
What I'd do โ Move the script into a template file and render it.
resource "aws_instance" "app" {
user_data = templatefile("${path.module}/templates/boot.sh.tftpl", {
app_version = var.app_version
region = var.region
})
user_data_replace_on_change = true
}Why โ The script becomes lintable shell, and user_data_replace_on_change makes the change visible in the plan as a replacement.
Interview tip โ Escape literal ${ as $${ in template files.
Q40 A module input has many optional settings with defaults. How do you type it?
Intermediate
Situation read โ A flat list of 20 variables is painful; an untyped map is dangerous.
What I'd do โ Use an object with optional() attributes and defaults.
variable "database" {
type = object({
engine = string
instance_class = optional(string, "db.t4g.medium")
multi_az = optional(bool, false)
backup_days = optional(number, 7)
})
}Why โ Callers set only what differs, typos are rejected at plan, and defaults are visible in one place.
Interview tip โ optional() with a default has been stable since Terraform 1.3.
Q41 Replacing a database should be forced when a config file changes, but the file is not an attribute of the resource. How?
Intermediate
Situation read โ You need a trigger that doesn't map to a resource argument.
What I'd do โ
- Track the hash in a
terraform_dataresource. - Use
replace_triggered_byto link it to the target.
resource "terraform_data" "config_version" {
input = filesha256("${path.module}/app.conf")
}
resource "aws_instance" "app" {
ami = var.ami
instance_type = "t3.small"
lifecycle {
replace_triggered_by = [terraform_data.config_version]
}
}Why โ terraform_data is the built-in replacement for null_resource, and replace_triggered_by (1.2+) expresses the intent declaratively.
Interview tip โ Use it sparingly; every forced replacement is downtime for a stateful thing.
Q42 You need to split a /16 into subnets across 3 AZs without hand-computing CIDRs. What function do you use?
Beginner
Situation read โ Network math is error-prone by hand.
What I'd do โ
locals {
azs = slice(data.aws_availability_zones.available.names, 0, 3)
private_subnets = [for i, az in local.azs : cidrsubnet(var.vpc_cidr, 8, i)]
public_subnets = [for i, az in local.azs : cidrsubnet(var.vpc_cidr, 8, i + 100)]
}Test it first with terraform console: cidrsubnet("10.0.0.0/16", 8, 1) gives 10.0.1.0/24.
Why โ cidrsubnet(prefix, newbits, netnum) is deterministic, so subnets never overlap and never change between runs.
Interview tip โ Leave gaps in the numbering for future tiers.
Q43 Which value wins when a variable is set in several places?
Beginner
Situation read โ A teammate's -var is being silently overridden.
What I'd do โ Recall the order, lowest to highest precedence:
- Defaults in the variable block.
TF_VAR_nameenvironment variables.terraform.tfvars, thenterraform.tfvars.json.*.auto.tfvarsfiles in alphabetical order.-varand-var-fileon the command line, in the order given.
Why โ Later sources override earlier ones, and the CLI always wins. Knowing this explains "why isn't my tfvars value used?" in seconds.
Interview tip โ Check terraform console and var.name to see the resolved value.
Q44 A nested attribute may or may not exist, and lookup or index errors break the plan. How do you write resilient expressions?
Intermediate
lookup or index errors break the plan. How do you write resilient expressions?Situation read โ Optional data causes "Invalid index" or "attribute not found" errors.
What I'd do โ
- Use
try()for fallbacks,can()for validations,coalesce()for first non-null andlookup()for map keys. - Prefer typed optional object attributes over defensive expressions.
locals {
port = try(var.app.port, 8080)
log_days = lookup(var.retention, var.environment, 30)
region = coalesce(var.region_override, data.aws_region.current.name)
}Why โ These make intent explicit, but try() can mask real typos, so I limit it to genuinely optional values.
Interview tip โ If every line has try(), the variable's type is too loose.
Q45 Your AMI must be x86_64 and the plan should fail otherwise. How do you enforce that inside Terraform?
Intermediate
Situation read โ Catch wrong assumptions at plan/apply time rather than at boot.
What I'd do โ Add a precondition or postcondition.
data "aws_ami" "app" {
owners = ["self"]
filter {
name = "name"
values = ["app-*"]
}
most_recent = true
lifecycle {
postcondition {
condition = self.architecture == "x86_64"
error_message = "AMI ${self.id} is ${self.architecture}, expected x86_64."
}
}
}Why โ Conditions encode assumptions where the data is read, with a message that tells the operator exactly what is wrong.
Interview tip โ Contrast with check blocks (1.5+), which warn but don't block.
Q46 for_each fails because the map keys depend on a resource ID not known until apply. What's the fix?
Intermediate
for_each fails because the map keys depend on a resource ID not known until apply. What's the fix?Situation read โ for_each keys must be known at plan time.
What I'd do โ
- Key by static values such as names, not generated IDs.
- Put the unknown part in the value instead.
# bad: for_each = toset(aws_subnet.this[*].id)
# good: keys are static names, IDs are values
for_each = { for k, v in aws_subnet.this : k => v.id }Why โ Terraform has to know how many instances exist and their addresses before applying; values can be unknown, keys cannot.
Interview tip โ If you hit this, the root cause is usually using the wrong thing as the identity.
Q47 You need to prove an expression works before editing a large config. What do you use?
Beginner
Situation read โ You don't want to apply to learn what cidrsubnet or a for expression returns.
What I'd do โ Use terraform console.
$ terraform console
> cidrsubnet("10.0.0.0/16", 8, 3)
"10.0.3.0/24"
> { for k, v in var.subnets : k => upper(v) }
> exitWhy โ It evaluates expressions against your real variables and, with state, resource attributes, without changing anything.
Interview tip โ Pipe expressions in non-interactively: echo 'length(var.azs)' | terraform console.
Q48 Resource names must be unique globally, such as S3 buckets, across many environments and accounts. How do you generate them safely?
Beginner
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.
Q49 A list of resources was created with count, and now the team wants for_each with no downtime or recreation. How?
Advanced
count, and now the team wants for_each with no downtime or recreation. How?Situation read โ Changing the repetition mechanism changes state addresses from [0] to ["key"].
What I'd do โ
- Change the code to
for_each. - Declare a
movedblock for each old index. - Run
terraform planand confirm it shows moves, not destroy/create.
moved {
from = aws_instance.web[0]
to = aws_instance.web["api"]
}
moved {
from = aws_instance.web[1]
to = aws_instance.web["worker"]
}Why โ moved records the rename in code, so every environment performs the same state migration safely when it applies.
Interview tip โ terraform state mv does the same but is manual and unreviewable.
Q50 A reviewer asks why you use locals with for expressions instead of count and element(). How do you answer?
Intermediate
locals with for expressions instead of count and element(). How do you answer?Situation read โ A style discussion about readability and safety.
What I'd do โ
- Show the
forversion with named keys. - Compare with
element(var.list, count.index)patterns.
locals {
buckets = { for env in var.envs : env => "${var.project}-${env}" }
}
resource "aws_s3_bucket" "this" {
for_each = local.buckets
bucket = each.value
}Why โ for expressions are explicit and keyed, so changes are local and plans are readable. Index arithmetic hides intent and breaks when order changes.
Interview tip โ Prefer data shapes that match how people refer to things (names), not positions.
Modules and Code Structure
๐ฅ Learn this hands-on with DevOps Shack โ YouTube @devopsshack ยท Hindi @shackverse ยท Courses at devopsshack.com
Q51 When do you turn a block of resources into a module, and when do you leave it alone?
Beginner
Situation read โ Modules add indirection; they should earn their keep.
What I'd do โ
- Create a module when the same pattern is used in 2โ3 places, or when a team needs a safe, opinionated way to build something (VPC, ECS service, RDS).
- Keep one-off resources in the root module.
- Give the module a small, typed interface and meaningful outputs.
Why โ A module with 40 pass-through variables is just a worse version of the resource. A good module hides complexity and enforces standards.
Interview tip โ "A module should model a concept, not wrap a single resource."
Q52 How do you consume a community module like terraform-aws-modules/vpc/aws responsibly?
Beginner
terraform-aws-modules/vpc/aws responsibly?Situation read โ Public modules save weeks, but they are third-party code running with your credentials.
What I'd do โ
- Pin the version with a constraint.
- Read the module source and its resources before adopting.
- Review the plan on every version bump.
module "vpc" {
source = "terraform-aws-modules/vpc/aws"
version = "~> 5.0"
name = "prod"
cidr = "10.0.0.0/16"
}Why โ Unpinned modules change under you. Pinning plus plan review treats module upgrades like any other dependency.
Interview tip โ Many companies wrap popular modules in an internal one to enforce tags and encryption.
Q53 An ECS service module needs the VPC and subnets created by a network module. How do you wire them together?
Intermediate
Situation read โ Modules communicate through outputs and inputs, never by reaching inside.
What I'd do โ
module "network" {
source = "./modules/network"
cidr = "10.0.0.0/16"
}
module "service" {
source = "./modules/ecs-service"
vpc_id = module.network.vpc_id
subnet_ids = module.network.private_subnet_ids
}Why โ Passing module.network.* outputs creates an implicit dependency, so ordering is automatic, and each module stays testable on its own.
Interview tip โ If a module needs 10+ outputs from another, they probably belong together.
Q54 How would you lay out a repo that deploys the same stack to dev, stage and prod?
Intermediate
Situation read โ You need isolation between environments and shared logic.
What I'd do โ
- Put reusable code under
modules/. - Create
envs/dev,envs/stage,envs/prod, each a small root module that calls the shared modules with its own variables and backend key. - Version modules with Git tags so prod can lag dev.
modules/network modules/app modules/database
envs/dev/main.tf envs/dev/backend.tf envs/dev/terraform.tfvars
envs/prod/main.tf envs/prod/backend.tf envs/prod/terraform.tfvarsWhy โ Separate directories mean separate state and a prod apply can never be triggered by editing dev.
Interview tip โ I avoid workspaces for prod separation; directories make the target environment obvious.
Q55 How do you release a shared module so consumers can upgrade at their own pace?
Intermediate
Situation read โ Many stacks depend on one module, and a breaking change must not hit them all at once.
What I'd do โ
- Keep modules in their own repo (or path with tags) and release with SemVer tags:
v1.4.0. - Consumers pin:
source = "git::https://github.com/acme/tf-modules.git//vpc?ref=v1.4.0". - Maintain a CHANGELOG and flag breaking changes with a major bump and migration notes (and
movedblocks).
Why โ Pinned versions mean consumers upgrade when ready, and moved blocks shipped inside the module make renames painless.
Interview tip โ Branch references like ref=main are a production incident waiting to happen.
Q56 A module needs to deploy to a second region. Why does putting a provider block inside the module cause trouble?
Advanced
Situation read โ Provider blocks inside child modules make the module impossible to use with for_each/count and hard to remove.
What I'd do โ
- Remove provider blocks from the module.
- Declare the expected provider names with
configuration_aliases. - Pass providers from the root.
# in module
terraform {
required_providers {
aws = { source = "hashicorp/aws", configuration_aliases = [aws.replica] }
}
}
# in root
module "bucket" {
source = "./modules/replicated-bucket"
providers = { aws = aws, aws.replica = aws.dr }
}Why โ If you delete a module that contains its own provider, Terraform can't destroy its resources because the provider config vanished with it.
Interview tip โ "Providers belong in the root."
Q57 Teams complain a "VPC module" has 90 variables and still doesn't do what they need. How do you fix the design?
Intermediate
Situation read โ A God module that tries to cover every case.
What I'd do โ
- Split by concern: network core, NAT, endpoints, flow logs.
- Offer opinionated defaults and a few feature flags.
- Group optional settings in typed objects.
- Add
examples/showing the three common shapes.
Why โ Smaller modules compose; each has a small interface, and consumers swap parts without forking.
Interview tip โ If a module needs a count for every resource, it's trying to do too much.
Q58 You must refactor loose resources into a module in a live prod state without recreating anything. How?
Advanced
Situation read โ The resources already exist; only their addresses change.
What I'd do โ
- Create the module with the same resource definitions.
- Add
movedblocks from the root addresses tomodule.x.โฆ. - Run
terraform plan; it must show only "moved", no create/destroy. - Apply, and keep the
movedblocks for a release or two.
moved {
from = aws_security_group.app
to = module.app.aws_security_group.this
}Why โ moved is declarative, reviewable and applies the same way in every environment.
Interview tip โ Mention that plan output literally says "has moved to" for each, which is your proof.
Q59 Where should you document modules so people actually use them correctly?
Beginner
Situation read โ Undocumented modules get copied and forked.
What I'd do โ
- Add a README per module with purpose, an example call and inputs/outputs.
- Generate the tables with
terraform-docsvia pre-commit so they never go stale. - Include an
examples/basicdirectory that CI actually plans.
terraform-docs markdown table --output-file README.md --output-mode inject ./modules/vpcWhy โ Generated docs match the code; tested examples prove the README works.
Interview tip โ Also write descriptions on every variable and output.
Q60 Platform team wants each module tested before release. What's your approach?
Intermediate
Situation read โ Modules are shared dependencies and need a test gate.
What I'd do โ
- Static:
fmt,validate,tflint,checkovon every PR. - Plan-level tests with
terraform testusingcommand = planand mock providers. - Integration tests in a sandbox account for critical modules, applying and destroying.
- Run the examples folder in CI.
Why โ Cheap checks run on every commit; expensive real-cloud tests run before release.
Interview tip โ Mention cleanup: tag test resources and run a sweeper so failed runs don't leak cost.
Q61 A module should optionally create a KMS key, or use an existing one. How do you design that interface?
Advanced
Situation read โ "Create or bring your own" is a very common module requirement.
What I'd do โ
- Accept
kms_key_arn(nullable) as input. - Create the key only if it is null.
- Expose the effective ARN as a local.
variable "kms_key_arn" {
type = string
default = null
}
resource "aws_kms_key" "this" {
count = var.kms_key_arn == null ? 1 : 0
enable_key_rotation = true
}
locals {
kms_key_arn = coalesce(var.kms_key_arn, one(aws_kms_key.this[*].arn))
}Why โ The caller expresses intent with one optional value, and the rest of the module uses local.kms_key_arn with no branching.
Interview tip โ The condition must depend on a value known at plan time, not on another resource's ID.
Q62 A team wants to tweak a resource inside your module that you didn't expose. What are the options?
Intermediate
Situation read โ Pressure to fork or hack a shared module.
What I'd do โ
- Ask whether it's a legitimate, general need; if yes, add a variable and release a minor version.
- If it's team-specific, create the extra resource outside the module using the module's outputs.
- Do not use
override.tffiles or copy the module.
Why โ Forks drift away from upstream and miss fixes; extending through outputs keeps one source of truth.
Interview tip โ Good modules output IDs and ARNs of their key resources for exactly this reason.
Q63 Why should the AWS provider be configured in the root module and not in a reusable child module?
Beginner
Situation read โ A junior added provider "aws" with a hardcoded region inside a module.
What I'd do โ Remove it; let the module inherit the root's default provider, and declare only required_providers.
# module
terraform {
required_providers {
aws = { source = "hashicorp/aws", version = ">= 5.0" }
}
}Why โ Region and credentials are deployment decisions, not module decisions. Modules with embedded providers can't be removed cleanly and break reuse across regions.
Interview tip โ In modules, set minimum provider versions with >=; the root pins the exact range.
Q64 Compare Terragrunt with plain Terraform for a company with 30 stacks and 5 accounts.
Intermediate
Situation read โ The pain is repeated backend and provider boilerplate and ordering between stacks.
What I'd do โ
- Quantify what hurts today: copied
backend.tf,-var-filewrappers, dependency ordering. - If it's mostly boilerplate, Terraform plus a generated backend via
-backend-configand a small CI matrix is enough. - If dependency graphs across many stacks is the real pain, Terragrunt (
dependency,run-all) pays off.
Why โ Every extra tool is something to learn, upgrade and debug; adopt it for a measured problem.
Interview tip โ Neither is wrong; show the trade-off, not a preference.
Q65 A monorepo has 40 stacks. How do you structure layers and blast radius?
Advanced
Situation read โ One giant state means slow plans and a huge blast radius.
What I'd do โ
- Layer by change frequency and ownership:
foundation(accounts, IAM, DNS),network,data,platform(EKS),apps. - One state per layer per environment.
- Pass values downward through SSM parameters or remote state outputs.
- Gate each layer with CODEOWNERS and separate apply roles.
Why โ Slow-changing, high-impact layers get strict review; fast-changing app layers deploy often and can't break the network.
Interview tip โ Say how apps discover infrastructure: data sources and tags, not hardcoded IDs.
Q66 Stack B needs the VPC ID created by stack A. Do you use terraform_remote_state, SSM parameters or a data source?
Intermediate
terraform_remote_state, SSM parameters or a data source?Situation read โ Cross-stack data sharing, with different coupling levels.
What I'd do โ
- Prefer data sources (
aws_vpcby tag) when the thing is discoverable. - Use SSM parameters or Secrets Manager as an explicit published contract between teams.
- Use
terraform_remote_stateonly inside one team where read access to the whole state is acceptable.
Why โ terraform_remote_state exposes the entire state, including secrets, to the reader, and couples stacks to output names and the backend.
Interview tip โ "Publish what you intend to share; don't share the whole state."
Q67 Variables in a module have no defaults and callers keep forgetting some. How do you set required versus optional correctly?
Beginner
Situation read โ Interface hygiene.
What I'd do โ
- No default for values the caller must decide, such as
nameandvpc_id. - A safe default for everything else.
- Add
description,typeandvalidationto each.
Why โ A missing required variable fails fast with "No value for required variable", while a risky default silently deploys the wrong thing. Never default something like publicly_accessible to true.
Interview tip โ Secure defaults, explicit opt-in for risk.
Q68 You need one module instance per team, and adding or removing a team must not touch others.
Advanced
Situation read โ Repeated module instances keyed by a stable identity.
What I'd do โ Use for_each on the module call with team names as keys.
module "team_sandbox" {
source = "./modules/team-sandbox"
for_each = var.teams # map keyed by team name
name = each.key
budget = each.value.budget
}Why โ State addresses become module.team_sandbox["payments"]..., so removing one key destroys only that team's resources. Keys must be known at plan time.
Interview tip โ for_each on modules requires providers passed from the root, not defined inside.
Q69 Two modules require different version ranges of the same provider and init fails. What now?
Advanced
init fails. What now?Situation read โ Version constraints from all modules must intersect.
What I'd do โ
- Run
terraform providersto see which module requires what. - Update or fork the module with the overly strict constraint (
~> 4.0while others need>= 5). - In your own modules use
>=lower bounds and let the root set the ceiling.
Why โ Terraform installs one version per provider per root module, so module constraints must be compatible.
Interview tip โ Strict upper bounds in shared modules are the usual culprit.
Q70 How do you enforce encryption and tagging standards on every team's infrastructure?
Intermediate
Situation read โ Standards should be built in, not remembered.
What I'd do โ
- Publish golden modules (encrypted S3, tagged RDS) as the default way to build.
- Enforce with policy as code in CI (Checkov, OPA/Conftest, or Sentinel) on the plan JSON.
- Add org guardrails (SCPs, AWS Config rules) as the backstop for anything outside Terraform.
Why โ Modules make the right thing easy, policy makes the wrong thing hard, and SCPs catch the rest.
Interview tip โ Mention both shift-left and runtime controls.
Q71 Someone proposes depends_on = [module.network] on every other module "to be safe". Your take?
Beginner
depends_on = [module.network] on every other module "to be safe". Your take?Situation read โ Over-constraining the graph.
What I'd do โ
- Remove blanket
depends_on. - Pass real outputs (
module.network.vpc_id) so dependencies are implicit and precise. - Keep explicit
depends_ononly for hidden dependencies, with a comment explaining why.
Why โ Module-level depends_on makes every resource wait for every network resource, reduces parallelism and makes data sources inside defer to apply time.
Interview tip โ Use references for ordering; use depends_on as a documented exception.
Q72 You inherit a module nested five levels deep and nobody can follow it. What do you do?
Advanced
Situation read โ Over-abstraction.
What I'd do โ
- Map the real resources with
terraform state listandterraform graph. - Flatten to at most two levels: root calling modules calling resources.
- Use
movedblocks while collapsing wrappers so state stays untouched. - Verify with
terraform planshowing no changes.
Why โ Deep wrappers pass variables through layers without adding value, and every layer is another place for a bug.
Interview tip โ Refactor behind a no-diff plan; that's your safety net.
Q73 Where do you put provider-agnostic helper logic, such as naming and tagging conventions, shared by all stacks?
Intermediate
Situation read โ Naming logic is copy-pasted in every stack.
What I'd do โ Create a tiny "context" or "naming" module with no resources, just locals and outputs.
module "ctx" {
source = "git::https://github.com/acme/tf-modules.git//context?ref=v1.2.0"
project = "payments"
environment = var.environment
}
resource "aws_s3_bucket" "x" {
bucket = "${module.ctx.prefix}-reports"
tags = module.ctx.tags
}Why โ One definition of "how we name things" means a convention change is a single release.
Interview tip โ Keep it dumb and stable; it's imported everywhere.
Q74 A new engineer asks why modules have outputs.tf full of IDs they never use.
Beginner
outputs.tf full of IDs they never use.Situation read โ They see unused outputs as clutter.
What I'd do โ Explain that outputs are the public interface of the module.
- Other modules and stacks consume them (
module.vpc.vpc_id). - Outputs are the only way to reach values inside a child module.
- Keep them: removing one is a breaking change for consumers.
Why โ Child module internals are not accessible from the caller; outputs define what is supported.
Interview tip โ Output IDs and ARNs of key resources, with descriptions.
Q75 When would you choose one root module with many modules over many small root modules (stacks)?
Advanced
Situation read โ Granularity of state is the real decision.
What I'd do โ
- Single root when components are tightly coupled, deployed together and owned by one team.
- Separate roots when lifecycles, owners or blast radius differ, such as network vs app.
- Between roots, share through published outputs, not shared state files.
Why โ One state gives atomic changes but slow plans and a large blast radius; many states give independence but need orchestration and contracts.
Interview tip โ Frame it as lifecycle and ownership boundaries, not a file count.
State Backends and Workspaces
๐ฅ Learn this hands-on with DevOps Shack โ YouTube @devopsshack ยท Hindi @shackverse ยท Courses at devopsshack.com
Q76 Two engineers keep overwriting each other's changes because state is local. What's the fix?
Beginner
Situation read โ Local terraform.tfstate on laptops means each person has a different truth.
What I'd do โ
- Move state to a remote backend (S3, Azure Blob, GCS, or HCP Terraform).
- Enable locking so only one run mutates state at a time.
- Migrate with
terraform init -migrate-state.
Why โ Remote state gives a single source of truth, access control, versioning and locking.
Interview tip โ Say "state is shared, sensitive and must be locked".
Q77 Set up a production-grade S3 backend. What do you configure for locking?
Intermediate
Situation read โ S3 backend needs encryption, versioning and a lock mechanism.
What I'd do โ
terraform {
backend "s3" {
bucket = "acme-tfstate-prod"
key = "network/terraform.tfstate"
region = "ap-south-1"
encrypt = true
use_lockfile = true # native S3 locking, Terraform 1.10+
}
}Why โ use_lockfile writes a .tflock object next to the state using S3 conditional writes, so no DynamoDB table is needed. The older dynamodb_table argument still works on older versions but is deprecated.
Interview tip โ Mention both approaches and say which Terraform version you're on.
Q78 How do you harden the S3 bucket that holds Terraform state?
Intermediate
Situation read โ State holds secrets and is the keys to the kingdom.
What I'd do โ
- Turn on versioning so you can roll back a bad write.
- Enable default SSE-KMS encryption.
- Block all public access.
- Add a bucket policy that denies non-TLS requests and restricts access to the CI role and a break-glass role.
- Enable access logging or CloudTrail data events.
Why โ Versioning is your undo; IAM scoping and encryption protect the secrets inside.
Interview tip โ Put the bucket in a dedicated tooling account.
Q79 Who creates the state bucket itself, given Terraform needs it to exist before init?
Intermediate
init?Situation read โ Bootstrap problem.
What I'd do โ
- Create the bucket once with a tiny bootstrap stack that uses local state, or with the CLI.
- Then optionally migrate that stack's state into the new bucket.
- Keep the bootstrap code in Git with a README.
aws s3api create-bucket --bucket acme-tfstate-prod --region ap-south-1 \
--create-bucket-configuration LocationConstraint=ap-south-1
aws s3api put-bucket-versioning --bucket acme-tfstate-prod \
--versioning-configuration Status=EnabledWhy โ There's always one thing created outside the system; make it tiny, documented and rarely touched.
Interview tip โ Account vending pipelines usually create it automatically.
Q80 A laptop apply and a CI apply start at the same time. What stops state corruption?
Intermediate
Situation read โ Concurrent writers are the classic cause of state corruption.
What I'd do โ
- Rely on backend locking: the second run fails with "Error acquiring the state lock".
- Don't use
-lock=falsefor applies. - Restrict who can apply prod to the CI role only.
Why โ The lock holds an ID and owner info; the second run waits (-lock-timeout=5m) or fails instead of interleaving writes.
Interview tip โ The cleanest control is making CI the only identity allowed to write prod state.
Q81 When are Terraform workspaces appropriate?
Beginner
Situation read โ A teammate wants to use workspaces for dev/stage/prod.
What I'd do โ
- Use CLI workspaces for short-lived copies of the same stack, such as a feature-branch environment or PR preview.
- Use separate directories or backends for long-lived environments with different access rules.
terraform workspace new pr-421
terraform apply -var="name_suffix=pr-421"
terraform workspace select defaultWhy โ CLI workspaces share the same backend and code, so credentials and blast radius are shared, and it's easy to apply to the wrong one.
Interview tip โ HCP Terraform "workspaces" are a different thing: independent state, variables and permissions.
Q82 Compare directories, workspaces and branches for environment separation.
Intermediate
Situation read โ A design-review question.
What I'd do โ
- Directories per environment: explicit, separate state and backend, best for prod isolation, some duplication.
- CLI workspaces: minimal duplication, same backend and credentials, easy mistakes.
- Branch per environment: drift between branches and painful merges; avoid.
Why โ Production safety comes from separate credentials and state, and directories give you both.
Interview tip โ Recommend directories plus shared modules, with workspaces only for ephemeral copies.
Q83 Move from local state to S3 for an existing project without losing anything.
Intermediate
Situation read โ Existing resources, existing local state.
What I'd do โ
- Back up
terraform.tfstate. - Add the
backend "s3"block. - Run
terraform init -migrate-stateand answeryesto copy. - Run
terraform plan; it should be clean. - Delete the local state file after verifying the remote object.
Why โ -migrate-state copies state with its lineage and serial, so nothing is re-imported.
Interview tip โ Check the plan is empty before telling anyone it worked.
Q84 A giant state with 1,500 resources must be split into network and app states. How do you do it safely?
Advanced
Situation read โ You must move resources between states without destroying anything.
What I'd do โ
- Back up the state (
terraform state pull > backup.tfstate). - Write the new root module, with the same resource code.
- Use
terraform state mv -state-out=new.tfstate ...for each resource, orimportblocks in the new stack andremovedblocks in the old one. - Push the new state to the new backend and run
terraform planin both: both must be clean. - Do it in a maintenance window with locks held.
Why โ Each step is reversible via the backup, and clean plans prove the split is correct.
Interview tip โ Prefer import and removed blocks for reviewability; state mv is imperative.
Q85 How do you inspect what Terraform thinks it manages?
Beginner
Situation read โ You want to see what's in state.
What I'd do โ
terraform state list
terraform state show aws_instance.web
terraform show -json | jq '.values.root_module.resources[].address'
terraform state pull > snapshot.jsonWhy โ state list gives addresses, state show gives attributes, and pull writes the raw JSON for offline inspection.
Interview tip โ State is JSON but never edit it by hand; use state mv, rm or import.
Q86 You want Terraform to stop managing a resource but leave it running.
Beginner
Situation read โ Handing off ownership.
What I'd do โ
- Use a
removedblock (Terraform 1.7+) withdestroy = false, then delete the resource block. - Run
terraform apply.
removed {
from = aws_s3_bucket.legacy
lifecycle {
destroy = false
}
}Why โ It's declarative and shows up in review, versus terraform state rm aws_s3_bucket.legacy which is an unreviewed manual edit.
Interview tip โ Whichever you use, plan afterwards to confirm nothing will be destroyed.
Q87 The state file in S3 is deleted by mistake. How do you recover?
Advanced
Situation read โ Infrastructure is fine, Terraform has amnesia.
What I'd do โ
- With versioning on, restore the previous version: list with
aws s3api list-object-versions, then copy the last good version back. - Without versions, rebuild state with
importblocks for each resource, and check plan. - Don't run
applywith an empty state; it would try to create duplicates.
Why โ Versioning turns a disaster into a one-minute fix; without it, recovery is slow and error-prone.
Interview tip โ Add MFA delete or object lock for prod state buckets.
Q88 Give a pipeline in Account A access to state in a bucket in Account B.
Intermediate
Situation read โ Cross-account backend access.
What I'd do โ
- Create an IAM role in the state account with
s3:GetObject,PutObject,DeleteObject(for the lock file),ListBucketon the prefix. - Allow the pipeline role to assume it.
- Configure the backend with
assume_role.
backend "s3" {
bucket = "acme-tfstate"
key = "app/terraform.tfstate"
region = "ap-south-1"
assume_role = { role_arn = "arn:aws:iam::111111111111:role/tf-state-access" }
}Why โ The backend's identity is separate from the provider's, which keeps state access centralised and auditable.
Interview tip โ Scope the role to the key prefix per stack.
Q89 Security asks, "who can see our secrets in Terraform state?" What do you answer?
Advanced
Situation read โ State stores resource attributes in plain text, including DB passwords and private keys.
What I'd do โ
- Treat state read access as equal to secret access and restrict it to CI and a few admins.
- Encrypt at rest with KMS and enforce TLS in transit.
- Reduce secrets in state: RDS
manage_master_user_password, ephemeral values and write-only arguments on Terraform 1.10/1.11+, secrets fetched at runtime by apps. - Audit access with CloudTrail.
Why โ sensitive = true only hides values in CLI output; it never removes them from state.
Interview tip โ This question tests whether you know "sensitive" is redaction, not protection.
Q90 How do you rename a resource in code, from aws_instance.web to aws_instance.app, without replacement?
Beginner
aws_instance.web to aws_instance.app, without replacement?Situation read โ A rename without a state change looks like destroy plus create.
What I'd do โ Add a moved block next to the renamed resource.
moved {
from = aws_instance.web
to = aws_instance.app
}Plan should say aws_instance.web has moved to aws_instance.app.
Why โ The move is tracked in code, so every environment migrates identically on its next apply.
Interview tip โ terraform state mv achieves the same for one state but isn't reviewable.
Q91 What is terraform refresh and what replaced it?
Beginner
terraform refresh and what replaced it?Situation read โ An old doc says to run refresh before plan.
What I'd do โ
- Know that plan and apply already refresh state by default.
- Use
terraform plan -refresh-onlyto review drift andterraform apply -refresh-onlyto accept it into state. - Avoid the standalone
terraform refresh, which writes state without showing a diff.
Why โ Refresh-only mode adds a review step, whereas the bare command can silently write bad data into state, for example after a credentials mistake.
Interview tip โ "refresh-only mode is the safe version".
Q92 You have dev, stage and prod backends that differ only by bucket and key. How do you avoid copy-pasting backend.tf?
Intermediate
backend.tf?Situation read โ Backend blocks can't use variables.
What I'd do โ Use partial configuration: leave the backend block mostly empty and pass the rest at init.
terraform {
backend "s3" {}
}terraform init -reconfigure -backend-config=envs/prod.backend.hcl# envs/prod.backend.hcl
bucket = "acme-tfstate-prod"
key = "app/terraform.tfstate"
region = "ap-south-1"Why โ One code path, per-environment backend config files that are easy to review.
Interview tip โ Use -reconfigure when switching between environments locally, and watch for the wrong-file mistake.
Q93 A CI job crashed and the lock remains. When is force-unlock acceptable?
Advanced
force-unlock acceptable?Situation read โ A stale lock from a killed runner blocks everyone.
What I'd do โ
- Confirm via the lock info (ID, who, when) and CI that no run is active.
- Check the state isn't partially written: compare the latest S3 version and look at logs.
- Run
terraform force-unlock <LOCK_ID>. - Run
planto verify state and reality agree.
Why โ Unlocking while a real apply is running can corrupt state. Verify, then unlock, then re-plan.
Interview tip โ With use_lockfile, the lock is an S3 object, which you can also inspect and delete.
Q94 Many teams read each other's outputs via terraform_remote_state. What problems appear, and how do you fix them?
Intermediate
terraform_remote_state. What problems appear, and how do you fix them?Situation read โ Hidden coupling.
What I'd do โ
- List who reads what; ensure readers use a read-only role.
- Treat outputs as a versioned contract and don't rename without a deprecation window.
- Move high-value shared values to SSM or a service catalog, with explicit ownership.
Why โ Anyone with remote_state access can read the entire state, including secrets, and renames silently break downstream plans.
Interview tip โ Mention "contract" and "least privilege".
Q95 State is 40 MB and operations are slow. What do you do?
Intermediate
Situation read โ Large state means slow refresh, slow locking and a large blast radius.
What I'd do โ
- Identify heavy resource types with
terraform state list | cut -d. -f1-2 | sort | uniq -c | sort -rn. - Split by lifecycle into multiple states.
- Remove noisy resources such as thousands of IAM policy attachments from a hot path by moving them to their own stack.
- Use
-refresh=falseonly for local iteration.
Why โ Plan time scales with resource count; smaller states are faster and safer.
Interview tip โ Splitting is a design fix, flags are a patch.
Q96 How do you protect state for disaster recovery?
Advanced
Situation read โ State is a critical asset; regional loss shouldn't block recovery.
What I'd do โ
- Enable versioning, and optionally Object Lock for compliance.
- Replicate the bucket cross-region (CRR) to a DR bucket in a separate account.
- Practice a restore, including pointing
-backend-configat the DR bucket. - Keep bootstrap code and runbooks outside the same region and account.
Why โ Versioning covers mistakes, replication covers regional failure, and rehearsal proves it works.
Interview tip โ You can't fix prod with Terraform in an outage if the state bucket is in the failing region.
Q97 Should you use HCP Terraform or an S3 backend for state?
Beginner
Situation read โ A build-versus-buy decision for a small team.
What I'd do โ
- S3 (or GCS, Azure Blob): cheap, simple, and you own the pipeline.
- HCP Terraform: remote runs, state locking, RBAC, policy, private registry and SSO out of the box, at a per-resource price.
- Pick HCP if you'd otherwise build runs, approvals and policy yourself.
Why โ It's about operational effort and governance needs rather than technical capability.
Interview tip โ Also mention OpenTofu with an S3 backend as a licence-free path.
Q98 In HCP Terraform, how do you manage 40 workspaces that need the same AWS credentials and tags?
Intermediate
Situation read โ Repeated variables across workspaces.
What I'd do โ
- Create a variable set with the shared environment variables (preferably dynamic provider credentials via OIDC, not static keys).
- Apply the set to a project or to all workspaces.
- Keep workspace-specific values on the workspace.
Why โ One place to rotate or change, and no keys copied by hand.
Interview tip โ Dynamic credentials give per-run short-lived tokens.
Q99 Two repos accidentally manage the same S3 bucket. What happens, and how do you resolve it?
Advanced
Situation read โ Dual ownership: each state thinks it owns the resource, and they fight.
What I'd do โ
- Decide the owner, ideally the team that owns the lifecycle.
- In the other repo, add a
removedblock withdestroy = false(orstate rm) and apply. - Consumers of the bucket use a data source instead.
- Add CODEOWNERS or tagging (
ManagedBy,Stack) to make ownership visible.
Why โ Two states reconciling one resource produce perpetual diffs, and a destroy in either repo deletes it for both.
Interview tip โ Ownership should be answerable from a tag.
Q100 What is the difference between terraform state rm, removed and terraform destroy -target for getting a resource out of your config?
Beginner
terraform state rm, removed and terraform destroy -target for getting a resource out of your config?Situation read โ Three tools with very different outcomes.
What I'd do โ
state rmandremoved { destroy = false }: forget the resource; the real one stays.- Deleting the resource block normally: destroys the real one on next apply.
destroy -target: destroys now, outside normal flow; use only in recovery.
Why โ Pick by intent: forget, delete via code, or emergency delete.
Interview tip โ Prefer the code-based options so there's a commit trail.
Import Refactoring Drift and Lifecycle
๐ฅ Learn this hands-on with DevOps Shack โ YouTube @devopsshack ยท Hindi @shackverse ยท Courses at devopsshack.com
Q101 An S3 bucket was created by hand in the console and now must be managed by Terraform. How do you bring it in?
Beginner
Situation read โ Existing resource, no code, no state entry.
What I'd do โ
- Write the resource block that matches the bucket.
- Add an
importblock (Terraform 1.5+). - Run
terraform plan, adjust the code until the diff is empty, then apply.
import {
to = aws_s3_bucket.assets
id = "acme-assets-prod"
}
resource "aws_s3_bucket" "assets" {
bucket = "acme-assets-prod"
}Why โ Import blocks are reviewable and plannable, unlike the one-shot terraform import command.
Interview tip โ Import only writes state; you must write the code that matches.
Q102 You must adopt 200 existing resources and don't want to write all the HCL by hand.
Intermediate
Situation read โ Large brownfield adoption.
What I'd do โ
- List the resources by service and tag; script the
importblocks (ID discovery with the AWS CLI). - Run
terraform plan -generate-config-out=generated.tfto draft the HCL. - Clean the generated code: drop computed attributes, replace hardcoded IDs with references, extract variables.
- Iterate until
planshows no changes, then refactor into modules.
Why โ Generated config is a starting point and is often noisy; the empty plan is the acceptance test.
Interview tip โ Do it in small batches grouped by dependency, not all 200 at once.
Q103 How do you find out that someone changed infrastructure outside Terraform?
Beginner
Situation read โ Console hotfix; code and reality have diverged.
What I'd do โ
- Run
terraform plan; drifted attributes appear as changes to revert. - Use
terraform plan -refresh-onlyto see only drift with no code changes mixed in. - Automate a scheduled plan that alerts on exit code 2.
Why โ Refresh reads real attributes from the cloud API and compares with state and code.
Interview tip โ Drift detection is only useful if somebody owns the alert.
Q104 Someone opened port 22 on a security group in the console. Terraform wants to remove it. What's your process?
Intermediate
Situation read โ Revert or codify? Find out why it happened first.
What I'd do โ
- Ask who changed it and why; check CloudTrail (
AuthorizeSecurityGroupIngress). - If it was an unauthorised or temporary change, run
terraform applyto revert. - If it's a legitimate need, add it to code through a PR, then apply.
Why โ Terraform's job is to enforce the desired state, but humans decide what that state should be.
Interview tip โ Mention follow-up: restrict console write access so drift becomes rare.
Q105 An Auto Scaling group's desired capacity is changed by autoscaling, and Terraform keeps resetting it.
Intermediate
Situation read โ Another system legitimately owns this attribute.
What I'd do โ Tell Terraform to ignore it.
resource "aws_autoscaling_group" "web" {
min_size = 2
max_size = 20
desired_capacity = 2
lifecycle {
ignore_changes = [desired_capacity]
}
}Why โ ignore_changes removes that attribute from diff computation; the initial value is still set at creation.
Interview tip โ Use it for attributes owned by other controllers (HPA, ASG, image pipelines), not to hide mistakes.
Q106 How do you protect a production database from an accidental terraform destroy?
Beginner
terraform destroy?Situation read โ A plan that deletes the DB must fail loudly.
What I'd do โ
- Add
prevent_destroy = true. - Also set
deletion_protection = trueon the resource itself. - Enable final snapshots (
skip_final_snapshot = false).
resource "aws_db_instance" "main" {
deletion_protection = true
skip_final_snapshot = false
final_snapshot_identifier = "main-final"
lifecycle { prevent_destroy = true }
}Why โ prevent_destroy stops Terraform; deletion_protection stops the API even if someone bypasses Terraform.
Interview tip โ prevent_destroy only works while the block is in code; deleting the block deletes the protection.
Q107 A load balancer's TLS certificate must be rotated with no outage.
Intermediate
Situation read โ The default order is destroy then create, which would break the listener.
What I'd do โ Use create_before_destroy.
resource "aws_acm_certificate" "app" {
domain_name = "app.example.com"
validation_method = "DNS"
lifecycle { create_before_destroy = true }
}Why โ The new cert exists and is attached before the old one is removed, so the listener always has a valid certificate.
Interview tip โ create_before_destroy propagates to dependencies, and names must not collide.
Q108 Using create_before_destroy fails because the new resource's name conflicts with the old one.
Intermediate
create_before_destroy fails because the new resource's name conflicts with the old one.Situation read โ Both exist briefly and share a unique name.
What I'd do โ
- Use
name_prefixso Terraform generates a unique suffix. - Where the resource has no prefix option, include a changing component such as a random or version suffix.
resource "aws_security_group" "app" {
name_prefix = "app-"
vpc_id = var.vpc_id
lifecycle { create_before_destroy = true }
}Why โ Names must be unique while both versions coexist; a prefix makes that automatic.
Interview tip โ Applies to launch templates, security groups and IAM roles.
Q109 The plan says an RDS instance "must be replaced" after a small code change. What do you do before approving?
Advanced
Situation read โ Some attribute changes force replacement, which for a database means data loss.
What I'd do โ
- Find the line marked
# forces replacementin the plan. - Stop. Take a manual snapshot.
- Check whether the change can be made in place (
modifyvs recreate), such as a parameter group change orapply_immediately. - If replacement is unavoidable, restore from snapshot through
snapshot_identifieror plan a migration.
Why โ The plan tells you which attribute is immutable; the fix is a design change, not a flag.
Interview tip โ Recognising "forces replacement" in plans is a core skill.
Q110 A resource was deleted from the console. What does Terraform do on the next plan?
Beginner
Situation read โ State says it exists, the cloud says it doesn't.
What I'd do โ
- Run
terraform plan; refresh notices it's gone and plans to create it again. - If the deletion was intended, remove the code too.
- Otherwise apply to recreate.
Why โ Terraform drives toward the code; missing means "create".
Interview tip โ For data-bearing resources recreation does not restore data; use backups.
Q111 An instance is unhealthy and needs rebuilding. How do you force replacement of one resource?
Beginner
Situation read โ You want a recreate without changing code.
What I'd do โ
terraform apply -replace="aws_instance.web[1]"Why โ -replace supersedes the older terraform taint: it appears in the plan, so reviewers can see it, and nothing is left tainted in state if the run is cancelled.
Interview tip โ Prefer -replace to taint; the docs deprecate taint.
Q112 A new AMI release makes Terraform want to replace every EC2 instance in prod. How do you control this?
Intermediate
Situation read โ most_recent AMI lookups change the AMI attribute, which forces replacement.
What I'd do โ
- Pin the AMI ID per environment via a variable.
- Promote new AMIs through dev and stage first.
- For fleets, use a launch template plus an ASG with
instance_refreshso rollout is rolling instead of all-at-once.
Why โ You choose when a new image reaches prod, and rollouts replace instances gradually.
Interview tip โ ignore_changes = [ami] hides the problem; use it only where an external pipeline owns the AMI.
Q113 How do you roll out a new launch template to an ASG without downtime?
Intermediate
Situation read โ A launch template change doesn't touch running instances by default.
What I'd do โ Enable instance refresh and reference the latest template version.
resource "aws_autoscaling_group" "web" {
launch_template {
id = aws_launch_template.web.id
version = aws_launch_template.web.latest_version
}
instance_refresh {
strategy = "Rolling"
preferences {
min_healthy_percentage = 90
instance_warmup = 120
}
}
}Why โ Terraform detects the new version and the ASG replaces instances in batches while keeping capacity.
Interview tip โ Combine with health checks and a target group so bad AMIs are caught and the refresh stops.
Q114 Import 30 similar resources with different IDs.
Intermediate
Situation read โ Many imports of the same type.
What I'd do โ Use for_each in the import block (Terraform 1.7+).
locals {
buckets = { logs = "acme-logs", assets = "acme-assets" }
}
import {
for_each = local.buckets
to = aws_s3_bucket.this[each.key]
id = each.value
}
resource "aws_s3_bucket" "this" {
for_each = local.buckets
bucket = each.value
}Why โ One block replaces dozens, and the plan shows exactly what will be imported.
Interview tip โ Remove import blocks after the first successful apply, or leave them; they're no-ops once imported.
Q115 An IAM role with five policy attachments is imported, and the plan wants to change policies. What did you miss?
Advanced
Situation read โ Importing the role does not import its attachments or inline policies.
What I'd do โ
- Import each attachment separately (
aws_iam_role_policy_attachmentusesrole-name/policy-arn). - Use exclusive resources deliberately:
aws_iam_role_policy_attachments_exclusiveif Terraform should be the only manager. - Re-plan until clean.
Why โ In the AWS provider each attachment is its own resource; mixing inline managed_policy_arns and attachments produces fights.
Interview tip โ Know whether a resource is "authoritative" (manages the whole set) or "additive".
Q116 A CloudFormation stack owns resources that you want in Terraform. How do you migrate?
Intermediate
Situation read โ Two tools claim the same resources.
What I'd do โ
- Update the CFN template to set
DeletionPolicy: Retainon every resource and deploy it. - Import the resources into Terraform and get a clean plan.
- Delete the stack; resources stay because of Retain.
Why โ Retain makes stack deletion non-destructive, so ownership moves safely.
Interview tip โ Do it in order; deleting the stack first would delete the infrastructure.
Q117 How do you accept a harmless drift into state without changing infrastructure?
Beginner
Situation read โ The cloud changed an attribute you're happy with, such as a tag added by another system.
What I'd do โ
terraform plan -refresh-onlyto review what changed.terraform apply -refresh-onlyto record it in state.- Update the code to match so the next normal plan is clean.
Why โ Refresh-only changes state only, never infrastructure.
Interview tip โ Without step 3 the next plan will try to revert it.
Q118 You need to move a resource from one module call to another within the same state.
Intermediate
Situation read โ Address change across module boundaries.
What I'd do โ Use a moved block with full addresses.
moved {
from = module.old_app.aws_lb.this
to = module.new_app.aws_lb.this
}For moves between different states, moved doesn't work; use import in the target and removed { destroy = false } in the source.
Why โ moved only rewrites addresses in the same state. Cross-state moves require forgetting in one and importing in the other.
Interview tip โ Apply the import side first, then the removal, to avoid an unmanaged gap.
Q119 A teammate runs terraform state mv ad hoc in prod. What do you recommend instead?
Beginner
terraform state mv ad hoc in prod. What do you recommend instead?Situation read โ Imperative state surgery with no review.
What I'd do โ
- Replace it with a
movedblock committed in a PR. - Keep
state mvfor cross-state moves or emergencies, with a state backup first.
Why โ moved blocks apply the same migration in every environment and leave a history in Git.
Interview tip โ Always terraform state pull > backup.json before any manual state command.
Q120 How would you run drift detection across 80 workspaces?
Advanced
Situation read โ One-off checks don't scale.
What I'd do โ
- In HCP Terraform, enable health assessments (drift detection) on workspaces; or in CI run a nightly matrix of
plan -detailed-exitcode -refresh-onlywith a read-only role. - Aggregate results: Slack alerts for drift, tickets with an owner by workspace tag.
- Track a drift metric over time.
- Decide a policy: auto-revert for non-prod, ticket for prod.
Why โ The goal is mean time to detect drift, not just detection.
Interview tip โ Say who acts on the alert.
Q121 AWS adds its own tags to resources, producing constant tag diffs. What do you do?
Intermediate
Situation read โ Tags starting with aws: or added by services (for example aws:cloudformation:*) differ from your config.
What I'd do โ
- Check the plan for which keys differ.
- Use provider
ignore_tagswith key prefixes for system tags. - Or
lifecycle { ignore_changes = [tags["Owner"]] }for a specific key.
Why โ You exclude tags you don't own while still managing yours.
Interview tip โ Avoid blanket ignore_changes = [tags]; it stops managing your own tags too.
Q122 One change to a VPC output makes the plan replace 30 resources. How do you find out why, and reduce the damage?
Advanced
Situation read โ A cascading replacement through dependencies.
What I'd do โ
- Read the plan top-down: find the first resource marked
forces replacement. - Trace the attribute that forced it with
terraform graph | dot -Tsvg. - Revert or restructure: avoid changing immutable inputs, or use
create_before_destroy. - Do not apply until the root cause is understood.
Why โ Replacing a parent (subnet, VPC, role) forces replacement of everything that has it as an immutable argument.
Interview tip โ A blast-radius estimate in the PR description shows maturity.
Q123 When is ignore_changes = all appropriate?
Beginner
ignore_changes = all appropriate?Situation read โ A teammate wants it to silence a noisy plan.
What I'd do โ
- Refuse as a default; list the specific attributes instead.
- Accept it only for resources that are intentionally "create once, then someone else manages it", with a comment explaining who.
Why โ all turns Terraform off for that resource: drift, upgrades and security fixes never apply.
Interview tip โ If you need all, ask if Terraform should manage it at all.
Q124 How do you test a refactor so that you're sure nothing will be destroyed?
Intermediate
Situation read โ A refactor should have a no-op plan.
What I'd do โ
- Run
terraform plan -out=refactor.tfplanagainst a copy of production state or a staging replica. - Inspect with
terraform show -json refactor.tfplan | jq '.resource_changes[] | select(.change.actions != ["no-op"]) | .address'. - Gate the PR on that command printing only intended moves.
Why โ The plan is machine-readable truth about what will change.
Interview tip โ Moves show as no-op with previous_address set.
Q125 Resources are shared between two environments, such as a DNS zone. How do you avoid accidental deletion by either stack?
Advanced
Situation read โ Shared dependency owned by neither environment.
What I'd do โ
- Put shared resources in their own stack (
foundation/dns) with its own state and owner. - Environment stacks reference them with data sources.
- Add
prevent_destroyand service-level deletion protection where available.
Why โ Resources that outlive environments belong to a lifecycle of their own.
Interview tip โ "Lifecycle boundaries define state boundaries."
Secrets Provisioners and Policy as Code
๐ฅ Learn this hands-on with DevOps Shack โ YouTube @devopsshack ยท Hindi @shackverse ยท Courses at devopsshack.com
Q126 A developer hardcodes a DB password in terraform.tfvars and commits it. What do you do right now, and what's the long-term fix?
Beginner
terraform.tfvars and commits it. What do you do right now, and what's the long-term fix?Situation read โ A credential in Git history is compromised, even if you delete the file.
What I'd do โ
- Rotate the password immediately.
- Remove it from history (
git filter-repo) and scan withgitleaks. - Move the value to a secret manager and read at runtime, or use
manage_master_user_password = trueon RDS. - Add a pre-commit secret scanner and ignore
*.tfvarscontaining secrets.
Why โ Deleting a file doesn't remove it from history or forks; rotation is the only real fix.
Interview tip โ "Rotate first, clean later."
Q127 How do you avoid Terraform persisting a secret in state when creating a secret in AWS Secrets Manager?
Advanced
Situation read โ Normal resource attributes are always stored in state.
What I'd do โ
- On Terraform 1.10+, use ephemeral values and ephemeral resources for secrets that are only needed during the run.
- On 1.11+, use write-only arguments where the provider supports them (for example
secret_string_wowithsecret_string_wo_versiononaws_secretsmanager_secret_version). - Check the provider docs for support per resource, and fall back to creating the secret container in Terraform while an out-of-band process sets the value.
Why โ Write-only arguments are sent to the provider but never written to plan or state.
Interview tip โ Know the pattern, and know that support depends on provider version and resource.
Q128 Someone wants a remote-exec provisioner to configure servers after creation. What's your advice?
Beginner
remote-exec provisioner to configure servers after creation. What's your advice?Situation read โ Provisioners are a last resort.
What I'd do โ
- Prefer
user_data/cloud-init for first boot and baked AMIs (Packer) for software. - Use Ansible or SSM State Manager for configuration management.
- If you must use a provisioner, make it idempotent and set
on_failure.
Why โ Provisioners don't appear in plan, aren't tracked by state, need network access to the host and fail halfway, leaving tainted resources. HashiCorp documents them as a last resort.
Interview tip โ Know local-exec vs remote-exec and why neither is declarative.
Q129 You must run a one-off command after a resource is created, such as registering with an external system.
Intermediate
Situation read โ No provider support; a hook is needed.
What I'd do โ Use terraform_data with local-exec and triggers.
resource "terraform_data" "register" {
triggers_replace = [aws_instance.app.id]
provisioner "local-exec" {
command = "./scripts/register.sh ${aws_instance.app.private_ip}"
}
provisioner "local-exec" {
when = destroy
command = "./scripts/deregister.sh"
}
}Why โ triggers_replace re-runs it when the instance changes, and destroy-time provisioners handle cleanup. Destroy-time provisioners can only reference self, so pass values via triggers/input.
Interview tip โ Say you'd replace it with a proper provider if one exists.
Q130 How do you generate and manage the master password for a new RDS instance?
Intermediate
Situation read โ You don't want a human choosing or seeing the password.
What I'd do โ
- Prefer AWS-managed master credentials:
manage_master_user_password = truestores and rotates it in Secrets Manager. - Applications read it from Secrets Manager at runtime via IAM.
resource "aws_db_instance" "main" {
engine = "postgres"
username = "app_admin"
manage_master_user_password = true
}Why โ No password in code, tfvars or state, and rotation is automatic.
Interview tip โ The alternative random_password puts the value in state.
Q131 Compare Sentinel, OPA/Conftest and Checkov for policy as code.
Intermediate
Situation read โ You need guardrails before apply.
What I'd do โ
- Checkov/Trivy: static scanning of HCL with hundreds of built-in rules; fast adoption.
- OPA with Conftest: custom Rego policies evaluated against
terraform show -jsonplan output; vendor-neutral. - Sentinel: HashiCorp's policy language, integrated into HCP Terraform with enforcement levels.
- Pair a built-in scanner with custom OPA or Sentinel for company-specific rules.
Why โ Scanners cover generic best practice; plan-based policies can reason about final values and cost.
Interview tip โ Plan-based checks catch values that only exist after expression evaluation.
Q132 How do you prevent public S3 buckets from ever reaching production via Terraform?
Intermediate
Situation read โ Defence in depth.
What I'd do โ
- Module default:
aws_s3_bucket_public_access_blockwith all four flagstrue. - CI scan:
checkov -d . --framework terraformfails the PR on public ACLs. - Account-level S3 Block Public Access and an SCP as backstop.
Why โ If a resource slips through code review, the account control still blocks it.
Interview tip โ Layer the checks: module, pipeline, org.
Q133 Write a policy that denies any plan creating an unencrypted EBS volume.
Advanced
Situation read โ Custom rule on plan JSON.
What I'd do โ
terraform plan -out=tfplan
terraform show -json tfplan > plan.json
conftest test plan.json -p policy/package main
deny contains msg if {
rc := input.resource_changes[_]
rc.type == "aws_ebs_volume"
rc.change.actions[_] == "create"
not rc.change.after.encrypted
msg := sprintf("%s must set encrypted = true", [rc.address])
}Why โ The plan JSON contains the final computed values, so the policy sees what will actually be built.
Interview tip โ Rego deny contains msg if is the current v1 syntax.
Q134 Which checks belong in pre-commit, and which only in CI?
Beginner
Situation read โ Fast feedback locally, authority in CI.
What I'd do โ
- Pre-commit:
terraform fmt,terraform validate,tflint,terraform-docs, secret scanning. - CI: everything above plus
checkov/trivy config, plan, policy checks.
Why โ Developers skip slow hooks; CI can't be skipped.
Interview tip โ CI is the control, hooks are the convenience.
Q135 Design least-privilege IAM for a Terraform pipeline.
Advanced
Situation read โ Pipelines often run as AdministratorAccess.
What I'd do โ
- Two roles:
plan(read-only plus state read, lock write) andapply(write permissions scoped to the services in that stack). - PR pipelines assume
plan; only the protected main-branch job assumesapply. - Add permission boundaries and use IAM Access Analyzer's policy generation from CloudTrail to tighten.
- Restrict by trust policy to the exact repo and branch.
Why โ A compromised PR can run arbitrary code in plan, so plan must not be able to change anything.
Interview tip โ Mention that terraform plan runs provider and data source code from your PR.
Q136 Pipeline needs AWS access without storing access keys in GitHub.
Intermediate
Situation read โ Long-lived keys in CI secrets are a liability.
What I'd do โ
- Create an IAM OIDC identity provider for
token.actions.githubusercontent.com. - Create a role whose trust policy restricts
subtorepo:acme/infra:ref:refs/heads/main. - Use
aws-actions/configure-aws-credentialswithrole-to-assume.
permissions:
id-token: write
contents: read
steps:
- uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: arn:aws:iam::123456789012:role/gha-terraform-apply
aws-region: ap-south-1Why โ Tokens are short-lived and bound to repo and branch; nothing to leak or rotate.
Interview tip โ Always constrain the sub claim, or any repo could assume the role.
Q137 A secret leaked in a Terraform plan log in CI. What now?
Intermediate
Situation read โ Log retention makes it widely visible.
What I'd do โ
- Rotate the secret.
- Delete or restrict the log and artifacts.
- Find why it printed: missing
sensitive = true, alocal-execechoing it, orTF_LOG=DEBUG. - Add masking in CI and a check forbidding debug logs in shared runs.
Why โ Treat logs as a leak channel; sensitive marking and masking are the controls.
Interview tip โ Plan files and terraform show output can also contain secrets.
Q138 Compare using SOPS or Vault with plain Secrets Manager for providing secrets to Terraform.
Intermediate
Situation read โ Choose a source of truth for secrets.
What I'd do โ
- Secrets Manager or SSM Parameter Store: native, IAM-controlled, easiest on AWS.
- Vault: dynamic, short-lived credentials and a policy engine; more to operate.
- SOPS: encrypted files in Git, good for small teams but secrets still land in state.
Why โ The question is "where does the value live and who rotates it?"; Terraform should reference, not own, secret values where possible.
Interview tip โ Whichever is chosen, keep the secret value out of state when you can.
Q139 Why is sensitive = true not enough for a private key resource output?
Beginner
sensitive = true not enough for a private key resource output?Situation read โ A tls_private_key output is marked sensitive and the team feels safe.
What I'd do โ
- Explain that sensitive hides the value in CLI output only.
- Point out that
terraform output -jsonand the state file still hold it in plain text. - Generate keys outside Terraform where possible, or restrict state access and encrypt.
Why โ Redaction is a display feature, not a security boundary.
Interview tip โ Be specific: "state is plain JSON".
Q140 An application needs a secret at boot. A teammate puts it in user_data. Why is that wrong, and what's the alternative?
Intermediate
user_data. Why is that wrong, and what's the alternative?Situation read โ User data is readable from the instance metadata and visible in console and state.
What I'd do โ
- Remove the secret from user data.
- Give the instance an IAM role.
- Have the app or boot script fetch it from Secrets Manager or SSM Parameter Store at runtime.
- Enforce IMDSv2 with
metadata_options { http_tokens = "required" }.
Why โ Secrets stay out of code, state and metadata, and access is auditable and revocable.
Interview tip โ Mention rotation: runtime fetch makes it painless.
Q141 How do you stop engineers from bypassing policy checks in a pipeline?
Advanced
Situation read โ A policy check that can be skipped is a suggestion.
What I'd do โ
- Enforce policy in the system that applies (HCP Terraform policy sets with hard-mandatory enforcement), not in a script in the repo that PR authors can edit.
- Protect the workflow files with CODEOWNERS and branch protection; use required workflows.
- Remove direct apply credentials from humans.
- Log and review override requests (soft-mandatory).
Why โ If the PR author controls the check, they control the result.
Interview tip โ Know advisory, soft-mandatory and hard-mandatory.
Q142 How do you verify that third-party providers and modules haven't been tampered with?
Advanced
Situation read โ Supply-chain risk: providers run with your cloud credentials.
What I'd do โ
- Commit the lock file;
initverifies checksums, and the registry's signing keys are verified for HashiCorp-signed providers. - Pin module versions or Git commit SHAs rather than branches.
- Use an internal mirror and allowlist namespaces.
- Review upgrades with a plan and read release notes.
Why โ Pinned, verified, mirrored dependencies reduce what can change without review.
Interview tip โ Pin Git modules by tag or SHA, not by branch.
Q143 Terraform needs temporary admin-like credentials for AWS. How can Vault help?
Intermediate
Situation read โ Static keys are risky; dynamic ones expire.
What I'd do โ
- Configure Vault's AWS secrets engine with a role mapped to the needed policy.
- The pipeline authenticates to Vault (OIDC/JWT) and requests credentials.
- Export them as
AWS_*environment variables for the run; they expire in minutes.
Why โ There's no long-lived credential to steal; every run's access is logged in Vault.
Interview tip โ Mention that HCP Terraform dynamic credentials give the same pattern natively.
Q144 What do you keep as evidence for an auditor that policy was enforced on every production change?
Intermediate
Situation read โ Compliance wants proof, not promises.
What I'd do โ
- Retain plan JSON, policy results, approver identity and the commit SHA for each apply.
- Store them in an immutable bucket or HCP Terraform run history.
- Link to CloudTrail events from the apply role.
Why โ Plan, policy and approval together tell the full story of a change.
Interview tip โ Plan files contain secrets, so encrypt and restrict access.
Q145 Why should you replace null_resource with terraform_data?
Beginner
null_resource with terraform_data?Situation read โ Old modules use the null provider for hooks.
What I'd do โ
- Switch to the built-in
terraform_dataresource (Terraform 1.4+). - Use
triggers_replaceinstead oftriggers. - Migrate with a
movedblock where supported, or recreate since it has no real infrastructure.
Why โ It needs no extra provider download and can store input and output values.
Interview tip โ It's a small thing that shows you keep up with the language.
Q146 You must pass a Kubernetes auth token to a provider without writing it to state.
Advanced
Situation read โ Short-lived credentials shouldn't persist.
What I'd do โ
- Use the provider's
execplugin (as inaws eks get-token) so the token is fetched at run time and never stored. - On Terraform 1.10+, use ephemeral resources/values where the provider supports them.
Why โ Values obtained by exec or marked ephemeral aren't saved in plan or state files.
Interview tip โ Avoid data "aws_eks_cluster_auth" tokens for long runs; they expire after about 15 minutes.
Q147 A teammate wants a remote-exec over SSH through a bastion for every new instance. What do you suggest instead?
Intermediate
remote-exec over SSH through a bastion for every new instance. What do you suggest instead?Situation read โ SSH from Terraform couples infrastructure creation to network reachability and key handling.
What I'd do โ
- Bake the setup into an AMI with Packer, or use cloud-init.
- For ongoing config, use Ansible over SSM Session Manager, or SSM Run Command/Association.
- Close port 22 entirely.
Why โ No keys, no bastion, and the configuration is repeatable and testable outside Terraform.
Interview tip โ "Terraform provisions, configuration management configures."
Q148 Tagging compliance: how do you guarantee every resource has Owner and CostCenter?
Intermediate
Owner and CostCenter?Situation read โ Missing tags break cost allocation.
What I'd do โ
- Set
default_tagsin the provider, fed from required variables with validation. - A policy check on plan JSON verifying
tags_allcontains both keys. - AWS Config or tag policies at the org level as the backstop.
Why โ Provider defaults make it automatic; policy makes it enforced.
Interview tip โ Check tags_all, not tags, in policies.
Q149 How do you share a database password between a Terraform-created RDS and an app deployed by another tool?
Advanced
Situation read โ Both sides need the secret, neither should be hand-copied.
What I'd do โ
- Let RDS manage the master secret (
manage_master_user_password); output only the secret ARN. - Grant the app's IAM role
secretsmanager:GetSecretValueon that ARN. - The app reads at runtime (External Secrets Operator on Kubernetes works well).
Why โ The value never passes through Terraform outputs, pipelines or Git.
Interview tip โ Share ARNs and names, not values.
Q150 How do you review a PR that adds a local-exec provisioner?
Intermediate
local-exec provisioner?Situation read โ Arbitrary code runs on the CI runner with deployment credentials.
What I'd do โ
- Ask why no provider or data source can do it.
- Read the script: idempotent? quoting safe? no secret in command line (visible in process list and logs)?
- Check failure behaviour (
on_failure) and that destroy-time behaviour is handled. - Require a ticket to retire it when native support exists.
Why โ Provisioners run outside Terraform's model, so the review must cover the script as if it were production code.
Interview tip โ Mention injection risk if interpolating untrusted variables into commands.
Pipelines Terraform Cloud and OpenTofu
๐ฅ Learn this hands-on with DevOps Shack โ YouTube @devopsshack ยท Hindi @shackverse ยท Courses at devopsshack.com
Q151 Build a basic GitHub Actions pipeline: plan on pull request, apply on merge to main.
Beginner
Situation read โ The standard GitOps-for-infrastructure loop.
What I'd do โ
- Trigger
planonpull_request,applyonpushtomain. - Authenticate with OIDC, pin the Terraform version.
- Protect
mainand require the plan job to pass.
on:
pull_request:
push: { branches: [main] }
jobs:
terraform:
runs-on: ubuntu-latest
permissions: { id-token: write, contents: read, pull-requests: write }
steps:
- uses: actions/checkout@v4
- uses: hashicorp/setup-terraform@v3
with: { terraform_version: 1.9.8 }
- run: terraform init -input=false
- run: terraform fmt -check -recursive
- run: terraform plan -input=false -out=tfplan
- if: github.ref == 'refs/heads/main'
run: terraform apply -input=false tfplanWhy โ Code review gates every change, and merge is the only path to production.
Interview tip โ Mention approval environments and concurrency for prod.
Q152 Reviewers can't read raw plan logs. How do you present the plan in the PR?
Intermediate
Situation read โ Review quality drops when diffs are hard to find.
What I'd do โ
- Run
terraform show -no-color tfplanand post it as a PR comment (collapsed, truncated). - Add a short summary from
terraform show -json(counts of create/update/delete). - Use Atlantis, Spacelift, HCP Terraform or an action that updates one sticky comment per PR.
Why โ Reviewers approve what they can see; a destroy count in the summary is the number they care about.
Interview tip โ Redact sensitive values and avoid posting secrets in PR comments.
Q153 Two PRs merge close together and both apply to the same stack. What prevents trouble?
Intermediate
Situation read โ Concurrent applies to one state.
What I'd do โ
- Backend locking guarantees only one writer at a time.
- A CI concurrency group per stack serialises runs without cancelling an in-flight apply.
- Plans are re-created on the merged commit, so a stale PR plan is never applied.
Why โ Locking prevents corruption; serialisation prevents confusing failures.
Interview tip โ cancel-in-progress: false for applies. Cancelling an apply can leave partial state.
Q154 How do you add a manual approval before prod applies?
Intermediate
Situation read โ Prod changes need a human gate.
What I'd do โ
- Split the workflow:
planjob produces the artifact;applyjob targets a GitHubenvironment: production. - Configure that environment with required reviewers and a deployment branch rule.
- Apply the saved plan from the artifact.
apply:
needs: plan
environment: production
steps:
- uses: actions/download-artifact@v4
with: { name: tfplan }
- run: terraform apply -input=false tfplanWhy โ The approver sees the exact plan; the apply is bound to it.
Interview tip โ Same shape in GitLab with when: manual and protected environments.
Q155 Compare Atlantis, HCP Terraform and a hand-built GitHub Actions pipeline.
Intermediate
Situation read โ Choosing the tooling for a growing team.
What I'd do โ
- GitHub Actions or GitLab CI: flexible, free to start, but you build locking, comments, policy and drift detection yourself.
- Atlantis: self-hosted PR automation (
atlantis plan,atlantis apply) with locking per directory. - HCP Terraform: managed runs, state, RBAC, policy, drift detection and private registry.
Why โ The trade-off is build effort and control versus subscription cost.
Interview tip โ Say what you'd choose for a 5-person team and for a 200-person platform.
Q156 A saved plan was approved yesterday and apply fails because main changed. How do you avoid dead approvals?
Intermediate
Situation read โ Long gaps between plan and apply make stale plans likely.
What I'd do โ
- Plan on the merge commit in the apply pipeline, then approve and apply right after.
- Set an expiry on approvals and re-plan if older than N hours.
- Use merge queues so each change is planned against current main.
Why โ The shorter the plan-to-apply window, the less drift can intervene; the stale-plan check is the safety net, not the workflow.
Interview tip โ Distinguish "PR plan" (informational) from "apply plan" (binding).
Q157 Explain HCP Terraform workflows: VCS-driven, CLI-driven and API-driven.
Beginner
Situation read โ A teammate is new to HCP Terraform workspaces.
What I'd do โ
- VCS-driven: connect a repo; pushes trigger plans, merges trigger applies, PRs get speculative plans.
- CLI-driven:
terraform planruns remotely via thecloudblock, with state and runs in HCP. - API-driven: pipelines upload configuration versions and create runs via API for custom flows.
terraform {
cloud {
organization = "acme"
workspaces { name = "network-prod" }
}
}Why โ Pick by where you want the trigger: Git events, developers, or your own automation.
Interview tip โ A workspace is state plus variables plus runs plus permissions.
Q158 A change in the network workspace should trigger the app workspace automatically.
Intermediate
Situation read โ Chained workspaces.
What I'd do โ
- Configure a run trigger on the app workspace with the network workspace as source.
- Keep the data hand-off explicit through outputs (via
tfe_outputsor SSM).
Why โ Downstream plans run after upstream applies, catching impact quickly.
Interview tip โ Run triggers queue a plan, so you still decide on apply.
Q159 Private resources (RDS in a VPC) can't be reached by HCP Terraform's public runners.
Intermediate
Situation read โ Providers like PostgreSQL or Vault need network access.
What I'd do โ
- Deploy HCP Terraform agents inside the VPC, outbound-only to HCP.
- Create an agent pool and set the workspace's execution mode to "Agent".
- Run the agent as a container with a least-privilege role.
Why โ Agents poll HCP over HTTPS, so you don't open inbound ports.
Interview tip โ In GitHub Actions, the equivalent is a self-hosted runner in the VPC.
Q160 Migrate existing S3-backend stacks into HCP Terraform with no downtime.
Advanced
Situation read โ State move under live infrastructure.
What I'd do โ
- Freeze applies on the stack (disable the pipeline, announce a window).
- Replace the backend with the
cloudblock and runterraform init -migrate-state. - Configure variables and credentials in the workspace; run a speculative plan: must be empty.
- Update CI to use HCP runs, archive the old state object.
Why โ The state is copied, not recreated; an empty plan proves the move.
Interview tip โ Migrate one low-risk workspace first as a pilot.
Q161 Why would a company evaluate OpenTofu instead of Terraform?
Beginner
Situation read โ Licence and governance questions after HashiCorp moved Terraform to the BUSL licence in 2023.
What I'd do โ
- OpenTofu is an open-source fork under the Linux Foundation, MPL-2.0 licensed, compatible with Terraform configuration and providers up to the fork point.
- Check legal requirements: BUSL restricts competing commercial offerings, which matters for vendors, less for most internal users.
- Evaluate features: native state encryption and other OpenTofu-only features.
Why โ For most users it's a governance and licence decision, and technically a small switch.
Interview tip โ Stay neutral and factual; know both exist and why.
Q162 How do you migrate a repo from Terraform 1.6 to OpenTofu?
Intermediate
Situation read โ Drop-in replacement, but verify.
What I'd do โ
- Back up state; confirm Terraform version is within the compatible range from the OpenTofu migration guide.
- Install
tofu, runtofu init(it uses the OpenTofu registry) and regenerate the lock file. - Run
tofu plan; expect an empty plan. - Update CI, Docker images and docs.
tofu init -upgrade
tofu planWhy โ State format is compatible within supported version ranges; an empty plan is the test.
Interview tip โ Moving back isn't guaranteed after newer OpenTofu features write state.
Q163 When would you use OpenTofu's native state encryption?
Advanced
Situation read โ State holds secrets; backend encryption protects at rest, but anyone with read access sees plaintext.
What I'd do โ
- Configure an
encryptionblock with a key provider (KMS, PBKDF2 passphrase) and method (AES-GCM). - Apply to state and plan files.
- Roll out with a fallback block so existing plaintext state migrates smoothly.
Why โ Client-side encryption means the backend operator, or someone who can read the bucket, can't read secrets without the key.
Interview tip โ Key loss means state loss; back up key material and test recovery.
Q164 Name differences between OpenTofu and Terraform that could affect an adoption decision.
Intermediate
Situation read โ A feature-parity question.
What I'd do โ
- OpenTofu adds native state and plan encryption (1.7), and
for_eachon providers (1.9) and an-excludeflag (1.9). - Terraform ships its own newer features, such as ephemeral resources and write-only arguments, which OpenTofu may add later on its own timeline.
- Check your providers, tooling (Terragrunt, Atlantis, Checkov) and HCP-specific features.
Why โ The two projects have diverged; decide using your required features and tooling.
Interview tip โ Verify versions against current release notes before answering in detail.
Q165 How do you add a nightly drift detection job in CI?
Intermediate
Situation read โ Scheduled, read-only comparison.
What I'd do โ
on:
schedule: [{ cron: "0 2 * * *" }]
jobs:
drift:
steps:
- run: terraform init -input=false
- run: |
set +e
terraform plan -detailed-exitcode -lock=false -input=false
rc=$?
[ $rc -eq 2 ] && ./notify-slack.sh "Drift detected in ${{ github.workflow }}"
[ $rc -eq 1 ] && exit 1
exit 0Why โ Exit code 2 signals pending changes without parsing text; a read-only role makes it safe.
Interview tip โ Mention -lock=false is acceptable only for read-only plans.
Q166 Finance wants cost visibility on infrastructure PRs.
Intermediate
Situation read โ Cost surprise comes from unreviewed changes.
What I'd do โ
- Add Infracost to the PR workflow:
infracost breakdown --path . --format jsonandinfracost diffagainst the base branch. - Post the monthly cost delta as a comment.
- Add a policy that blocks PRs exceeding a threshold without approval.
Why โ A "+$4,200/month" line changes review behaviour.
Interview tip โ Cost estimates for usage-based resources are approximations.
Q167 How do you promote the same Terraform code from dev to stage to prod?
Advanced
Situation read โ Promotion needs to move through environments with the same module versions.
What I'd do โ
- Tag module releases; environments pin versions in their own directory.
- Pipeline: merge โ apply dev โ automated checks โ apply stage โ manual approval โ apply prod, each with its own plan.
- Keep environment differences in tfvars only.
Why โ What was proven in dev is the same code in prod; only inputs differ.
Interview tip โ Plans are per-environment; never promote a plan file.
Q168 Which CI gates would you require on every infrastructure PR?
Beginner
Situation read โ A baseline.
What I'd do โ
terraform fmt -check -recursiveterraform validatetflint --recursivecheckov -d .ortrivy config .terraform planwith output on the PR- Policy checks on the plan
Why โ Each gate is cheap and each catches a different class of mistake.
Interview tip โ Fail fast: run cheap checks first.
Q169 In a monorepo with 40 stacks, how do you plan only the stacks that changed?
Advanced
Situation read โ Planning everything on every PR is slow and noisy.
What I'd do โ
- Detect changed paths (
git diff --name-only origin/main...HEAD) or usepaths:filters. - Map changed module directories to the stacks that use them.
- Generate a job matrix of affected stacks and run plans in parallel.
- Apply in dependency order (network before apps).
Why โ Affected-only plans scale; a shared module change correctly fans out to all consumers.
Interview tip โ Shared module changes are the case naive path filters miss.
Q170 How do you keep the Terraform version consistent between laptops and CI?
Beginner
Situation read โ Version skew produces confusing plan differences.
What I'd do โ
- Commit a
.terraform-version(tfenv) or.tool-versions(mise/asdf) file. - In CI, read it:
terraform_version_fileinsetup-terraform. - Set
required_versionin code as the hard stop.
Why โ One source of truth for the version and a guard in the code.
Interview tip โ Bump the version in one PR with a clean plan in every environment.
Q171 Your HCP Terraform runs can't reach an internal Git server. What are your options?
Intermediate
Situation read โ VCS or private module sources aren't reachable from the managed runners.
What I'd do โ
- Publish modules to the HCP private registry instead of private Git URLs.
- Use agents in your network for runs that need internal access.
- Or run CLI-driven, with your CI uploading the configuration.
Why โ Moving the dependency to where the runner can reach it is easier than opening network paths.
Interview tip โ Note that agents handle runs, but VCS webhooks still need to reach HCP.
Q172 An emergency requires a manual apply to prod outside the pipeline. How do you handle it?
Advanced
Situation read โ Pipeline is down or too slow for an incident.
What I'd do โ
- Use a break-glass role that requires approval, MFA and is alerted on assumption.
- Apply the smallest possible change, with a saved plan reviewed by a second person.
- Immediately commit the same change to Git so code and state agree.
- Post-incident, review whether the pipeline path could have been used.
Why โ Emergencies happen, but they must be audited and reconciled to avoid drift.
Interview tip โ "Break-glass is allowed, silent break-glass isn't."
Q173 How do you handle secrets as environment variables in CI for Terraform?
Intermediate
Situation read โ Providers like Datadog or Cloudflare need API tokens.
What I'd do โ
- Store them in the CI secret store, exposed only to the apply job and protected branches.
- Pass them as provider environment variables (
DD_API_KEY) orTF_VAR_*markedsensitive. - Prefer OIDC or dynamic credentials where the provider supports them.
Why โ Secrets never appear in code, and PR jobs from forks never see them.
Interview tip โ Never echo env in debug steps.
Q174 Where does Terraform sit relative to GitOps tools like Argo CD?
Intermediate
Situation read โ Teams blur the boundary between infrastructure and application delivery.
What I'd do โ
- Terraform: cloud infrastructure (VPC, EKS, IAM, databases, DNS) and cluster bootstrap including installing Argo CD.
- Argo CD: everything that runs inside the cluster, reconciled continuously from Git.
- Share values through outputs, SSM or annotations on service accounts.
Why โ Terraform is plan/apply on demand and weak at continuous reconciliation; GitOps controllers are strong at it.
Interview tip โ Avoid managing app Helm releases in Terraform for fast-moving services.
Q175 Leadership wants developers to self-serve infrastructure safely. How do you design the platform?
Advanced
Situation read โ Tickets to the platform team don't scale.
What I'd do โ
- Publish versioned golden modules in a private registry with examples.
- Give teams their own repos and workspaces created from a template, with guardrails: policy as code, cost checks, least-privilege roles.
- Offer a small form or Backstage template that generates a PR with the module call.
- Platform team owns modules and policies; app teams own their usage.
Why โ Paved roads let teams move fast, and guardrails keep them safe.
Interview tip โ Measure it: time to first environment and number of exceptions.
Testing Upgrades and Large-Scale Operations
๐ฅ Learn this hands-on with DevOps Shack โ YouTube @devopsshack ยท Hindi @shackverse ยท Courses at devopsshack.com
Q176 What does each of terraform validate, plan and terraform test actually check?
Beginner
terraform validate, plan and terraform test actually check?Situation read โ A team thinks validate means the config works.
What I'd do โ
validate: syntax, types and references only; no cloud calls, no provider credentials.plan: computes the real diff against state and the cloud; catches invalid values the API rejects at plan time.terraform test: runs.tftest.hclfiles with assertions against plan or apply results.
Why โ They're layers: structure, behaviour against reality, and behaviour you assert.
Interview tip โ Many API errors only appear on apply (quotas, IAM), so plan isn't proof.
Q177 Write a native test for a module that creates an encrypted S3 bucket.
Intermediate
Situation read โ Use terraform test at plan level for fast feedback.
What I'd do โ
# tests/bucket.tftest.hcl
variables {
name = "acme-test-bucket"
}
run "bucket_is_encrypted" {
command = plan
assert {
condition = aws_s3_bucket_server_side_encryption_configuration.this.rule[0].apply_server_side_encryption_by_default[0].sse_algorithm == "aws:kms"
error_message = "Bucket must use KMS encryption."
}
}Run with terraform test.
Why โ Plan-mode tests don't create anything, so they run on every PR without cost.
Interview tip โ Use mock_provider (1.7+) to avoid needing credentials.
Q178 Compare Terratest with terraform test.
Intermediate
terraform test.Situation read โ Picking an integration test tool.
What I'd do โ
terraform test: native HCL, no extra language, supports plan and apply, mocks; ideal for module contracts.- Terratest: Go tests with full programming power, such as calling the deployed endpoint, retrying, SSH checks.
- Use native tests by default, and Terratest for end-to-end behaviour.
Why โ Smaller toolchain wins unless you need to test the running system.
Interview tip โ Mention cost and cleanup for either.
Q179 Real-cloud integration tests leave orphaned resources when they fail midway. How do you handle that?
Advanced
Situation read โ Cost leak and quota exhaustion in the test account.
What I'd do โ
- Run tests in a dedicated sandbox account with budgets and alarms.
- Tag everything with
test-run-idandttl. - Run a nightly sweeper (
cloud-nukeor a custom script) deleting expired items. - Always run
destroyin adefer/always()step.
Why โ Failures are normal; cleanup must not depend on tests succeeding.
Interview tip โ Account-level isolation limits blast radius.
Q180 How do you upgrade from Terraform 1.5 to 1.9 safely?
Intermediate
Situation read โ A multi-version jump across many stacks.
What I'd do โ
- Read the changelogs for each minor version.
- Upgrade the CLI in a branch with dev state; run
plan: expect no changes. - Roll through stage then prod; keep prod on the old CLI until the others are clean.
- Bump
required_versionlast.
Why โ After a newer version writes state, older versions can't read it; rollout order matters.
Interview tip โ Take a state backup before the first apply with the new CLI.
Q181 Major AWS provider upgrade from v4 to v5 (or v5 to v6) across many stacks. How do you plan it?
Advanced
Situation read โ Major versions change defaults and remove deprecated arguments.
What I'd do โ
- Read the upgrade guide; list breaking changes that touch your resources.
- Upgrade to the latest minor of the old major first to see deprecation warnings.
- Bump a single low-risk stack, fix code, and capture the pattern.
- Roll out stack by stack with plans reviewed for unexpected diffs.
- Pin to the new major in a shared module constraint.
Why โ The provider is where most upgrade breakage lives, so move slowly and learn from the pilot.
Interview tip โ Cite a concrete change, such as the v4 S3 bucket argument split into separate resources.
Q182 A stack is still on Terraform 0.12 syntax and old providers. What upgrade path do you follow?
Advanced
Situation read โ Skipping versions isn't supported.
What I'd do โ
- Step through 0.13, 0.14, 0.15 and 1.0 one at a time, using the matching upgrade guide.
- At 0.13 run
terraform 0.13upgradeand addrequired_providerssources. - Run
planafter each step: expect no diffs. - Then proceed to current 1.x.
Why โ State format upgrades are one-way and each step has a guided migration.
Interview tip โ Do it on a copy of state first.
Q183 Why do you review .terraform.lock.hcl diffs in PRs?
Beginner
.terraform.lock.hcl diffs in PRs?Situation read โ A lock file change shows up in a PR.
What I'd do โ
- Check which provider version and hashes changed.
- Confirm it matches an intended constraint bump.
- Ensure all platform hashes are present.
Why โ The lock file defines what code runs with your credentials, so unexpected changes are supply-chain red flags.
Interview tip โ Unexplained lock changes are worth a question.
Q184 Add a runtime health assertion to infrastructure without blocking applies.
Intermediate
Situation read โ You want post-apply validation that warns instead of failing.
What I'd do โ Use a check block (Terraform 1.5+).
check "app_is_healthy" {
data "http" "health" {
url = "https://${aws_lb.app.dns_name}/health"
}
assert {
condition = data.http.health.status_code == 200
error_message = "Health endpoint did not return 200."
}
}Why โ Check failures show as warnings on every plan/apply, which is useful for continuous validation.
Interview tip โ Contrast with precondition/postcondition, which block.
Q185 You need to push a change across 100 workspaces. How do you do it safely?
Advanced
Situation read โ Fleet-wide rollout, such as a module version bump.
What I'd do โ
- Group workspaces into rings: canary (2), non-prod, small prod, rest.
- Automate with a script or the HCP Terraform API (
tfeprovider or CLI) that opens PRs or triggers runs per ring. - Require clean or expected plans before each ring; pause on failures.
- Track progress in a dashboard.
Why โ Rings limit blast radius and give early signal.
Interview tip โ Resist "big bang" changes for shared infrastructure.
Q186 API rate limits cause "Throttling" errors during large applies. What do you do?
Intermediate
Situation read โ Hundreds of parallel API calls hit account limits.
What I'd do โ
- Lower
-parallelism(for example-parallelism=5). - Raise the provider's retry settings (
max_retries, and retry modeadaptivefor AWS). - Split the state so fewer resources are touched at once.
Why โ Terraform retries with backoff but needs headroom; less concurrency means fewer throttles.
Interview tip โ Check if other tools hit the same account concurrently.
Q187 Developers leave dev environments running over weekends, burning money.
Beginner
Situation read โ Idle cost.
What I'd do โ
- Add a scheduled pipeline running
terraform destroyon dev stacks at night (or scale to zero with schedule-based ASG actions). - Tag
ttlon ephemeral environments and sweep. - Make re-creation a single command.
Why โ If environments rebuild reliably, destroying them is free.
Interview tip โ This only works with fully-codified, tested environments.
Q188 A failed apply left half the resources created. What do you do?
Intermediate
Situation read โ Partial apply: Terraform saves progress to state as it goes.
What I'd do โ
- Read the error; fix the cause (permissions, quota, name collision).
- Re-run
terraform plan; it plans only what's missing. - If a resource was created but not recorded (timeout),
importit before applying. - Apply again.
Why โ Terraform is convergent: re-applying finishes the job.
Interview tip โ Check for tainted resources in the plan.
Q189 Someone ran terraform destroy against production. What's your recovery plan?
Advanced
terraform destroy against production. What's your recovery plan?Situation read โ Worst-case incident.
What I'd do โ
- Stop further changes and revoke the identity's access.
- Check what survived: deletion protection and
prevent_destroymay have saved databases. - Restore stateful data from snapshots and backups first (RDS, EBS, S3 versions).
- Re-apply the code (state is empty or reflects destroyed items) to recreate stateless layers.
- Run a blameless review: remove human prod credentials, require approval, enable protection.
Why โ Data recovery comes first; infrastructure is reproducible from code.
Interview tip โ This is why DR drills and deletion protection exist.
Q190 What do you look for when reviewing a teammate's Terraform PR?
Intermediate
Situation read โ A code review for infrastructure.
What I'd do โ
- Read the plan first: creates, updates, destroys, replacements; question every
forces replacement. - Security: IAM wildcards, open CIDRs, unencrypted storage, public access.
- Blast radius: shared resources, state boundaries.
- Quality: variable validation, module pinning, naming, tags, no hardcoded IDs.
Why โ The plan shows effects; the code shows intent; both matter.
Interview tip โ "I review the plan before I review the code."
Q191 Design a multi-account AWS landing zone managed with Terraform.
Advanced
Situation read โ Dozens of accounts, consistent guardrails.
What I'd do โ
- Use AWS Organizations with OUs; manage them and SCPs in a
managementstack. - An account factory (AWS Control Tower Account Factory for Terraform, or custom) creates accounts from a request file.
- Baseline modules per account: IAM roles, CloudTrail, Config, VPC, budgets.
- Layered states, a central state bucket in a tooling account, and OIDC roles per account.
Why โ Accounts are created and baselined by code, so each looks identical and is auditable.
Interview tip โ Describe the account-vending flow end to end.
Q192 New AWS feature, but provider support hasn't landed. Options?
Intermediate
Situation read โ Resource missing in hashicorp/aws.
What I'd do โ
- Check the
awsccprovider (generated from Cloud Control API). - Use
aws_cloudformation_stackwrapping a minimal template. - Use
terraform_data+ AWS CLI as a stopgap, documented as technical debt.
Why โ Pick the option that still gives drift detection and dependency tracking.
Interview tip โ Also open a provider issue.
Q193 How do you write unit tests for policy rules without deploying?
Advanced
Situation read โ Policies need tests like code.
What I'd do โ
- Keep a folder of sample plan JSONs (good and bad cases).
- Run
conftest verifyfor Rego unit tests, oropa test policy/. - Generate sample plans from small fixtures using
terraform show -json. - Run policy tests in CI whenever policies change.
Why โ Untested policies either block everything or nothing.
Interview tip โ Test both the deny and the allow path.
Q194 Where do you draw the line between Terraform and Helm/Kubernetes providers for cluster add-ons?
Intermediate
Situation read โ Platform bootstrapping.
What I'd do โ
- Terraform: cluster, node groups, IAM roles for service accounts, and a minimal set of bootstrap add-ons (CNI, CoreDNS, Argo CD).
- GitOps tool: everything else, such as ingress controllers, monitoring and apps.
- Separate state for cluster and for bootstrap resources.
Why โ Slow-moving infrastructure benefits from plan/apply; fast-moving workloads benefit from continuous reconciliation.
Interview tip โ Avoid long helm_release lists in one state.
Q195 A new hire needs to start contributing to Terraform safely on day one.
Beginner
Situation read โ Onboarding with a safety net.
What I'd do โ
- Give a read-only role so
terraform planworks locally. - Pair on a small PR in a dev stack; CI does the apply.
- Point them at the module README, the style guide and pre-commit config.
Why โ They learn the workflow without the ability to damage prod.
Interview tip โ Safe environments make fast onboarding possible.
Q196 Does Terraform have rollback? How do you undo a bad change?
Advanced
Situation read โ A change made things worse.
What I'd do โ
- Revert the commit and apply (roll forward with the old code).
- For replaced resources, recreate from the previous config; stateful data comes from backups.
- If state is wrong, restore the previous state version from S3 versioning, then plan.
Why โ Terraform has no transactional rollback; "revert in Git and apply" works for stateless resources only.
Interview tip โ Distinguish stateless (easy) from stateful (needs backups).
Q197 List a short checklist of Terraform best practices you'd enforce in a team.
Beginner
Situation read โ A standard answer to "your top practices".
What I'd do โ
- Remote state with locking and versioning.
- Pinned providers and committed lock file.
- Modules with typed, validated variables.
- Plan in PR, apply from CI only.
- Secrets never in code; least-privilege roles.
- Policy checks and drift detection.
Why โ Each point maps to a real failure mode: lost state, drift, version skew, leaks.
Interview tip โ Tie each one to an incident it prevents.
Q198 Terraform vs Crossplane vs Pulumi vs CDK: how do you advise a team?
Advanced
Situation read โ Tool selection.
What I'd do โ
- Terraform/OpenTofu: largest provider ecosystem, declarative HCL, plan/apply workflow, easiest hiring.
- Pulumi / AWS CDK: general-purpose languages, good for developer-heavy teams, more abstraction power and more ways to write unmaintainable code.
- Crossplane: Kubernetes-native control plane, continuous reconciliation, fits platform teams built around Kubernetes APIs.
- Choose by team skills, existing platform and ecosystem fit.
Why โ Tool religion is less important than consistent practice, and migration cost is high.
Interview tip โ Give a recommendation and the condition under which you'd change it.
Q199 A plan shows a diff on a resource nobody touched, after a provider upgrade. How do you decide whether to apply?
Intermediate
Situation read โ A new provider version computes attributes differently, or a default changed.
What I'd do โ
- Read the diff attribute by attribute; check the provider changelog.
- If the change is a new default, either accept it or pin the old behaviour explicitly in code.
- If it's a bug, pin the previous provider version and file an issue.
Why โ No-op upgrades are the goal; unexpected diffs deserve explanation before apply.
Interview tip โ Explicit config beats relying on defaults that can change.
Q200 After a year of growth, the team has 60 stacks with inconsistent practices. How do you standardise without stopping delivery?
Advanced
Situation read โ Organic sprawl.
What I'd do โ
- Inventory stacks: Terraform versions, provider versions, backend types, owners.
- Publish a baseline template repo (backend, pre-commit, CI, policy) and a migration guide.
- Migrate by risk and value: top 10 critical stacks first, with no-diff plans.
- Track compliance in a scorecard; make new stacks use the template by default.
Why โ Incremental, measured migration beats a freeze; the template makes the right way the easy way.
Interview tip โ Show a metric, such as the percentage of stacks on the baseline.