Advanced Level
This section covers expert-level concepts in Infrastructure as Code, including CI/CD integration, security best practices, and enterprise-scale implementations.
Terraform Questions
How do you implement CI/CD pipelines for Terraform?
The standard pattern is plan on PR, apply on merge — with the plan as the review artifact:
yamlElements that make it production-grade:
- Plan-as-comment — reviewers see the exact create/update/destroy diff in the PR
- State locking via backend — concurrent plans are safe, applies serialize
- OIDC federation — no static cloud keys in CI
- Policy gates — OPA/Sentinel/Checkov evaluate the plan before apply
- Manual approval for prod — GitHub Environments / GitLab protected environments
- Tools worth naming: Atlantis (PR-driven plans/applies), Terraform Cloud/Enterprise run pipelines, Digger
What is policy-as-code for Terraform, and which tools exist?
Policies evaluate the plan output and reject infrastructure that violates org standards — before any resource is created:
- Sentinel — HashiCorp's framework (Terraform Cloud/Enterprise); HCL-like policies with
tfplan/tfconfigimports, soft-mandatory vs hard-mandatory enforcement - OPA / Conftest — Rego policies against plan JSON; free and cloud-neutral
- Checkov / tfsec — security-focused scanners (CIS benchmarks, encryption, public access) run directly on the code
pythonThe lifecycle to describe: policies versioned in Git, tested like code, rolled out in advisory mode first (violations warn), then enforced — and every exception is documented with an expiry.
- Sentinel — HashiCorp's framework (Terraform Cloud/Enterprise); HCL-like policies with
How do you detect and manage infrastructure drift?
Drift = live infrastructure diverging from state + code — from console changes, out-of-band hotfixes, or broken automation:
- Detect — scheduled
terraform planruns (zero diff = clean); Terraform Cloud drift detection; S3 backend resources flagged by external tools (driftctl — now Snyk IaC) - Decide the policy per resource — GitOps-style auto-revert (drift is undone) for standard resources vs alert-and-review for the few that legitimately change outside Terraform (autoscaling, some tags)
- The import rescue — a manually created emergency resource gets
import-ed into state and codified immediately, so it's not the next untracked snowflake - Prevention — IAM without console write access to prod, IaC-only change policy, and making the pipeline path faster than the console
The consequence to articulate: drift means the next
terraform applymay revert a live fix — that's why detection is scheduled, not done "when we remember".- Detect — scheduled
How do you manage multi-region and multi-account Terraform at scale?
- Multi-region — aliased providers let one configuration manage several regions:
hcl- Multi-account — one Terraform "landing zone": account/OU structure via AWS Organizations, role assumption across accounts (
assume_rolein the provider), and separate state per account/env — blast-radius isolation - Scale structure — directory-per-environment or per-stack repos, shared versioned modules, Terragrunt (or Terramate) to de-duplicate backend/config boilerplate across hundreds of stacks
- OpenTofu — the open-source Terraform fork worth naming for vendor-independence discussions (drop-in compatible, Linux Foundation governed)
The scaling principle: many small states beat one giant state — plan/apply speed, lock contention, and blast radius all improve per stack.
Terraform Cloud/Enterprise vs open-source Terraform — what do you get?
- Remote runs — plan/apply executed on managed workers; state locking, drift detection, and scheduled runs built in
- Private module registry — org-wide, versioned module sharing with usage visibility
- Sentinel/OPA policy enforcement — policy-as-code applied to every run
- Team governance — RBAC per workspace, audit logs, SSO
- Cost estimation — pre-apply cloud cost estimates per plan
The comparison answer: OSS Terraform + CI (Atlantis/GitHub Actions) + DIY state management gets you surprisingly far — TFC/Enterprise buys the operational layers (governance, drift, registry, agent isolation) that large orgs otherwise hand-build. Also know HCP Terraform as the current branding and the OSS OpenTofu alternative.
How do you test Terraform code?
Layered like any other code:
- Static —
terraform fmt -check,terraform validate,tflint(provider-aware linting: invalid instance types, deprecated syntax) - Security — Checkov/tfsec/Trivy on the code (public buckets, open SGs, unencrypted volumes)
- Policy — OPA/Sentinel on the plan JSON
- Integration — Terratest (Go): deploys real infrastructure into a disposable account, asserts behavior (endpoint responds, bucket refuses public access), then destroys
- Smoke after apply — pipeline post-apply checks against the created resources
goThe tiering to state: every PR gets static + security + plan review; integration tests run nightly or per-release (they cost real cloud money); prod applies are gated by all of the above.
- Static —
Ansible Questions
How do you implement RBAC in Ansible Automation Platform (Tower/AAP)?
Ansible Automation Platform gives Ansible a web UI, scheduling, and enterprise access control:
- Organizations → Teams — the hierarchy: users belong to teams, teams belong to organizations
- RBAC by object — permissions attach to job templates, inventories, projects, and credentials (use/read/execute/admin), so a team can run a deploy job without seeing the credentials inside it
- Credential isolation — machine credentials, vault credentials, and cloud credentials are stored encrypted; users reference them, never view them
- Execution environments — containerized runner images with pinned Ansible/tool versions, per-job isolation
The enterprise pattern: git-backed projects (playbooks pulled from Git), scheduled/triggered job templates, and RBAC such that developers execute a "deploy" button without raw SSH access to any host.
How do you handle secrets in Ansible at scale?
- Ansible Vault — encrypt files or single values (
ansible-vault encrypt_string); vault passwords via prompt, password file (mode 600), or CI-injected; use multiple vault IDs for per-environment keys - HashiCorp Vault lookup —
lookup('community.hashi_vault.vault_read', ...)fetches secrets at runtime instead of storing them — combined with short-lived dynamic credentials (Vault's database engine), this is the scale answer - Cloud secret stores — AWS Secrets Manager lookup plugins; secrets pulled per task, never written to disk
- The rules that hold everywhere — no plaintext secrets in playbooks or Git,
no_log: trueon tasks handling sensitive output, and rotation that doesn't require re-encrypting every playbook
The scale insight: Vault-style dynamic secrets change the failure model — a leaked credential expires on its own, and revocation is immediate from the vault.
- Ansible Vault — encrypt files or single values (
How do you write a custom Ansible module?
When no module fits, write one in Python following the module contract — idempotent, JSON-in/JSON-out:
python- Contract details —
argument_specvalidates inputs;supports_check_modehonors dry runs;exit_json(changed=...)reports idempotency; failures viafail_json(msg=...) - Before writing one — check whether a
scripttask,commandwithcreates:, or an existing collection module suffices; custom modules carry maintenance cost - Distribution — bundle into a collection with docs and tests
- Contract details —
CloudFormation Questions
How do you implement cross-stack references in CloudFormation?
Export outputs from one stack; import them into another:
yaml- The constraint to know — you cannot delete a stack (or a resource) while its exports are imported elsewhere — CloudFormation enforces the dependency graph across stacks
- Naming discipline — stable export names (
<env>-vpc-id); renaming breaks every consumer - Alternatives at scale — SSM Parameter Store (more flexible than exports, but loses the delete-protection), or nested stacks/one-big-stack when everything is one lifecycle. AWS-native answer for org-wide sharing: Resource Access Manager for subnets/transit gateways
How do rollbacks and drift detection work in CloudFormation?
- Automatic rollback — a failed create/update reverts the stack to the previous stable template; failure details land in stack events. RollbackConfiguration adds monitoring alarms that trigger rollback when the application misbehaves post-update (runtime failures, not just deploy failures)
- Continue/fix flows —
--disable-rollbackfor debugging failed creates;continue-update-rollbackafter fixing the cause of a failed update-rollback - Drift detection —
aws cloudformation detect-stack-driftcompares live resources against the template: statuses IN_SYNC / MODIFIED / DELETED per resource. Console changes become visible — the same problem Terraform drift solves, with the same remedy (re-codify or revert) - Update policies —
UpdateReplacePolicy/DeletionPolicy: Retainprotect stateful resources during replacements and stack deletion
The expert framing: rollback alarms (app health) + drift detection + Retain policies together make CloudFormation stacks safe to hand to CI/CD.
What are Lambda-backed custom resources, and when do you use them?
When CloudFormation has no native resource type for something you need, a custom resource delegates creation/update/delete to a Lambda:
yamlThe Lambda receives the request type (Create/Update/Delete) plus
ResourceProperties, performs the action, and must respond to the pre-signed SNS/queue URL — a hung handler blocks the stack for an hour.- When to use — third-party APIs not yet in CloudFormation, data migrations at deploy time, custom validations
- The modern alternative to lead with — CloudFormation Registry resource types (CFN-CLI to develop first-class typed resources) and, honestly, Terraform for resources CloudFormation lacks
- The gotchas — idempotent handlers, correct response on every path (including errors — otherwise stack timeouts), and Delete handling that doesn't leak the external resource
How do you deploy across multiple accounts with StackSets?
StackSets deploy one template to many accounts/regions in one operation — the mechanism behind org-wide baselines:
yaml- Permission models — SERVICE_MANAGED (Organizations-managed, auto-deployment for new accounts) or SELF_MANAGED (cross-account IAM roles you provision)
- Deployment targets — OUs or account lists, per-region deployment ordering, account-level stack instances with per-instance parameter overrides
- The guardrail pattern it enables — org-wide security baselines (CloudTrail everywhere, mandatory encryption, guardduty) deployed and kept deployed by the StackSet — new accounts are compliant on creation
- Alternatives worth naming — Control Tower built on StackSets, Terraform for org-level management when you're multi-cloud
How do you test infrastructure code — Terraform and CloudFormation — in CI?
Layered testing, mirroring application code:
- Static —
terraform fmt/validate, tflint; CloudFormation:cfn-lint(syntax, property validation), cfn-nag (security) - Security scanning — Checkov/tfsec (IaC misconfigs: open SGs, unencrypted storage, public access) as PR gates
- Plan/change-set review — the diff posted to the PR; policy-as-code (OPA/Sentinel) evaluating the plan
- Integration tests — Terratest for Terraform (deploy to a disposable account, assert behavior, destroy); CloudFormation: deploy to a test account + assertion scripts (or pytest with boto3) + teardown
- Post-deploy smoke — pipeline asserts the created endpoints/buckets behave as declared
The budget note to include: integration tests spend real money and take real time — run static/security on every PR, integration nightly or per-release against ephemeral accounts, and keep destroy-after-test non-negotiable.
- Static —
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