Intermediate Level
This section covers intermediate concepts in Infrastructure as Code, including state management, testing strategies, and best practices.
Terraform Questions
What is the difference between local and remote state?
hclThe rule to state plainly: local state is for learning and throwaway labs only — every shared environment uses remote state with locking and encryption, because state contains resource IDs and frequently secrets.
How do you handle secrets in Terraform?
The challenge is double: secrets must not live in code, and Terraform state stores them anyway once a resource uses them.
- Code side — variables marked
sensitive = true; values injected via environment variables (TF_VAR_db_password), a secrets-manager data source (Vault/AWS Secrets Manager providers), or-var-fileexcluded from Git - State side — enable backend encryption + strict access control; Terraform Cloud/Enterprise offers stronger state encryption; the nuclear option for leaked values: rotate the secret, then
terraform taint/replace the resource - Avoid —
terraform outputwithsensitivevalues still prints with-raw; plan/apply logs can echo secrets — keep state access and CI logs locked down
The honest line: Terraform has no end-to-end secret solution — the pattern is "inject at apply time from a vault, encrypt the backend, and audit who can read state."
- Code side — variables marked
What is state locking, and what happens when it fails?
Locking prevents two concurrent applies from corrupting state (each reading the same baseline and writing conflicting changes):
- S3 backend — DynamoDB lock table (the
dynamodb_tablesetting); S3 remote state with Terraform ≥1.10 also supports S3-native locking viause_lockfile - Terraform Cloud/Enterprise — locks are built into runs
- Failure mode — a crashed apply leaves a stale lock; Terraform refuses to run. Resolution: verify no one is actually applying, then force-unlock with the lock ID (
terraform force-unlock <LOCK_ID>) — with the explicit understanding that force-unlocking during a live apply will corrupt state
Related safety commands to know:
terraform plan -lock-timeout=5m(wait politely instead of failing instantly) and running applies through CI (serialized, single-writer by design).- S3 backend — DynamoDB lock table (the
What are Terraform workspaces, and when should you use them vs. separate directories?
Workspaces give one configuration multiple named state instances:
bash- Use case — identical infrastructure with small per-environment differences (e.g.,
count = var.env == "prod" ? 3 : 1), referencingterraform.workspacein code - The limitation interviewers want — workspaces share one code path: environment drift creeps in as
if workspace == ...logic, and all environments' state depends on one config. Divergent environments quickly become unmaintainable - The alternative — directory-per-environment (
environments/dev,environments/prod) reusing shared modules: more boilerplate, but environments can differ freely and apply independently - Also distinguish from Terraform Cloud workspaces — which are more like "runs for a directory + variables" units, not the CLI concept
Rule of thumb: workspaces for genuinely identical environments (per-region replicas), directories for divergent ones (dev vs prod).
- Use case — identical infrastructure with small per-environment differences (e.g.,
How do you create and structure reusable Terraform modules?
A module is a directory with its own
.tffiles, invoked from elsewhere:hclhclBest practices to name:
- Contract-driven — inputs (variables with types/descriptions) and outputs (what consumers need); no hidden lookups into the root config
- One responsibility per module — VPC module, RDS module; compose at the root
- Version module sources — Git tags/registry versions (
?ref=v1.2.0); consumers upgrade deliberately - Registry structure —
examples/,READMEwith inputs/outputs table; private registries (TFC, Artifactory) for org-wide reuse
The org-level payoff: teams stop copy-pasting infrastructure — they consume reviewed, versioned building blocks.
What is
terraform import, and when do you use it?importbrings existing, manually-created infrastructure under Terraform management:bashAfter importing, you must write matching configuration (the
planshows the gap — ideally zero) —terraform plan -generate-config-out=generated.tf(1.5+) scaffolds it for you.When to use: adopting IaC for an existing estate, or capturing a console-created emergency resource. The follow-up to know: import registers the resource in state but doesn't create code — until config matches, the next apply would propose deleting/recreating it. Related tool:
terraformerfor bulk-exporting whole estates.
Ansible Questions
How do variables work in Ansible, and what's the precedence order?
Variables come from many sources — and precedence decides conflicts. The commonly used layers (low → high):
- Role defaults (
roles/x/defaults/main.yml) — lowest, overridable defaults - Inventory group_vars / host_vars — per-group/per-host facts
- Playbook
vars:— play-level explicit values extra vars(-e/--extra-vars) — highest precedence, always wins
yamlThe pattern this enables: role defaults define sane behavior, inventory overrides per environment, and
-eforces CI-specific values. Also knowset_fact/registerfor runtime-computed values — and that Jinja2 templating ({{ }}) drives all interpolation.- Role defaults (
What are Ansible facts, and how do you control them?
Facts are system data Ansible collects automatically at the start of each play (OS version, IP addresses, CPU count, disks):
bashyamlUsage to know: facts drive conditional logic (
when: ansible_os_family == "RedHat"chooses apt vs yum), and templates reference them. Control flags:gather_facts: no(faster for tasks that don't need them),fact_caching(Redis/JSON cache to skip re-collection), andansible_factsnaming (olderansible_prefix vs the newer namespaced form).What are Ansible handlers, and how do they work?
Handlers are tasks that run only when notified by a change — and only once, at the end of the play, no matter how many tasks notified them:
yamlThe idempotency synergy is the point: if the config is already correct, no change happens, no notification fires, and nginx keeps running — a restart happens only when something actually changed. Details to know: handlers run in the order defined, not the order notified;
listenlets multiple handlers share a topic; andflush_handlersforces them to run mid-play when ordering matters.What are Ansible roles, and how do you structure one?
Roles package playbooks into reusable, shareable units with a conventional layout:
code- Usage —
roles:in a play,ansible-galaxy init nginxto scaffold, Galaxy/Ansible Automation Hub for sharing - The DRY payoff — "configure nginx" written once, parameterized per environment, reused across every playbook
- Modern alternative to mention — Collections bundle roles + modules + plugins as the current distribution format
- Usage —
How do you test Ansible playbooks and roles?
Test in layers, like any code:
- Syntax —
ansible-lint(style + common bugs),ansible-playbook --syntax-check,yamllint - Dry run —
--checkmode shows what would change without changing anything (diff with--diff) - Local integration — Molecule: spins up containers/VMs, applies the role, runs verifier assertions, destroys — the standard role-testing framework
- Idempotency check — Molecule's default assertion: run the role twice, second run must report zero changes
The CI pattern to name: lint +
--checkon every PR; Molecule against containers for role repos. Untested infrastructure code fails at the worst time — during a prod deploy.- Syntax —
CloudFormation Questions
What are the main components of CloudFormation?
- Templates — YAML/JSON declarations of resources and their relationships (the code)
- Stacks — a deployed instance of a template; created/updated/deleted as an atomic unit with automatic rollback on failure
- Change sets — a preview of what an update will do before executing it (Terraform plan's equivalent)
- StackSets — deploy one template across many accounts and regions in one operation (org-wide baselines: logging, guardrails)
- Nested stacks / modules — reusable template components; plus the newer CloudFormation Modules for abstracted resource groups
The mental model to give: template = code, stack = running instance, change set = plan, StackSet = fleet deployment. Everything else (drift detection, deletion policies, rollback triggers) hangs off that model.
How do you update a CloudFormation stack safely?
bashSafety concepts to name:
- Update vs replacement — some property changes require CloudFormation to recreate the resource (e.g., an instance's AZ) — change sets flag this explicitly, which is where data-loss accidents get caught
- Update policies —
UpdateReplacePolicy/DeletionPolicy: Retainprotect databases and volumes during replacement/deletion - Rollback — failed updates automatically roll back to the last stable state;
RollbackConfigurationwith monitoring alarms can trigger rollback on runtime failures (e.g., app health), not just deploy failures
What is the difference between
DependsOn,Ref/GetAtt, andCreationPolicy?- Implicit dependency (Ref/GetAtt) — referencing another resource's attribute (
!Ref MyVPC) automatically orders creation. This is the default mechanism — explicitDependsOnis only for ordering that produces no natural reference (e.g., "wait for the log group before the app") DependsOn— explicit ordering: this resource waits for another to complete firstCreationPolicy— goes further: the resource isn't marked CREATE_COMPLETE until it signals back (e.g., an EC2 instance's cfn-init scripts finish and sendcfn-signal). Without it, CloudFormation marks an instance "created" when the VM exists — not when the app on it is actually running
The interview point:
DependsOnsequences creation,CreationPolicysequences readiness — confusing them produces stacks that complete while applications aren't up yet. (Sibling to know:UpdatePolicycontrols how instances are replaced during updates.)- Implicit dependency (Ref/GetAtt) — referencing another resource's attribute (
Contribute & Stay Updated
Want to contribute? We welcome contributions! If you have insights, new tools, or improvements, feel free to submit a pull request.
How to Contribute?
- Read the CONTRIBUTING.md guide.
- Fix errors, add missing topics, or suggest improvements.
- Submit a pull request with your updates.
Community & Support
GitHub: @NotHarshhaa Blog: ProDevOpsGuy Telegram Community: Join Here