Infrastructure as Code (IaC) & Terraform Enterprise Master Interview Bank
Terraform state management, remote backends with state locking, HCL modules, dependency graphs, drift detection, and CI/CD automation.
Curriculum Roadmap & Learning Path
4 StagesPart 1: Terraform Core Architecture, HCL & Providers (1 - 15)
15 QuestionsWhat is Infrastructure as Code (IaC), and how does Declarative (Terraform) differ from Imperative (Ansible / Scripts)?
Infrastructure as Code (IaC) is the practice of provisioning, configuring, and managing computing infrastructure using machine-readable configuration files rather than manual UI clicks or interactive CLI commands.: Declarative (Terraform, OpenTofu, CloudFormation): You specify the desired end state ("I want 3 EC2 instances in a...
Explain the Terraform Core Engine Architecture: Providers, State File, and Directed Acyclic Graph (DAG).
Terraform Core • Parses HCL configurations • Builds a Directed Acyclic Graph (DAG) of all resources to determine dependencies and maximum parallel execution paths • Compares the desired state against the State File to produce an execution plan.
Explain HCL Syntax Fundamentals: Variables, Locals, Outputs, and Data Sources.
Variables (variable): Configurable parameters passed into modules (can have default values, types, and validation rules) • Locals (locals): Internal computed variables or constants scoped to the module to prevent repetitive expressions.
What is `terraform init`, and what happens inside the `.terraform` directory and `.terraform.lock.hcl`?
terraform init initializes a working directory containing Terraform configuration files: Downloads required provider plugins and child modules into the hidden .terraform/ directory • Initializes the configured backend (local disk, AWS S3, Terraform Cloud).
Understanding the Execution Lifecycle: `terraform validate` vs. `terraform plan` vs. `terraform apply`.
terraform validate: Checks syntax, HCL validity, and internal consistency locally without contacting remote cloud APIs • terraform plan: Refreshes the state file against cloud APIs, compares current state with configuration files, builds the dependency graph, and.
What is the Terraform State File (`terraform.tfstate`), and why is it essential?
Terraform must map real-world cloud resources to the resources declared in your HCL code. The State File stores this mapping: Maps aws_instance.web to AWS resource ID i-08a9f2123b • Tracks resource metadata, dependencies, and cached attributes (private IPs, ARNs).
How do you configure a Production Remote Backend with AWS S3 and DynamoDB State Locking?
Storing state locally on a developer's laptop causes state desynchronization, lost state on laptop failure, and race conditions if two engineers run apply simultaneously. Production S3 + DynamoDB Backend: S3 Bucket: Stores the state file with Versioning and Server-Side Encryption (KMS) enabled.
How do you protect sensitive secrets from leaking into plaintext Terraform State files?
Terraform state files store all resource attributes—including database passwords, TLS private keys, and API tokens—in plaintext JSON. Protection strategy: Enable Server-Side Encryption (SSE-KMS) and strict IAM bucket policies on the S3 state bucket.
Explain Critical State Management Commands: `state rm`, `state mv`, and `state list`.
terraform state list: Lists all resources currently tracked in the state file • terraform state show : Displays all attributes of a specific tracked resource • terraform state rm : Removes a resource from state tracking without destroying the actual cloud resource.
How do you import existing Cloud Infrastructure into Terraform (Traditional `import` vs. `import` block in Terraform 1.5+)?
Legacy CLI: terraform import awss3bucket.legacy bucket-name-123 • Terraform 1.5+ Declarative import block: Configured directly in code.
What is Configuration Drift, and how do you detect and remediate it in Terraform?
Configuration Drift happens when an engineer makes manual changes in the AWS Console (e.g. editing a security group rule or changing instance size), making real-world infrastructure differ from Terraform code.: Detection: Run terraform plan -refresh-only.
Compare Meta-Arguments: `count` vs. `for_each` (Why is `for_each` preferred for dynamic resources)?
count: Creates resources indexed by integer: aws_subnet.public[0], [1], [2] • Severe Risk: If you remove an item from the middle of a list, Terraform shifts array indexes, causing unnecessary destructions and recreations • foreach: Iterates over maps or sets: awssubnet.public["us-east-1a"].
How do Dynamic Blocks work in Terraform, and when should you use them?
A dynamic block produces repeated nested configuration blocks (like ingress rules inside a security group) inside a top-level resource, driven by a collection variable.
Explicit Dependencies (`depends_on`) vs. Implicit Dependencies in the Resource Graph.
Implicit Dependency (Automatic): When you reference an attribute of one resource in another (e.g. vpcid = awsvpc.main.id) • Explicit Dependency (dependson): Used when two resources have a hidden dependency not expressed in HCL references (e.g. an S3 bucket.
Explain Resource Lifecycle Rules: `create_before_destroy`, `prevent_destroy`, and `ignore_changes`.
createbeforedestroy = true: Creates replacement resources before destroying the old ones • prevent_destroy = true: Causes Terraform to reject an apply and throw an error if an operation would destroy the resource.
Part 2: Modules, Multi-Environment & GitOps (16 - 30)
10 QuestionsHow do you design Production-Ready Reusable Terraform Modules?
A modular design structure: main.tf: Resource declarations • variables.tf: Input definitions with descriptive documentation and type constraints • outputs.tf: Essential output attributes exposed to consumers • versions.tf: Pinned minimum Terraform and provider versions.
Terraform Workspaces vs. Directory-Based Multi-Environment Architecture: Which is better for enterprise?
Terraform Workspaces: A single set of HCL files with multiple named states (default, staging, prod) • Risk: A single misconfigured variable can accidentally apply to the wrong workspace • Directory-Based Architecture (Industry Standard) • Separate folders: environments/dev/, environments/staging/, environments/prod/.
How do Custom Input Validation, Preconditions, and Postconditions work in Terraform?
Variable Validation: Enforces input constraints at plan time • Preconditions: Assertions verified before a resource or module evaluates • Postconditions: Assertions verified after a resource is created, checking real cloud attributes.
What is Terragrunt, and how does it DRY up Terraform configurations?
Terragrunt is a thin wrapper around Terraform that: Keeps Backends DRY: Defines a single root terragrunt.hcl backend configuration; all sub-environments inherit it without copy-pasting • Promotes Immutable Modules: Enforces passing input variables directly to versioned Git modules without duplicate boilerplate.
What is OpenTofu, and why was it created?
In August 2023, HashiCorp switched Terraform's license from open-source MPLv2 to proprietary Business Source License (BSL 1.1). In response, the Linux Foundation launched OpenTofu as a 100% open-source, community-governed, drop-in replacement fork.
What is Policy as Code? Enforcing Guardrails with Open Policy Agent (OPA) / Conftest.
Policy as Code validates planned infrastructure against organizational compliance, security, and cost rules before apply runs. Using Conftest (OPA / Rego): Export plan as JSON: terraform show -json tfplan.binary > plan.json • Evaluate rules written in Rego • "No S3 buckets without server-side encryption.".
What Static Security Analysis Tools should run in an IaC CI/CD Pipeline?
Checkov / tfsec: Scans HCL code for hundreds of cloud security misconfigurations and CIS benchmarks • TFLint: Catches provider-specific deprecations, invalid instance types, and naming errors.
Explain GitOps for Infrastructure: How does Atlantis automate Terraform Pull Requests?
Atlantis is an open-source pull request automation server: Engineer opens a Git PR with Terraform changes • Atlantis runs terraform plan automatically and posts the formatted output as a PR comment • Team reviews and approves the plan • Engineer types atlantis apply in the PR comments.
How do you refactor Terraform code without destroying existing cloud resources using the `moved` block?
In older Terraform, renaming a resource in HCL caused Terraform to destroy the old resource and create a new one. Starting in Terraform 1.1, the moved block instructs Terraform to update the state file mapping without touching the physical cloud infrastructure.
What are Ephemeral Resources in Terraform 1.10+?
Ephemeral Resources represent short-lived secrets or temporary access tokens (e.g. temporary Vault tokens, dynamic AWS STS credentials).
Part 3: Kubernetes Infrastructure as Code & GitOps (31 - 42)
9 QuestionsHow do the Terraform Kubernetes and Helm Providers work?
Terraform Kubernetes Provider: Manages native Kubernetes manifests (kubernetesdeployment, kubernetesservice) directly through the Kubernetes API • Terraform Helm Provider: Manages Helm release deployments (helm_release), passing custom values.yaml overrides dynamically.
What is GitOps, and how does ArgoCD continuously reconcile Kubernetes cluster state?
GitOps is an operating model where a Git repository is the single source of truth for desired infrastructure and application state. ArgoCD: A Kubernetes controller running inside the cluster • Continuously polls the Git repository and compares Git manifests with active cluster state.
How do you manage Secrets in GitOps without committing plaintext secrets to Git?
Two production patterns: External Secrets Operator (ESO): Git contains an ExternalSecret CRD referencing a secret in AWS Secrets Manager or HashiCorp Vault • Sealed Secrets (Bitnami): Developers encrypt secrets with a public key and commit the encrypted SealedSecret to Git.
Kubernetes Ingress Controllers (Nginx, Traefik, ALB) and Automated TLS with Cert-Manager.
Ingress Controller: A reverse proxy and load balancer translating external HTTP/HTTPS traffic to internal cluster Services based on hostnames • Cert-Manager: A native Kubernetes controller that automates issuing and renewing SSL/TLS certificates from Let's Encrypt or HashiCorp Vault via.
Service Mesh Architecture: Istio vs. Linkerd (Mutual TLS, Traffic Shifting, Canary).
A Service Mesh injects a sidecar proxy (Envoy) next to every pod to handle service-to-service communication: Zero-Trust mTLS: Automatically encrypts and verifies identities for all pod-to-pod traffic without application changes.
What is the Kubernetes Operator Pattern and Custom Resource Definitions (CRDs)?
An Operator encodes human operational domain knowledge (backup, failover, scaling) into software: CRD (Custom Resource Definition): Extends Kubernetes API with new resource types (e.g. apiVersion: postgres-operator/v1, kind: PostgresCluster).
Multi-Tenancy in Kubernetes: Namespaces, NetworkPolicies, and ResourceQuotas.
Namespaces: Virtual clusters isolating resource names • ResourceQuotas & LimitRanges: Cap CPU, RAM, and Pod counts per namespace to prevent noisy neighbors from exhausting node capacity • NetworkPolicies: Virtual firewalls controlling traffic flow between pods.
Pod Disruption Budgets (PDB) and Zero-Downtime Kubernetes Node Upgrades.
When upgrading Kubernetes worker nodes (kubectl drain), nodes are cordoned and pods evicted. A Pod Disruption Budget (PDB) specifies the minimum number or percentage of replicas that must remain running simultaneously during voluntary disruptions.
Autoscaling in Kubernetes: HPA vs. VPA vs. Karpenter.
HPA (Horizontal Pod Autoscaler): Adds or removes pod replicas based on CPU, memory, or custom metrics (e.g. queue depth) • VPA (Vertical Pod Autoscaler): Adjusts CPU and memory requests/limits of existing containers over time • Karpenter: High-speed node auto-provisioner.
Part 4: Enterprise Cloud Infrastructure Architecture & SRE (35 - 50)
16 QuestionsHub-and-Spoke VPC Architecture with AWS Transit Gateway and Terraform.
Connecting dozens of VPCs via point-to-point VPC Peering creates an unmaintainable O(N^2) mesh. Hub-and-Spoke Architecture: Hub VPC: Centralized inspection VPC containing firewalls, NAT gateways, and VPN/DirectConnect connections • Spoke VPCs: Application and database VPCs in separate AWS accounts.
Designing Multi-Region Active-Active Cloud Architectures with Terraform.
Deploy identical infrastructure stacks across multiple regions (e.g. us-east-1 and eu-west-1) using parameterized Terraform modules and provider • Use Amazon Route 53 Geolocation or Latency-based Routing to steer user traffic to the nearest healthy region.
Zero-Trust Cloud Security: AWS IAM Identity Center (SSO), Least Privilege, and Workload Identity Federation.
No Long-Lived Access Keys: Eliminate permanent awsaccesskey_id for developers • Workload Identity Federation: Allow GitHub Actions or Kubernetes pods to assume AWS IAM roles dynamically via OpenID Connect (OIDC) tokens.
How do you integrate FinOps (Cloud Cost Optimization) into IaC workflows?
Run Infracost on every PR: Prevents costly accidental provisioning (e.g. provisioning a db.m5.24xlarge instead of db.t4g.medium) • Enforce mandatory billing and ownership tags via Terraform default_tags.
Blue/Green vs. Canary Deployments at the Infrastructure / Network Layer.
Blue/Green: Two identical infrastructure stacks exist simultaneously • Canary: Traffic is shifted incrementally (e.g. 10%, then 25%, then 50%, then 100%) using weighted ALB target groups or Route 53 weighted.
Configuration Management vs. IaC: When do you use Ansible alongside Terraform?
Terraform owns the Infrastructure lifecycle: Creates VPCs, subnets, route tables, load balancers, security groups, and VM instances • Ansible owns the OS/Host Configuration: Configures bare-metal servers, edits configuration files, hardens Linux kernels, and installs software.
Disaster Recovery (DR) RPO and RTO Automation with Terraform.
Store Terraform configuration in a separate version control system and replicate state storage across multiple AWS regions • Automated failover scripts trigger terraform apply in the disaster recovery region using pre-configured variable files (dr.tfvars), standing up.
How do you handle State Lock Deadlocks in Terraform (`force-unlock`)?
If an apply command is killed prematurely (e.g. network failure, laptop lid closed), DynamoDB retains the lock, blocking future applies.
Multi-Account AWS Architecture: AWS Organizations, SCPs, and Terraform.
Running production, staging, and development in a single AWS account is dangerous (blast radius covers the whole company). Multi-Account Strategy: Use AWS Control Tower / AWS Organizations • Separate accounts: Prod-Workloads, Dev-Workloads, Security-Audit, Log-Archive, Shared-Services.
Automated Testing for Terraform: `terraform test` vs. Terratest (Go).
terraform test (Built into Terraform 1.6+): Native HCL-based test framework • Terratest: Go library that executes terraform apply, sends real HTTP requests to the created load balancer, verifies the 200 OK response, and.
What is Blast Radius Reduction, and how do you structure state files to prevent catastrophic failures?
Putting your VPC, Kubernetes cluster, databases, and DNS in a single gigantic state file means any typo or state corruption can take down the entire company. Blast Radius Reduction: Split infrastructure into independent layers with dedicated state files: 01-network/ (VPC, Subnets, Transit Gateway) - Updated rarely.
How do you manage DNS and Domain Automation with Terraform and AWS Route 53?
Automate Route 53 Hosted Zones, alias records pointing to ALBs, and ACM Certificate validation records.
CloudTrail, AWS Config, and Compliance Auditing with Terraform.
CloudTrail: Logs every API call made across all accounts • AWS Config: Continuously monitors and records AWS resource configurations and evaluates them against compliance rules (e.g. S3 bucket public.
Container Image Scanning and Harbor / ECR Registry Best Practices.
Enable Image Scanning on Push in Amazon ECR to automatically detect CVE vulnerabilities • Enforce Immutable Image Tags to prevent overwriting existing tags like v1.0.0 • Sign container images using Cosign / Sigstore and verify signatures in Kubernetes admission controllers.
Managing Distributed Infrastructure Teams: Code Reviews and Pull Request Standards for IaC.
Mandatory 2-person reviews for production changes • CI automated checks • terraform fmt -check • tflint.
Senior Platform Engineer Conclusion: Core Philosophy of Cloud & DevOps Engineering.
A Staff/Lead Platform Engineer operates on four non-negotiable principles: Everything as Code: If it is not in Git and automated by Terraform/GitOps, it does not exist • Minimize Blast Radius: Decouple state files and separate accounts to isolate failures.