Skip to content
Tech Interview Prep
Technical interview guide

Configuration Management

Keeping infrastructure and application configuration consistent, versioned, and reproducible across environments.

Minutes to read
4
Practice MCQs
25
Interview Q&A
25
Edition
v5
Editorial status
Reviewed

Scope: Ansible Core, Puppet Core, Chef Infra Client, Salt, Kubernetes, NIST SP 800-128, and CIS Controls guidance current 2026-08-31.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-3

Design ordering for package, template, and service resources.

Answer

Assumptions. A declarative config-management system with a resource graph: Puppet, Chef, or Ansible. Three resource kinds: package (install a pinned version), template (render a config file), service (run/reload a daemon). Nodes are long-lived and converge repeatedly, so idempotence and minimal restarts matter.

Core answer. Model the three as a directed graph with explicit edges, never source order: package → file → service. The first edge is a plain ordering edge (require/before); the second is a refresh edge (notify/subscribe), so the service restarts only when the rendered file actually changed. Render to a temp path, validate with the target binary, then install.

Why source order fails. Puppet compiles a catalog from every class, defined type and include in the run. The order resources land in that catalog depends on class evaluation order, not the order you read them in the manifest: a file written above its package can still be applied first. Only declared edges are guaranteed.

PUPPET
package { 'nginx':
  ensure => '1.24.0-1.el9',
}

file { '/etc/nginx/nginx.conf':
  ensure  => file,
  owner   => 'root',
  mode    => '0644',
  content => template('nginx/nginx.conf.erb'),
  require => Package['nginx'],
  notify  => Service['nginx'],   # refresh edge, not ordering
}

service { 'nginx':
  ensure  => running,
  enable  => true,
  require => Package['nginx'],
}

notify on the file and subscribe on the service are the same edge spelled from either end; declare one.

Trace. Three runs against the same node:

runpackagefileservicechanged
firstinstalledcreatedstarted3
rerun, nothing editedunchangedunchangedunchanged0
template editedunchangedrewritten → notify firesrestarted2

The rerun reporting 0 changed is the whole point. A plain require between file and service would restart nginx every run.

Failure modes.

  • Missing require => Package: on a clean node the file resource fails because /etc/nginx does not exist yet. Detected by a converge on a fresh node, not on your dev box.
  • Ordering edge instead of refresh edge between file and service: change count stays above 0 on a no-op rerun; every run restarts the daemon and drops in-flight connections.
  • Cycle: A require B plus B require A fails catalog compilation with a dependency-cycle error before any change is applied. Cheap to catch, so reject cycles at compile time.
  • Unvalidated config: write the file, restart, and nginx exits on a syntax error, taking the service down. Render to /tmp/nginx.conf, run nginx -t -c /tmp/nginx.conf, and replace the live file only on exit 0.

Alternatives and when to pick them.

  • Declarative graph vs linear script. A one-shot bootstrap where every node is fresh can be a linear shell script: no cycle risk, no graph to reason about. Pick the graph when nodes converge repeatedly and you need no-op reruns.
  • Validate-in-place vs side-by-side. Side-by-side (temp render plus nginx -t) costs an extra file and a validation step but bounds the blast radius to a failed converge. Validate-in-place is only defensible when the service cannot be tested without the live path.
  • Ansible handlers dedupe by name and run at end of play; meta: flush_handlers forces them mid-play. Batching is fine until a later task needs the restarted service, then you must flush.

Scale. Illustrative: 200 nodes, hourly converge. Restart-on-every-run is 200 × 24 = 4,800 restarts/day; refresh-only is roughly 200 on the day the template changes. At ~200 ms of dropped connections per restart, that is the difference between a routine edit and a daily blip.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-20

How does variable precedence resolve conflicting definitions of the same setting across inventory, group_vars, host_vars, role defaults, and playbook vars, and how do you diagnose which value actually won on a given host?

Answer

Precedence is a fixed, ordered list, not a merge. Ansible resolves a name by walking 22 levels from lowest to highest and keeping the last definition it finds. Nothing is combined unless you ask for it with combine() or +.

The levels that matter in practice, low to high:

#LevelTypical file
2role defaultsroles/x/defaults/main.yml
4-7group_vars (all, then groups)inventory/group_vars/*.yml
9-10host_varsinventory/host_vars/web1.yml
11facts / cached set_factsgathered or fact cache
12-14play vars, vars_prompt, vars_filessite.yml
15role varsroles/x/vars/main.yml
16-17block vars, task varssite.yml
18include_varstasks
19set_fact / registeredruntime
20-21role params, include paramssite.yml
22extra vars-e, always wins

Two consequences people miss. Role vars beat play vars, so a value in roles/x/vars/main.yml cannot be overridden from the playbook: only by role params or -e. And dicts are replaced, not merged: group_vars/all setting nginx: {worker_processes: 4, keepalive_timeout: 65} and host_vars setting nginx: {worker_processes: 8} leaves keepalive_timeout undefined on that host. Use nginx | combine(host_override, recursive=True) when you want a merge.

Diagnosis, in order:

  1. Reproduce at the point of use. A debug task resolves with full precedence at that moment:

yaml

  • ansible.builtin.debug: msg: "app_port={{ app_port | default('UNSET') }}"

ansible-inventory --host web1 --yaml shows only the inventory layers (group_vars, host_vars, inventory file). It never shows play, role or runtime values, so it can confirm a host_vars value exists but not that it won.

  1. Check for extra vars before editing anything. -e, -e @file, an AWX/Tower survey, or a CI wrapper variable all land at level 22 and are invisible in the repo. This is the most common cause of "my change did nothing".

  2. Walk the layers with grep: grep -rn "app_port" inventory/ group_vars/ host_vars/ roles/*/defaults roles/*/vars site.yml. ansible-playbook -vvv prints which group_vars and host_vars files it loads, which narrows the search but does not name the winner.

  3. Check group ordering. Groups merge in hierarchy order, and groups at the same level merge in ASCII order with the last winning; ansible_group_priority in group_vars/all overrides that. ansible-inventory --graph shows the hierarchy.

  4. Guard it. An assert on the resolved value fails the play instead of shipping a wrong config.

Failure modes worth naming: a set_fact with cacheable: true writes into the fact cache and reappears at level 11 on later runs, so a stale value outlives the play; hash_behaviour=merge is deprecated and not a reliable fix for the dict-replace trap; and include_vars at level 18 silently beats task vars, so a task-level override can lose to a file included earlier.

Precedence is a resolution algorithm, not a design tool. Keep one source of truth per setting, namespace names, and assert the range you expect rather than relying on which layer happens to win.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

How do you use facts and conditionals to apply OS-specific configuration from a single role across a mixed fleet (choosing package names, file paths, and service names per distribution) and what happens when a fact is missing or wrong on a host?

Answer

A strong candidate answers in three moves: gather facts, map them to per-OS variables in one role, and make a missing or wrong fact a hard failure instead of a silent default.

Core pattern. One role, one task list, one vars file per OS family. The task list never contains when: ansible_facts['distribution'] == 'Ubuntu' scattered through it; the only branch is which vars file gets loaded.

yaml

roles/web/vars/Debian.yml

web_pkg: apache2 web_conf: /etc/apache2/apache2.conf web_svc: apache2

roles/web/vars/RedHat.yml

web_pkg: httpd web_conf: /etc/httpd/conf/httpd.conf web_svc: httpd

yaml

roles/web/tasks/main.yml

  • name: Require the facts this role branches on ansible.builtin.assert: that: - ansible_facts['os_family'] is defined - ansible_facts['os_family'] in ['Debian', 'RedHat'] fail_msg: "os_family={{ ansible_facts['os_family'] | default('undefined') }} is not supported by role web"

  • name: Load OS-specific variables ansible.builtin.include_vars: "{{ ansible_facts['os_family'] }}.yml"

  • name: Install web server ansible.builtin.package: name: "{{ web_pkg }}" state: present

  • name: Deploy config ansible.builtin.template: src: web.conf.j2 dest: "{{ web_conf }}" notify: restart web

  • name: Service enabled and running ansible.builtin.service: name: "{{ web_svc }}" state: started enabled: true

package and service already abstract the package manager and init system, so the vars file carries only the three things that genuinely differ: package name, path, service name. Use ansible_facts[...] rather than the legacy top-level ansible_* names.

Which fact to branch on. os_family (Debian, RedHat, Suse, Archlinux) is the right key for name mapping; distribution and distribution_major_version only when a repo or config syntax actually differs.

FactValuesUsed for
ansible_facts['os_family']Debian, RedHat, Susewhich vars file
ansible_facts['distribution']Ubuntu, Rocky, AlmaLinuxrepo/version quirks
ansible_facts['distribution_major_version']12, 9, 22version-gated settings
ansible_facts['pkg_mgr']apt, dnf, zypperpackage manager
ansible_facts['service_mgr']systemd, sysvinitservice handling

Puppet does the same with $facts['os']['family'] in a selector or Hiera hierarchy; Chef with node['platform_family'] in a case. The shape is identical.

When a fact is missing or wrong. Three distinct failures:

  1. Missing fact. gather_facts: false, a stripped container without /etc/os-release, or a fact-cache miss. Without the assert, include_vars: "{{ ansible_facts['os_family'] }}.yml" fails with an undefined-variable error on that host: loud, but late and per-host. The assert turns it into one clear message before anything is installed. The dangerous variant is | default('Debian'): the host silently gets Debian paths and the failure surfaces later as a service that will not start.
  2. Stale fact. Fact caching plus an in-place upgrade (Debian 11 to 12) or a reimage (CentOS to Rocky) leaves the cache saying RedHat while the host is now Debian. Wrong package name, wrong path, service fails with "unit not found". Detect by bounding cache TTL, forcing setup on the hosts you are changing, and asserting a fact you can cross-check against /etc/os-release.
  3. Wrong fact from the wrong context. A container or chroot reports the host's os_family. Check ansible_facts['virtualization_type'] before trusting the branch.

Coverage. include_vars fails loudly for an unlisted family, but only on the host that hits it: --syntax-check will not catch it. Run the role in CI against one container per supported os_family (Molecule or equivalent) so a new family is a test failure, not a production surprise.

When not to do this. If the OSes diverge beyond names (different config syntax, different daemons, different reload semantics) a single task list with more conditionals becomes unreadable. Split into platform-specific roles or platform-specific task files included by the same entry point, and keep the shared logic in one place.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-14

How do dynamic inventories work in configuration management, and how do you handle rapidly auto-scaling fleets?

Answer

The first 90 seconds

A dynamic inventory is a plugin that builds the host list at run time by querying a source of truth (a cloud API, a hypervisor, or a service registry) instead of reading a static file. It runs before the play starts and emits hosts, groups and hostvars; the orchestrator then connects to whatever it found.

For an auto-scaling fleet that snapshot is the problem. Between the query and the last task, instances terminate. So the design has three parts: shrink the window (short cache TTL, server-side filters), tolerate hosts that vanish mid-run (serial, max_fail_percentage, ignore_unreachable), and stop making the control node a dependency of every node. Converge on the node itself via pull or a baked image, and keep central runs for changes that genuinely need coordination.

What the plugin produces

YAML
# inventory.aws_ec2.yml — amazon.aws collection, ansible-core 2.16
plugin: amazon.aws.aws_ec2
regions: [us-east-1]
filters:
  tag:Environment: prod
  instance-state-name: running
hostnames: [instance-id]
compose:
  ansible_host: private_ip_address
keyed_groups:
  - key: tags.Role
    prefix: role
cache: true
cache_plugin: jsonfile
cache_timeout: 60
cache_connection: /tmp/ansible-inv-cache

Caching is off by default in aws_ec2; switched on, the default cache_timeout is 3600 s: useless for a fleet that turns over every few minutes. 60 s is the working range. filters are applied server-side by the API, so they cut both response size and request cost.

$ ansible-inventory -i inventory.aws_ec2.yml --list | jq '._meta.hostvars["i-0a1b2c3d"]'
{ "ansible_host": "10.0.4.17",
  "instance_id": "i-0a1b2c3d",
  "placement": "us-east-1a",
  "tags": { "Environment": "prod", "Role": "api" } }   # trimmed

--limit does not reduce the API call: the plugin resolves the whole inventory first and the limit is applied to the result. Filter in the plugin if you want fewer calls. When the plugin does hit the ceiling, EC2 returns RequestLimitExceeded and the inventory parse fails outright: the play never starts.

The staleness window, in numbers

Illustrative: a 300-instance fleet with a 30-minute average instance lifetime replaces 10 instances/min, so 5 terminations/min. Cache TTL 60 s plus a 90 s play is up to 150 s of drift: roughly 12 hosts in the inventory are already gone. Ansible's default SSH timeout is 10 s and default forks is 5, so those 12 hosts add 12 × 10 ÷ 5 = 24 s of pure waiting to the run and still show up as unreachable=12 in the recap. ignore_unreachable: true stops them failing the play; it does not stop the timeout. Raising forks and dropping timeout to 5 does.

Push vs pull

Central pushNode-side pull / baked image
Who queries the source of truthcontrol node, once per runeach node, at boot
Scale-inSSH to a terminated host, timeoutnode is gone, nothing to do
API loadone query per run, every runone per boot, naturally spread
Convergence latencynext scheduled runseconds after boot
Coordinated changenaturalneeds a separate central run
Blast radiusthe control nodeone node

Pull is ansible-pull -U <repo> -C main -i localhost, from user-data; Chef runs chef-client as a systemd unit against the Infra Server; Puppet runs puppet agent -t with PuppetDB as the inventory source; Salt uses salt-cloud to provision and the minion to converge. Bake the base with Packer (amazon-ebs builder) so boot-time convergence only fetches secrets and renders templates.

Scale-in

Trap termination with an ASG lifecycle hook on autoscaling:EC2_INSTANCE_TERMINATING, --heartbeat-timeout 300, --default-result CONTINUE. The node deregisters from Consul (consul leave), drains, then calls complete-lifecycle-action --lifecycle-action-result CONTINUE. If the heartbeat expires, CONTINUE terminates anyway: the hook buys time, it does not guarantee cleanup. The ALB target group deregistration_delay.timeout_seconds defaults to 300 s, so a scale-in takes up to five minutes unless you lower it. The ASG health check grace period defaults to 0 s, which is why a slow boot-time CM run gets instances killed mid-convergence; set it to cover boot + convergence + app start.

When not to go pull

Anything that must be ordered across the fleet (schema migrations, quorum changes, certificate rotation) belongs in a central run with serial: 1 and max_fail_percentage. Pull gives you no ordering guarantee at all.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

How would you validate a generated service configuration?

Answer

The 90-second answer. Assume the config is generated from a declarative source, a service spec plus a pinned template, and the target is a named runtime version. Validation is a ladder, and each rung exists because the one below it is blind to something. Schema validation catches a malformed source. A deterministic render catches nondeterminism. Parsing with the target binary catches syntax and directives that version no longer accepts. Policy checks catch configs that are legal but unsafe. A shadow instance catches configs that are legal, safe, and still wrong under real traffic. Then activate atomically and verify after.

The ladder, and what each rung catches.

  1. Input schema and cross-field constraints. JSON Schema or CUE over the service spec. Catches replicas: "three", and rules like "if tls.enabled then tls.certRef must be set". Milliseconds, runs on every commit.
  2. Deterministic render. Same input, byte-identical output: sorted map keys, no timestamps, no hostname baked in, template version pinned in the artifact header. Catches the diff noise that makes review useless.
  3. Parse with the exact target version. nginx -t inside the nginx:1.25.3 image, envoy --mode validate -c, promtool check config, kubectl apply --dry-run=server. This is the rung that catches a directive your generator emits that the target dropped: nginx 1.25.1 deprecated the listen ... http2 parameter in favour of http2 on;, and a pipeline that treats that warning as failure catches it before merge instead of at reload.
  4. Policy invariants. OPA/Rego through conftest test, or Kyverno/Gatekeeper for Kubernetes. Catches legal-but-unsafe: container running as root, no resource limits, :latest tag, a proxy_pass to a host outside the allowlist, a secret inlined instead of a secretKeyRef.
  5. Shadow instance. Deploy the rendered artifact to an isolated instance, mirror a slice of production traffic (say 5% for 10 minutes), compare error rate and p99 against the incumbent. This is the only rung that catches a config that parses, passes policy, and still breaks: proxy_read_timeout 5s when the upstream p99 is 8s produces 504s that no static check can see.
  6. Atomic activation, then verify. Write to a versioned path, flip a symlink or update the ConfigMap, reload rather than restart (nginx -s reload drains old workers). Record the sha256 of the rendered artifact next to the source commit and template version. Then run negative tests, request a path that should 403 and confirm it does, and watch telemetry for one full traffic cycle.

Trade-offs. The static rungs cost tens of milliseconds and run on every commit. Server-side dry-run costs a cluster round trip and is the only way to see admission webhooks and API-server defaulting. A shadow instance costs a full replica plus mirrored traffic and ten minutes of wall clock. The deciding criterion is where the risk lives: if the config is a thin translation of a well-tested spec, static plus dry-run is enough. If the generator composes values that interact with live state (timeouts, pool sizes, upstream addresses) the shadow rung is the one that pays for itself. Skip it and you find out in production.

Failure modes and how you see them.

  • Template drift: generator emits a field the target version dropped. Detected by the parse rung, exit 1, in CI, before merge.
  • Silent defaulting: the API server fills in a default that differs from what you wrote. Detected by diffing --dry-run=server -o yaml against the rendered manifest; the diff is the effective config.
  • Secret leakage: a literal token in the rendered artifact. Detected by gitleaks plus a policy rule requiring valueFrom.secretKeyRef. Blast radius is the CI log and the artifact store, so rotate on detection.
  • Parses-but-wrong: timeout or pool-size mismatch. Detected only by shadow traffic, as an error-rate and p99 delta against the incumbent.
  • Non-atomic activation: a restart instead of a reload drops in-flight connections. Detected by a connection-reset spike in the activation window.

What would change my answer. If the target has no offline validator, some managed services only validate on apply, the parse rung collapses into dry-run and the shadow rung becomes mandatory. If the config is generated per request rather than per deploy, the shadow instance is replaced by a canary with automatic rollback on the error-rate signal.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

A resource reports changed on every run even though its desired state is already present. How do you diagnose and fix it?

Answer

Start by reproducing the report with the tool's diff/check mode: ansible-playbook --check --diff, puppet apply --noop --show_diff, chef-client --why-run, or salt-call state.apply test=True. The diff tells you what the provider thinks differs. If the diff shows only a timestamp, a hostname, a random UUID, or the output of a command that includes volatile data, the resource is comparing volatile desired state to actual state. That is the bug.

The most common cause is a template that embeds a value that changes every run. For example, a Jinja2 template with {{ ansible_date_time.iso8601 }} in /etc/app/config.yml renders different content each run, so the file resource rewrites the file, reports changed, and fires any handler that depends on it: often restarting the service every cycle. The fix is to remove volatile data from the managed artifact. If you need a deploy timestamp, write it to a separate file that nothing notifies on, or use a stable version variable. Do not paper over it with changed_when: false on the template; that hides real drift.

The second cause is a command or shell task that runs unconditionally. command: /usr/bin/foo --init runs every time. Add a guard: creates: /var/lib/foo/initialized or removes:, or use a native module. Chef's bash resource has not_if/only_if guards for the same purpose. If the command is genuinely a read-only check, changed_when: false is correct for reporting, but it does not make the resource converge: it just stops lying about change.

The third cause is a custom resource whose idempotency check is wrong. In Puppet, a custom type's is/current comparison must compare the desired property to the actual system state, not to the output of a command that includes volatile data. In Chef, a custom resource's load_current_value must read the current state correctly. If the check always returns false, the resource always converges.

Distinguish a false positive from a real change. A package pinned to latest that upgrades is a real change. A file whose mode is normalized differently by the provider (e.g., SELinux context, or a symlink vs regular file) may report changed once and then settle. Run twice and compare: if the second run is clean, the first was a real convergence. If every run reports changed, it is a false positive.

Worked example: Ansible role manages /etc/nginx/nginx.conf from a template that includes # Generated by Ansible on {{ ansible_date_time.date }}. Every 30-minute run rewrites the file, notifies restart nginx, and causes a rolling restart. The diff shows only the date line. Fix: remove the date line from the template; if you want a generation timestamp, write it to /var/log/nginx/last_config_generation with copy and changed_when: false so it does not notify the service. After the fix, the second run reports ok and no handler fires.

Failure modes: masking with changed_when: false on a resource that does change state hides real drift and breaks audit. Using force: no on a template stops updates entirely. A guard like creates: on a command that should re-run when a config file changes is wrong: use a notify from the file resource instead. Detection: run the play twice in check mode and diff the two reports; any resource that reports changed both times without a real state difference is the culprit.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

How do you ensure idempotency when using command or shell tasks in configuration management?

Answer

A command/shell/exec task is idempotent only when the engine can decide without running it whether the desired state already holds. Native modules do that by inspecting the resource; raw commands don't, so you supply the decision yourself. Three mechanisms, in order of preference:

  1. Artifact predicate: the engine checks for a file, directory or socket. creates: skips the task if the path exists; removes: skips it if the path is absent.
  2. Guard command: a cheap read-only command whose exit code decides. onlyif/only_if runs the task only if the guard exits 0; unless/not_if skips it if the guard exits 0.
  3. Probe and branch: run a read-only command, register its output, and gate the mutating task on the result with when:.
EngineSkip if guard succeedsRun only if guard succeedsArtifact predicate
Ansible command/shellno native guard: when: on a registered probesamecreates: / removes:
Chef execute/bashnot_ifonly_ifcreates
Puppet execunlessonlyifcreates
Salt cmd.rununlessonlyifcreates

Ansible deliberately has no onlyif/unless; the equivalent is a registered probe plus when:. Salt's onlyif/unless are arguments to cmd.run, not requisites: requisites (require, watch, onchanges) order states, they don't test state.

Artifact predicate. Best when the side effect leaves a permanent file.

YAML
- name: Generate TLS DH parameters
  ansible.builtin.command: openssl dhparam -out /etc/ssl/certs/dhparam.pem 2048
  args:
    creates: /etc/ssl/certs/dhparam.pem

Second run: creates finds the file, the task reports ok, no handler fires. Failure mode: an interrupted first run leaves a zero-byte file, and creates now skips forever. Write to a temp path and mv it into place atomically, or guard on content (openssl dhparam -check).

Guard command. Chef:

RUBY
bash 'enable_br_netfilter' do
  code 'modprobe br_netfilter && echo br_netfilter >> /etc/modules-load.d/k8s.conf'
  not_if 'lsmod | grep -q br_netfilter && grep -q br_netfilter /etc/modules-load.d/k8s.conf'
end

The guard runs on every converge, so keep it to a grep/lsmod, not a network call. Prefer a Ruby block (not_if { File.exist?('/x') }) when you can avoid forking a shell.

Probe and branch. When the command itself is the only way to read state:

YAML
- name: Probe wireguard interface
  ansible.builtin.command: wg show wg0
  register: wg
  changed_when: false
  failed_when: wg.rc != 0 and 'No such device' not in wg.stderr

- name: Bring up wg0
  ansible.builtin.command: wg-quick up wg0
  when: wg.rc != 0

changed_when: false is the load-bearing line: without it every converge reports changed, which fires notify handlers and makes drift detection useless.

Check mode. Command tasks can't simulate side effects, so under --check Ansible reports them as changed without executing. Mark read-only probes check_mode: false so they still run and later when: conditions have real data. Puppet's equivalent is refreshonly => true with subscribe, or --noop; Chef's is --why-run.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-2

How would you prove a custom resource is idempotent?

Answer

What I'd say first. Idempotent for a Kubernetes controller means reconcile is a function of the CR's spec plus the observed child objects: run it twice on unchanged input and you get the same end state, and the second pass issues zero writes. So the property I test is convergence plus write silence, not "the resource still exists". The assumption I state out loud is that the controller is level-triggered: it gets called on every watch event, including the events its own status writes generate, so it must be safe to call forever with the same input.

1. Pin the postcondition before testing anything. A snapshot diff of children (name, labels, ownerReferences, the spec fields you own) plus status.observedGeneration == metadata.generation. generation only increments on spec changes for resources with a status subresource, so if observed generation never catches up to generation you have not converged, whatever the logs claim.

2. Count writes; don't compare objects. Wrap the client, count Create/Update/Patch/Delete including the status subresource, seed one CR, then reconcile three times with identical input and require passes 2 and 3 to write nothing.

Go
type countingClient struct {
	client.Client
	writes uint32 // Create/Update/Patch/Delete, status included
}

func (c *countingClient) Create(ctx context.Context, o client.Object, opts ...client.CreateOption) error {
	atomic.AddUint32(&c.writes, 1)
	return c.Client.Create(ctx, o, opts...)
}
// Update, Patch and Delete are wrapped the same way, one line of counting each.

if _, err := r.Reconcile(ctx, req); err != nil { t.Fatal(err) }
first := atomic.LoadUint32(&c.writes)
for i := 0; i < 2; i++ {
	if _, err := r.Reconcile(ctx, req); err != nil { t.Fatal(err) }
}
if extra := atomic.LoadUint32(&c.writes) - first; extra != 0 {
	t.Fatalf("pass 2 wrote %d times; not idempotent", extra)
}

Status writes go through client.SubResourceWriter, so the wrapper has to override Status() as well: otherwise a controller that rewrites status on every pass looks perfectly silent.

3. Then the cases that actually break it. Drift: scale the child Deployment to 0 by hand, reconcile, assert it is restored and no other child changed. Spec change: bump the CR, assert one controlled transition, then assert the following pass is silent again.

breakersecond pass doesassertion that catches it
child name has a rand/time suffixcreates a second childchildren per ownerReference equals the expected set, stable across passes
appends to a list with no dedupe (status.conditions, spec.tolerations)list growslist length identical on pass 2 and pass 3
writes status unconditionallyhot loop on its own writecontroller_runtime_reconcile_total flat when nothing changed; apiserver audit shows verb=update every loop
treats AlreadyExists as a hard errorrequeues forevercontroller_runtime_reconcile_errors_total is 0 while the cluster is healthy
external call with no idempotency keysecond DNS record or second LB targetstub call count on pass 2 is 0

Partial-failure trace. CR v1 wants a ConfigMap, a Service and a Deployment. Pass 1 creates the ConfigMap and the Service, then the Deployment create fails (apiserver 500, or the manager is killed). observedGeneration stays 0. Pass 2 gets all three: two exist, one is absent, so it issues exactly one Create. Assert three children, each owned by the CR, observedGeneration == 1, zero reconcile errors. The broken version creates all three blindly and returns the AlreadyExists on the ConfigMap, so it never reaches the Deployment and the CR sits in a permanent error loop.

Trade-offs. The fake client is in-process and milliseconds, and it lets you inject a failure on the Nth call, which is the only way to script partial failure deterministically. It does not run CRD defaulting or validation, admission webhooks, or real resourceVersion conflicts. envtest gives you a real kube-apiserver and etcd, so defaulting, schema validation and 409s on stale resourceVersion are genuine, but there is no kubelet, so Deployments never roll out and you assert on the objects you own, not on ReplicaSet status. Use a kind cluster for garbage collection of ownerReferences, finalizers, and anything that touches a real external system. For concurrency, the workqueue dedupes keys, so at MaxConcurrentReconciles=1 the same CR is never reconciled in parallel; set it to 4 deliberately and assert the losing writer gets a 409 and requeues rather than creating a duplicate child.

A second run that reports "unchanged" is not evidence on its own: a controller that writes nothing at all also looks unchanged. The evidence is zero writes on the second pass with generation caught up to observed generation.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

Explain the limits of check mode or dry-run output.

Answer

What a dry run actually is. Every check mode is a model of the change computed from the tool's own inputs, not from the target system. It is exact for the part of the change that is known at plan time and validated by the same code path that applies it. Everything else is deferred to apply, and the deferral is usually silent: the preview looks complete while omitting the thing that will fail.

Three mechanisms produce the gap:

  1. Unknown values. Some attributes are computed only at apply. Terraform prints them as (known after apply), and any check that depends on them cannot run.
  2. The apply path executes code the plan path does not. Provisioners, controllers, admission webhooks, post-start hooks.
  3. The target validates things the tool cannot model. Global name uniqueness, quotas, API-side semantic checks.
CheckWhat it actually executesWhat it cannot see
terraform planState refresh, provider PlanResourceChange, diffValues computed at apply, provisioners, API-side uniqueness and quota checks
kubectl apply --dry-run=clientLocal parse and built-in schema validationAPI defaulting, admission webhooks, CRD schema validation
kubectl apply --dry-run=serverFull admission chain (mutating + validating), defaulting, no persistenceControllers: scheduling, image pull, readiness; quota consumption
ansible-playbook --checkOnly modules that declare check-mode supportcommand/shell effects, modules that skip, anything behind check_mode: false

Trace: a plan that cannot know its own failure.

HCL
resource "random_id" "suffix" { byte_length = 4 }

resource "aws_s3_bucket" "logs" {
  bucket = "logs-${random_id.suffix.hex}"
}

Plan output:

# aws_s3_bucket.logs will be created
+ resource "aws_s3_bucket" "logs" {
    + bucket = (known after apply)
    + id     = (known after apply)
  }

Apply generates the suffix (say a3f19c2b) and calls CreateBucket. S3 bucket names are globally unique, so if logs-a3f19c2b exists, apply returns BucketAlreadyExists. The plan could not have caught this: the name did not exist when the plan ran. terraform plan -detailed-exitcode (0 = no changes, 1 = error, 2 = changes present) tells you the plan is non-empty, not that it will succeed.

Trace: a preview that is wrong, not just incomplete. kubectl apply --dry-run=server runs the admission chain, so a mutating webhook that injects a sidecar shows up in the returned object. You see the injected container. But the ReplicaSet controller never runs, so no pod is scheduled, no image is pulled, no readiness probe fires. Worse, a webhook declaring sideEffects: Some is skipped for dry-run requests entirely, so its mutation is absent from the response. The preview is not merely partial; it is confidently missing a field that apply will add.

When dry-run alone is enough. It is sufficient when all three hold: no (known after apply) appears in the diff, the tool's apply path adds no steps beyond the API call the plan models, and the target enforces nothing the tool cannot see. A tag-only change on an existing Terraform resource, or a --dry-run=server apply of a ConfigMap with no webhooks in the path, meets that bar. Anything creating a resource whose name or ID is computed, anything with provisioners, anything behind controllers or quota, does not.

Failure modes and how to detect them.

  • Stale plan file. terraform apply plan.out does not re-plan, so drift between plan and apply is never caught. Re-run terraform plan and compare before applying.
  • Silently skipped webhook. Read the sideEffects field on every webhook in the path; Some means it will not run under dry-run.
  • Ansible false negative. Tasks that do not support check mode report skipped, and command/shell report changed regardless of what they would do. A task marked check_mode: false executes for real during --check.
  • Quota. A plan showing 20 nodes to add still fails at 15 if the account quota is 15. Only the API call reveals it.

Treat the preview as one gate. Follow it with a disposable integration run against a real target, then a canary on a representative slice, then explicit postconditions you assert after apply.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-4

How should an organization detect and remediate configuration drift?

Answer

I'd start by defining what drift means here: any difference between the intended configuration in your source of truth and what's actually running. The source of truth is usually Git for IaC: Terraform, Ansible, Kubernetes manifests. The actual state comes from cloud APIs, agents, or SSH.

Assumptions: you have some IaC, a change management process, and the ability to query actual state. Without a source of truth, you can't detect drift: you're just guessing.

Detection: compare desired vs actual on a cadence tied to criticality. For production security groups, every 5 minutes. For dev, hourly. Tools: AWS Config rules evaluate resource properties; osquery or Chef InSpec run on hosts; Kubernetes operators reconcile continuously. Agentless scans via cloud APIs are simpler but miss ephemeral changes. Agent-based gives real-time but adds overhead: for example, a 500-node fleet with a 5-minute hash check adds about 2% CPU per node.

Remediation: classify drift before acting. Categories: accidental (no change ticket), emergency (approved but not in IaC), malicious (attacker modified config), tolerated exception (known and accepted), stale input (inventory wrong), observer error (API rate limit). For accidental drift on low-risk resources, auto-remediate with Terraform apply or Ansible. For high-risk: say a security group opening 0.0.0.0/0 on port 22: require human approval. Always preserve forensic evidence: snapshot the resource, log the diff, and keep an audit trail. Repair in bounded cohorts: e.g., 10% of nodes at a time: to limit blast radius. Any legitimate change must be committed to the source of truth; exceptions get an expiry date and are tracked.

Trade-offs: Auto-remediation vs human review. Auto is fast and prevents drift accumulation, but can break emergency fixes. Use it for low-risk, well-understood drift. Human review is safer but slower; use it for stateful resources or when blast radius is large. Agentless vs agent-based: agentless is easier to deploy but can't detect in-memory changes; agent-based is more accurate but requires managing agents. Deciding criteria: criticality, blast radius, whether drift is in a change window, and whether the resource is stateful.

Failure modes: False positives from stale inventory, if your CMDB says a server exists but it was terminated, you get noise. Observer errors: API rate limiting causes incomplete scans. Competing writers: two automation tools fighting over the same resource cause flapping. Malicious drift: attacker modifies config to exfiltrate data; detection requires integrity monitoring and anomaly detection. Repeated drift on the same resource indicates a process gap: fix the process, not just the resource.

Here's a table comparing detection methods:

MethodLatencyCoverageOverheadBest for
Agent-based (osquery)1-5 minOS-level files, packages, processes1-3% CPU per nodeServers, compliance
Agentless API (AWS Config)10-15 minCloud resource properties$0.003 per config item recordedCloud infrastructure
GitOps reconciliation (Argo CD)3 min (default)Kubernetes manifestsController overheadKubernetes workloads

And a simple check using Terraform:

Shell
terraform plan -detailed-exitcode -out=tfplan
# exit code 0 = no changes, 2 = changes present
if [ $? -eq 2 ]; then
  echo "Drift detected"
  # optionally apply if auto-remediation enabled
fi

A worked trace: At 02:00, a scheduled scan runs. It finds a security group with an inbound rule 0.0.0.0/0 on port 22. The change ticket system shows no approved change. The drift classifier marks it as accidental. The auto-remediator applies the Terraform state, closing the port. It logs the event to Splunk. If the same drift appears again within 24 hours, it escalates to the security team.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-5

Resolve two automation systems that continuously overwrite the same setting.

Answer

What I'd say first

Two controllers writing the same field is not a tuning problem, it's an ownership problem. Each loop is individually correct: it reads current state, compares it to its own desired state, and writes. Neither knows the other exists, so each treats the other's write as drift and corrects it. The oscillation period is set by the slower loop, and it never converges because the two desired states are genuinely different. The resolution is to give the field exactly one writer: either by removing the field from the other system's desired state, or by partitioning so each system owns a different field.

Assumptions I'd state out loud: both systems are declarative controllers with a reconcile loop; the setting is a single scalar (replica count, instance size, retention days); and I can change what each system considers its desired state.

Why it oscillates: concrete case

Kubernetes HPA and Argo CD both managing spec.replicas on a Deployment.

writerfieldperioddesired state fromon drift
HPAspec.replicas via /scale15s (--horizontal-pod-autoscaler-sync-period)metrics (CPU/RPS)writes computed count
Argo CDspec.replicas180s (timeout.reconciliation)Git manifestreverts to manifest value if selfHeal: true

Trace: Git says replicas: 3. Load rises, HPA computes 8 at t=0 and writes it. Pods scale up. At t=180s Argo reconciles, sees 8 ≠ 3, reverts to 3. At t=195s HPA sees CPU still high and writes 8 again. Sawtooth 3→8→3 every ~3 minutes. Pods never reach steady state: each scale-up needs image pull plus readiness (~30-60s), so you pay for churn and run under-provisioned for most of each cycle.

The fix

Pick one writer per field. Three real options:

  1. Git owns the value, HPA off. Remove the HPA. Simple, but you lose metric-driven scaling.
  2. HPA owns the value, Git owns the bounds. Remove replicas from the manifest; keep minReplicas/maxReplicas in the HPA. Argo no longer sees drift on that field. This is the usual answer.
  3. If you can't edit the manifest, tell Argo to ignore that field:
YAML
ignoreDifferences:
  - group: apps
    kind: Deployment
    jsonPointers: ["/spec/replicas"]

Trade-off: option 3 hides the conflict rather than removing it. The manifest still claims to own replicas, so the next person reading Git is misled. Prefer 2.

Failure modes

  • Ignoring too much: a broad jsonPointers: ["/spec"] also masks real drift in image tags or env. Detect by mutating a field you do care about and confirming Argo still reports OutOfSync.
  • Disabling self-heal instead: drift accumulates silently everywhere. Alert on argocd_app_info{sync_status="OutOfSync"} == 1 for more than 15 minutes.
  • Two writers inside one window: last write wins at the API server. Detect in the audit log: two update calls on /scale and deployments within seconds, or kubectl get events showing repeated ScalingReplicaSet.
  • Cost of getting it wrong: a 3-minute sawtooth means pods churn ~20 times an hour; each cycle burns image pulls and leaves you under capacity during the ramp.

Close

Faster oscillation is not a resolution: it's the same conflict with a shorter period. One field, one writer.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-19

When should drift be reported but not automatically remediated?

Answer

Assumption: drift is a managed resource whose observed state (or state file) diverges from committed config, and the pipeline can either report it or apply the config. Report-only is the safe default because it is what the tooling does by construction: CloudFormation drift detection never modifies a stack, terraform plan mutates nothing, and Argo CD applies only when syncPolicy.automated is set or a human presses Sync. The real decision is which resources stay outside the auto-apply set once you opt in.

Auto-remediate only when all four hold: exactly one writer owns the resource, the revert is reversible and non-destructive, no human changed it under incident pressure, and committed config is authoritative for that field. Miss any one and report only.

SituationWhy auto-apply is unsafeDetect-only playSignal
A controller is the second writer: cluster autoscaler on ASG desired_capacity, HPA on Deployment /spec/replicas, Secrets Manager rotation on aws_secretsmanager_secret_versionBoth sides reconcile to their own desired state; the shorter loop wins, your apply is undone in seconds and drift re-fires on every checkExclude the field: Argo CD ignoreDifferences with jsonPointers: [/spec/replicas], Terraform lifecycle { ignore_changes = [desired_capacity] }same address drifts twice in 30 minutes
A human changed it during an incident: an SG opened to a debug CIDR, a listener patched at 02:40The diff is the mitigation; applying reverts the thing holding the service upFreeze applies for that service, attach the plan diff to the incident, require owner sign-off before repairchange author is a console identity, timestamp inside an open incident
The fix is destructive: plan shows replace or delete on a database, bucket or volumeTerraform replace means destroy then create; the data is gone before the replacement existsNever auto-apply; keep prevent_destroy = true, RDS deletion_protection = true, CloudFormation DeletionPolicy: Retainplan JSON change.actions contains delete
Config is not authoritative: a quota was raised, a cutover ran from another team, the provider does not round-trip the attributeApplying makes production worse in a way plan text does not revealReport, then reconcile config to reality by import or edit, then re-enable auto-applydiff on a field no Git commit touched
Blast radius exceeds the value of the fix: one stale tag needs a prod-wide applyA bad apply costs far more than the stale tagQueue it; batch the low-risk set weeklyopen drift count vs time-to-close

Enforcement mode is per resource, not per repo:

HCL
resource "aws_autoscaling_group" "web" {
  # autoscaler owns desired_capacity; Terraform still owns the launch template
  lifecycle { ignore_changes = [desired_capacity] }
}

Turn a plan into evidence rather than an apply (Terraform 1.x plan JSON):

Shell
terraform plan -out=tfplan -detailed-exitcode   # exit 0 no diff, 1 error, 2 diff
terraform show -json tfplan | jq -r '
  .resource_changes[]?
  | select(.change.actions != ["no-op"] and .change.actions != ["read"])
  | [.address, (.change.actions | join("+"))] | @tsv'
# delete or delete+create -> page the owner, do not apply
# update                  -> open a ticket
# controller-owned field  -> add to ignore_changes / ignoreDifferences

Worked trace, numbers assumed: Git pins desired_capacity = 6; the cluster autoscaler raised it to 40 for the 09:00 peak. The 09:12 check sees 6 against 40. Reporting costs one notification, and the owner either excepts the field or raises the Git floor. Auto-applying writes 6 and terminates 34 nodes; at 30 pods per node that is roughly 1,020 pods competing for capacity that just vanished, so they sit Pending and p99 climbs until the autoscaler re-adds nodes 3-10 minutes later, when the next check fires again on the same field.

Failure modes run both ways. Alert on controller-owned fields and one resource pages every cycle, 288 times a day at a 5-minute interval, the channel gets muted, and a widened security group goes unseen. Measure the share of drifts that revert on their own within one controller loop (seconds to minutes); those belong on the exclude list. The opposite failure is silence: ignore_changes = all or a wildcard ignoreDifferences hides the interesting diff too, so keep a small always-remediate set, ingress 0.0.0.0/0 on a non-public port, IAM Action: "*", a public bucket ACL, and count excepted attributes per resource so the list cannot grow unnoticed.

One trap inside detect-only itself: terraform apply -refresh-only copies observed values into state while the config still holds the old ones, so the next normal plan re-proposes the revert. It collects evidence; it does not reconcile.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

How should configuration changes that require restarts be managed?

Answer

Assumptions I would state first: 40 stateless replicas on Kubernetes behind a regional load balancer serving about 10k rps, gRPC clients holding long-lived streams, config split between a mounted ConfigMap and container flags. Different numbers change the arithmetic, not the method.

Core answer (first 90 seconds). Name the mechanism before the process: what does this change actually touch in the running process?

ClassExampleWhat happensDowntime
Reloadnginx upstream list, Envoy routes pushed over xDSmaster keeps the listening socket, spawns workers that read the new file, old workers finish in-flight requests0
Restart-Xmx, connection-pool size, in-memory truststoreprocess exits, socket closes, heap and caches rebuild from empty10-60 s per pod
Replacekubelet flag, kernel sysctl, anything baked into the imagenew pod or node identityminutes

That distinction is where most answers go wrong, because "we change the ConfigMap and it picks it up" is often false. Values injected with envFrom are resolved when the container starts, so a running pod never sees the new ones. A volume-mounted ConfigMap is rewritten on disk on the kubelet's sync period (default 1 minute) plus cache lag, but most frameworks read the file once at startup. Whether a change needs a restart is decided by how the process consumes config, not by whether the value is nominally dynamic.

Then the process: coalesce six small edits into one restart window instead of six cold starts, roll upstream-first (LB or DNS before the app, schema before the code that reads it), validate the new revision before it takes traffic, and batch by failure domain.

Failure modes, each with the signal that detects it.

  • Split fleet. Half the pods on revision 41, half on 40: two behaviours at once, one accepts a new JSON field, one rejects it. Detection: a per-pod config_revision gauge; alert when the distinct-value count is greater than 1 for more than 5 minutes. That metric turns rollback into a decision instead of a guess.
  • Ready before loaded. The readiness probe passes before config and pools are warm, so the pod serves with defaults. Symptom: 5xx concentrated on newly Ready pods for roughly 90 s, then quiet. Fix: gate readiness on config load plus one successful dependency call.
  • Cold-start stampede. Illustrative figures: a 200k-entry cache taking 90 s to warm, with 10 pods restarting at once, moves DB reads from 3k to 9k qps. Kubernetes Deployment defaults are maxUnavailable: 25% and maxSurge: 25%, so with 40 replicas that is 10 pods down and 10 surging at any moment. If 30 of 40 are Ready and traffic is flat, each survivor takes 33% more; check p99 headroom before the window, not during it.
  • A rollout that stalls on capacity. A surge needs a free slot. With the cluster at its node-group maximum and maxSurge: 1, the new pod sits Pending, kubectl rollout status reports it stuck, and the pod event reads insufficient cpu; no autoscaler can help because the group is capped. (maxUnavailable: 0 with maxSurge: 0 is not an option either: the API rejects that pair.) At progressDeadlineSeconds (default 600 s) the Deployment is marked failed and stays failed; kubectl rollout undo is a step you take, it does not revert by itself.
  • Drains in the same maintenance window. A Deployment rolling update deletes old pods directly and never calls the eviction API, so a PodDisruptionBudget does not slow the rollout down. Drains do: minAvailable: 100% on a 40-pod Deployment hangs kubectl drain during the next node maintenance until it times out. If you set a budget, expect it to bite there instead.
  • Cut streams. terminationGracePeriodSeconds defaults to 30 s; a gRPC stream with no preStop drain gets reset. Detection: the client reconnect rate should show one clean step, not a spike.

Recovery. Keep the last known-good config as an immutable named object, so reverting is a reference change plus one rollout, roughly 3 minutes at these numbers, and decide in advance who can authorise that at 3 a.m.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

Design secure secret use in configuration automation.

Answer

Assumptions. The automation is a CI/CD pipeline plus config management (Ansible, Terraform) deploying to cloud VMs or Kubernetes, and the secrets are DB passwords, API tokens and TLS keys. If your automation runs on a laptop with no platform identity, jump to the last paragraph.

The 90-second answer. Delete static secrets wherever the workload can prove what it is. A cloud workload gets an IAM role (EC2 instance profile, ECS task role, EKS IRSA projected token) and STS mints the credential at start: 1 hour by default, up to 12 hours if the role's max session duration allows it. Nothing lands in git, nothing in the config repo, nothing to rotate by hand. For secrets with no identity-based equivalent (third-party API keys, passwords for non-cloud engines), broker them: Vault's database secrets engine issues a per-deploy user with default_ttl=1h, max_ttl=24h, revoked by lease ID. The automation holds a lease, not a durable secret.

Why identity beats a stored secret. A static secret's exposure window is "until someone rotates it": weeks. A brokered credential's window is its TTL, and revocation is one API call against the lease. The mechanism matters: the credential is derived from a platform attestation (instance metadata, a projected service-account token with expirationSeconds: 3600, a SPIFFE SVID), so stealing it requires already running code as that workload. At which point the attacker has the workload's permissions anyway.

ApproachLifetimeBlast radius if leakedDependency
Static value in Vault KV, injected as env varuntil rotated (weeks)full DB access until rotationVault at deploy time
Vault dynamic DB creds (default_ttl=1h)1h1h, revocable by lease IDVault at every deploy/restart
Cloud IAM role (IRSA / instance profile)1h STS, auto-renewedscoped to the role policy; no secret to stealcloud API only

Keeping the automation's own surfaces clean. Ansible: mark every task that touches a secret no_log: true, including the one that renders the file, or the value appears in the callback output. Terraform: state is plaintext for anyone who can read it, so keep it in S3 with SSE-KMS and a bucket policy denying GetObject to everything but the CI role, and prefer ephemeral values so the secret never enters state at all.

YAML
- name: Issue short-lived DB credentials
  community.hashi_vault.vault_database_credentials:
    url: https://vault.internal:8200
    mount_point: database
    role_name: app-readonly
    auth_method: approle
  register: db_creds
  no_log: true

- name: Render app config
  ansible.builtin.template:
    src: app.env.j2
    dest: /etc/app/app.env
    mode: "0600"
  no_log: true

Failure modes and how you catch them.

  • Secret in a CI log. Detect with gitleaks or trufflehog as a pre-commit hook plus GitHub push protection; cost is a few false positives per week. Rotate on any hit: assume the log is public.
  • SSRF reaching instance metadata. Enforce IMDSv2 with hop limit 1; detect via CloudTrail AssumeRole/GetSessionToken from an unexpected source IP.
  • Rotation breaks consumers. Use a dual-credential window and alert when DB auth failures exceed 1% of connections for 2 minutes. Long-lived connection pools that can't reconnect are the usual casualty: add reconnect logic before shortening TTLs.
  • Vault unreachable at 03:00. The play fails at the credential task and the host keeps its previous config, so the deploy is blocked rather than half-applied. Alert on vault.core.unsealed == 0 and on the task's failure rate. A lease cache with a 15-minute buffer buys you an outage window but extends exposure by the same 15 minutes.
  • Terraform state read by the wrong principal. Scan with checkov or tfsec in CI; treat any state reader as a secret holder.

When not to do this. If the workload can't present a platform identity (an on-prem cron box, a third-party SaaS) brokering adds a hard runtime dependency for little gain. Fall back to a KMS-encrypted store with automated rotation and a documented break-glass path. Separate decryption authority only when the CI runner is genuinely lower-trust than the runtime; if the same team can already deploy arbitrary code to prod, the separation buys nothing.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-6

Design a configuration data hierarchy across environments.

Answer

Core answer (first 90 seconds)

I'd assume a Kubernetes-based service fleet, config rendered at deploy time by Kustomize overlays, secrets resolved separately. The design is one precedence chain, deep-merge semantics, strict validation, and a rendered artifact that names the winning layer for every key.

Precedence, lowest to highest:

  1. Code defaults: compiled in, always present
  2. base/: shared across all environments
  3. env/<env>/: dev, staging, prod
  4. region/<region>/
  5. service/<name>/
  6. asset/<id>/: one shard, one tenant, one node pool

Merge rule: maps merge recursively; scalars and lists replace. That's Kustomize's default, and it's the rule that bites people.

Trace: db.pool.maxSize for checkout in prod/us-east-1, shard 7:

layervalue
code default10
base20
env/prod40
region/us-east-160
service/checkout80
asset/shard-7120

Effective value 120. The provenance report prints that whole chain, so "why is the pool 120?" is one command, not a Slack thread.

Failure modes

  1. Silent list replacement. env/prod sets allowedCidrs: [10.0.0.0/8]; region/us-east-1 sets [192.168.0.0/16]. Lists replace, so prod's entry vanishes. Symptom: traffic from 10/8 starts getting 403s after a region overlay lands. Detection: CI renders the overlay and diffs against the previous render; any list whose length shrinks fails the build.

  2. Key typo. maxsize instead of maxSize: without strict validation the default 10 silently wins, and p99 climbs once concurrency passes 10. Detection: JSON Schema or CUE validation with additionalProperties: false, run in CI and at boot. Fail the build, not the request.

  3. Precedence inversion. Two layers set the same key and nobody knows which wins. Detection: the provenance report flags any key set in more than two layers for review.

  4. Version skew. Config written for schema v3 loaded by a v2 binary. Detection: config carries schemaVersion; the service refuses to start on mismatch. Fail at boot, not at first request.

Trade-offs

The alternative is a wholesale fork per environment: a complete config tree for dev, staging, prod. It's easier to reason about and needs no merge tooling, but every fix is applied N times and the trees drift; the drift stays invisible until prod behaves differently from staging for a reason nobody can find. I'd take layers when there are more than two environments and more than a handful of services; below that, the tooling cost isn't worth it.

Dynamic config (etcd, Consul, a feature-flag service) removes the redeploy for a value change, but adds a runtime dependency and a staleness failure mode: a node that can't reach the store serves the last cached value, so you need a TTL and a metric on cache age.

Secrets never enter this tree. The layer holds a reference (secretRef: prod/checkout/db), resolved at deploy by External Secrets Operator or a Vault agent. The rendered artifact contains the pointer, not the value, so it's safe to commit and diff.

Finally, rendering is deterministic: same inputs, byte-identical output. Hash the render and record it with the deploy, so "what config was live at 14:03" is a lookup, not an archaeology project.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

How do configuration management and immutable images complement each other?

Answer

The 60-second answer

Assume a fleet of Linux VMs on one cloud, images built in CI, and a config tool you already run. The two aren't alternatives; they're two stages of one pipeline, and the split is decided by a single question: does this value differ between two instances of the same role, or change more often than I want to rebuild an image?

If no, it goes in the image. Kernel, package versions, the app binary, systemd units, base OS hardening. Packer bakes it, the AMI is the artefact, you version it and roll forward.

If yes, it goes in configuration management. Environment name, database endpoint, feature flags, TLS certificates, credentials. Those are supplied at boot by cloud-init reading instance user-data, or by the SSM agent pulling from Parameter Store, and rotated at runtime.

The rule that keeps this from breaking: one writer per file. Pick the owner for /etc/app/config.yml and never let the other layer touch it.

Why the split matters: mechanism

Drift exists because a running instance is mutable by default: someone SSHs in, edits nginx.conf, reloads. The image doesn't know. The next instance launched from the same AMI comes up without the change, so you now have two behaviours behind one load balancer. Immutability doesn't prevent the edit; it makes the edit not survive, which converts a silent divergence into a visible one at the next replacement.

Two writers collide because both are declarative and neither knows about the other. cloud-init writes the file at first boot; an Ansible run at 03:00 rewrites it from a template. Whichever ran last wins, and the loser's run reports "changed" forever: a non-idempotent task is the tell.

Blast radius is the real trade-off. A bad value baked into an image is inert until instances are replaced, so a rolling ASG at, say, 10% per hour gives you hours to catch it, but every replacement is poisoned. A bad value pushed by config management hits the whole fleet in one run. Bake for safety of rollout, push for speed of correction.

Ownership table

SettingOwnerWhy
OS packages, app binary, systemd unitImage (Packer)Identical on every instance; slow to install at boot
Environment name, DB endpoint, feature flagscloud-init user-data / SSM Parameter StoreDiffers per environment
TLS certs, DB credentials, API tokensSecrets Manager + runtime fetchExpire; baking leaks them into every AMI copy
Stateful data, license-locked binariesNeither: externalise or snapshotCan't be rebuilt from a recipe

Failure modes and how you see them

  • Silent drift. Detection: SSM State Manager association compliance, or an Ansible --check --diff run that reports changes on a host that should be clean. A clean host reports changed=0.
  • Config collision. Detection: file mtime newer than instance launch time, or a task that reports changed on every run.
  • Boot-time dependency. cloud-init installing packages at boot means a repo outage or slow mirror becomes a failed scale-out. Detection: cloud-init status --long showing cloud-final past your launch timeout; instances stuck in pending.
  • Stale secret in an image. Detection: secret scanner in the image build pipeline; a rotated credential that still works from an old AMI.

When not to do this

If your instances are long-lived and hand-tuned (a licensed appliance, a database you can't rebuild) full immutability is a fiction. Use config management with drift detection and accept the mutability. And don't bake anything you'd have to rebuild more than weekly; that's the signal it belongs in runtime config.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-24

Build a test strategy for a reusable configuration role.

Answer

Assumptions I'd state first. Ansible role, published on Galaxy or inside a collection, included by other teams. Targets Linux: Debian/Ubuntu and RHEL 9 families. Writes a config file, drops a systemd unit, takes one secret, and must be safe to re-run on a host an operator has already hand-tuned.

The answer: three layers, cheapest first.

Layer 1: static, every push, seconds. ansible-lint --profile production (production is the strictest of the min/basic/moderate/safety/shared/production set), yamllint over defaults/, vars/ and the Molecule scenario, ansible-playbook --syntax-check, and the role's meta/argument_specs.yml (ansible-core 2.11+) so invalid input fails before a single task runs. This is where unquoted values, command without changed_when, and a missing no_log get caught instead of argued about in review.

Layer 2: Molecule on containers, every push. Create, converge, idempotence, verify, destroy. The idempotence step earns its keep: it converges a second time and fails if any task reports changed. That one check catches templating that appends instead of replaces, command tasks missing proper changed_when, and handlers that fire on every run. Verify with Testinfra or Goss asserting state rather than output: file contents, mode 0600 on the secret file, unit enabled and started, service answering on its port.

Layer 3: one canary per platform per release, on a real VM. Containers do not run systemd as PID 1 the way a VM does and share the host kernel, so SELinux context, firewalld, and distro repo behaviour are invisible. The canary is the only place you learn the RHEL 9 unit fails on an SELinux denial or that a repo GPG key rotated.

Failure modes and how they show up:

failuresymptomcaught by
non-idempotentsecond converge reports changed=NMolecule idempotence step
secret leakcanary secret in CI log, or config world-readableno_log: true, log grep, Testinfra mode assertion
drift overwriterole clobbers an operator's manual editprepare/side_effect with a pre-modified host
interruptionconverge killed mid-run leaves half-written configkill the run, re-run, assert convergence
core driftapt_key removed in a newer ansible-corematrix across the versions you claim
handler misfirerestart loopcompare systemctl show -p ActiveEnterTimestamp before and after: advances exactly once

Trade-offs. Molecule + Docker per commit: tens of seconds a cell, free, blind to systemd and SELinux. ansible-test --docker: what ansible-core collections use, gives sanity/units/integration targets, more setup than a standalone role usually justifies. Real VMs via the Molecule delegated driver or a cloud runner: catches everything, costs minutes and money, so run once per release rather than per push. The rule is to run the cheapest layer that can actually fail for this change: task logic, containers; unit, package repo or firewall, canary. A hand-run checklist is not a layer, because it leaves no artefact to diff between role versions.

Sizing. Two platforms x two ansible-core versions = 4 cells at roughly 75 s each (create, converge twice, verify, destroy) is about 5 minutes serialised, under 2 on 4 runners. Two VM canaries add about 5 minutes each and catch the class of bug no container will.

Evidence. Publish the compatibility matrix in the repo keyed by role version (role version, ansible-core floor from meta/main.yml, distro, result, link to the CI run) beside the canary logs. A consumer then knows which role version is safe on their fleet without reading the tasks.

What would change this. If the role only renders files and restarts nothing, drop layer 3 and the handler check. If it drives a cloud API instead of a host, containers prove nothing and the canary becomes layer 2. If consumers run it in check mode, make --check --diff a first-class CI target and expect to fix every command task that lies about changing.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-7

How would you govern third-party configuration modules?

Answer

Clarify, then answer. "Third-party configuration modules" means Terraform modules, Helm charts, Ansible roles, Chef cookbooks: code you didn't write that runs with your cloud credentials and can create, modify or delete infrastructure. The governance question is what must be true before that code runs against production, and what you do when it turns out to be wrong.

Assumptions I'd state up front: modules come from a public registry or a git repo; they execute in CI with real credentials; nobody is going to read every line of every module.

Core answer: three gates: pin, inspect, canary.

Pin. Every module reference is immutable and verifiable.

  • Terraform: source = "git::ssh://git@github.com/acme/vpc.git?ref=9f3c1a2". A commit SHA, not a tag, because tags are mutable. Registry modules get an exact version = "5.1.2", not ~> 5.1.
  • Helm: helm package --sign --key release --keyring ~/.gnupg/secring.gpg emits a .prov; helm install --verify refuses a chart whose digest doesn't match it. Chart.lock pins subchart digests.
  • Ansible: requirements.yml with version: 1.4.0. Galaxy has no signature verification, so pin the SHA and vendor the role.

Inspect what the module does with privilege, not what it claims.

  • terraform plan -json piped to OPA/Conftest: fail on aws_iam_policy with "Action": "*", on local-exec/remote-exec provisioners, on data sources hitting external URLs.
  • Diff the new plan against the previous version's plan for identical inputs. A changed default (encrypted = false, publicly_accessible = true) is the silent regression that matters, and it never appears in a changelog.

Canary. Apply to one non-prod account or one region, watch for a day, then promote.

Trade-offs. Vendoring versus registry pinning: copying the module into your repo means no network fetch at plan time and full review control, at the cost of manually merging upstream fixes. Worth it for anything touching IAM or networking, overkill for a module that just names an S3 bucket. Allow-list versus block-list: an allow-list of approved sources is safer but every new source becomes a ticket; a block-list is faster and misses the next typosquat. Governance also has a floor: a five-person team with one internal module repo needs CODEOWNERS review and pinned SHAs, not SLSA provenance and a signing ceremony.

Failure modes and how you catch them.

  • A module update silently widens a security group to 0.0.0.0/0. Caught by the plan diff plus policy check, not by trusting the release notes.
  • A module's destroy deletes a resource it didn't create: a shared bucket. Caught by running terraform plan -destroy in a sandbox before you ever need it.
  • A module pins a provider version that conflicts with the root, so terraform init upgrades a provider you didn't intend. Caught by diffing .terraform.lock.hcl in the PR. Note the lock file covers providers, not modules: module pinning is entirely on you.
  • A typosquatted registry module. Caught by the allow-list plus terraform providers lock hashes.

Removal plan. Because you pinned a SHA, rollback is a one-line change. Keep the resolved artifact, the vendored directory or the .terraform/modules copy, so a registry deletion doesn't break a rebuild.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

How should obsolete configuration and modules be retired?

Answer

The 90-second answer. Retirement is two decisions, not one: remove the declaration, and decide the resource's fate. Destroy it, hand it to another owner, or leave it running unmanaged on purpose. Most incidents come from conflating those. So I'd classify each item as stateful (data, DNS records, IAM roles other things assume) or recreatable (a stateless module, a feature flag), because that sets the blast radius and the rollback.

Assumptions: Terraform-managed infrastructure, a Kubernetes CRD, and a feature flag, since the mechanism differs per surface.

Why declarative removal orphans state. In Terraform, deleting a resource block from config makes the next terraform plan propose a destroy: Terraform diffs config against state and destroys what is no longer declared. If you want to keep the resource but stop managing it, you must first terraform state rm aws_instance.foo (or, from Terraform 1.7, add a removed block with lifecycle { destroy = false }), then delete the block. Skip that and you either destroy something you meant to keep, or, if someone already removed it from state, you leave an unmanaged resource billing silently.

Three dispositions, one deciding criterion.

DispositionCommandUse whenReversible?
Destroyremove block, terraform applyrecreatable, no datayes, re-apply
Orphanterraform state rm then remove blockanother team takes ownershipyes, terraform import
Freezekeep block, add lifecycle { prevent_destroy = true }stateful, pending migrationyes

Deciding criterion: does the resource hold state that cannot be rebuilt from code? If yes, never destroy it in the same change that removes the declaration.

Worked trace. Config has module "legacy_queue". Step 1: terraform state list | grep legacy_queue → shows 4 resources. Step 2: terraform state rm module.legacy_queue.aws_sqs_queue.main → state now has 3; the queue still exists in AWS. Step 3: delete the module block. Step 4: terraform plan → "No changes." The queue is now unmanaged: nothing will destroy it, and nothing will recreate it. That is the intended freeze. If instead you deleted the block first, terraform plan would show - aws_sqs_queue.main (destroy), and apply would delete the queue and its messages.

Failure modes and how you catch them.

  • Silent orphan spend. An orphaned resource keeps billing. Detect with a cost-anomaly alert or a periodic terraform plan in CI that should be empty; blast radius is money, not availability.
  • Recreated drift. A controller or a second pipeline recreates what you deleted. Detect with AWS Config or a drift-detection job; if the resource reappears within one reconcile loop, you removed the wrong layer.
  • Cascading CRD deletion. kubectl delete crd widgets.example.com deletes every custom resource of that type, and finalizers can hang it. Blast radius is all tenants; detect via the API server audit log, and check kubectl get crd widgets.example.com -o jsonpath='{.metadata.finalizers}' first.
  • Flag removed while code reads it. The SDK serves the default variation, silently. Detect via flag-evaluation metrics showing the key still being read after removal.

Retain the audit trail (the state rm output, the plan, and the ticket) for at least one quarter, and record the successor or the accepted absence so the next person does not re-add it.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-11

Design exception management for secure configuration baselines.

Answer

The core decision: where the exception lives

Assume a config scanner already runs (AWS Config rules, Azure Policy, or a CIS-CAT-style agent), thousands of assets across several product teams, and a baseline like CIS. The first decision is not the fields: it is where the exception is stored. If it lives in a Jira ticket, the scanner keeps flagging the asset, the team gets alert fatigue, and someone eventually suppresses the finding wholesale. You lose the signal. So the exception must be a first-class object the scanner reads at evaluation time, and the scanner must emit two numbers, never one.

The record

fieldexamplewhy it matters
idEXC-2024-0417stable key the scanner joins on
scope selectorenv=prod AND app=paymentsresolves to assets at eval time, not a frozen host list
controlCIS AWS 2.1.1the exact rule ID, not "S3 hardening"
allowed statepublic_access_block=falsethe deviation, bounded
owner / approverteam-payments / security-engaccountable human, separate from requester
compensating controlWAF + object-level deny policywhat actually reduces the risk
start / expiry2024-06-01 / 2024-09-01 (90d)mandatory end

Two compliance numbers

The scanner computes raw compliance (assets passing the baseline) and effective compliance (raw + assets covered by a live exception). Report both. Blending them hides the debt; reporting only raw makes the exception pointless.

Worked figure (hypothetical): 4,000 assets, 120 live exceptions. Raw = 91.2%, effective = 94.1%. Now group exceptions by control. If 2.1.1 is excepted on 90 of its 400 in-scope buckets (22.5%), that is above a 20% review threshold: the baseline is wrong for this environment, so fix the baseline rather than the fleet.

Trade-offs

Centralized vs delegated approval. Security approving every exception works at ~10/week. At scale it bottlenecks and turns into a rubber stamp. Delegate: a team lead approves up to a risk budget (say 5 open exceptions), security reviews the aggregate weekly. Costs an audit trail; buys throughput.

Fail-open vs fail-closed at expiry. Fail-closed, at expiry the asset reverts to non-compliant and pages the owner, is the correct default. But if the exception was load-bearing (that public bucket serves traffic), fail-closed at 00:00 breaks production. So alert at T-14 and T-3 days, and route late renewal through a logged break-glass re-approval, never a silent auto-renew.

Failure modes and detection

  • Exception sprawl. Detect via exception count per control ID; >20% of in-scope assets excepted flags a baseline defect. Cost of missing it: the baseline erodes to "whatever teams already do."
  • Stale exceptions. The scanner stops reading the store, or the two drift. Detect with a nightly reconciliation: every exception past expiry must suppress zero findings; alert on any mismatch.
  • Scope drift. A tag-based selector silently stops matching after a re-tag: the asset now fails, or worse, keeps the exception after moving to a more sensitive environment. Detect by logging which assets each exception matched at eval time and diffing week over week.

What would change this

Under ~50 assets, a spreadsheet plus a calendar reminder is fine; the machinery earns its keep at scale. If your scanner cannot read external state, you are forced into a separate GRC tool, and then reconciliation between the two is the whole job.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

Design ownership and approval for high-risk configuration settings.

Answer

What I'd say first

Assume AWS plus Kubernetes, infrastructure in Terraform, review in GitHub, one platform team. The question isn't who owns a setting: it's which changes can hurt you before anyone notices, and who has to agree before they land. So I tier by blast radius and reversibility, not by service.

TierExamplesApprovalEnforcement
1IAM trust policies, SCPs, KMS key policies, CloudTrail config, any SG rule with 0.0.0.0/0, ClusterRoleBinding to cluster-admin2 approvers, at least one from security, self-approval blockedadmission deny + SCP deny
2namespace RBAC, ingress annotations, HPA limits, retention settings1 reviewer from the owning teamCI policy check
3app config, feature flags, log levelsauthornone

Why the split works

Approval only means something if the approver can't be the author. GitHub's environment protection rules have prevent_self_review; without it, a single engineer with write access pushes and approves, and the control is a speed bump. The approver's job is narrow: read the rendered object and ask what it grants. That's why the review artifact should be the plan output, not the diff.

Policy validation catches what review misses because admission controllers evaluate the rendered object, not the intent. A Terraform plan can be valid HCL and still open port 22 to the world. Gatekeeper and Kyverno see the final object. But only in enforcing mode: Kyverno's validationFailureAction: Audit logs the violation and admits the resource anyway.

A trace of the failure this is meant to stop

  1. Engineer adds 0.0.0.0/0 → 22 to a security group under infra/network/.
  2. .github/CODEOWNERS has a syntax error on line 3. GitHub doesn't detect the file at all, so no reviewers are requested.
  3. CI runs terraform plan: valid HCL, plan succeeds.
  4. Merge, apply, rule is live.
  5. AWS Config's restricted-ssh managed rule flags it on the next configuration change, minutes later.

Two independent controls would have stopped this at step 2 or 3. One typo removed both.

Failure modes and how I'd detect them

  • Approval theater. Query the review API for merged PRs where the approver equals the author. Non-zero means the control is decorative.
  • Policy in audit mode. Count violations against admissions. Violations with no denials means you're logging, not blocking.
  • SCP blind spot. SCPs don't apply to the AWS Organizations management account. Test the same deny from there.
  • Break-glass that never expires. An IAM role's MaxSessionDuration defaults to 1 hour and can be set to 12. Alert on every AssumeRole for that role ARN outside a declared incident.
  • Drift. Console edits never appear in a plan. Run terraform plan nightly and alert on a non-empty diff.

When not to add friction

Two-person review on every change creates a queue, and a queue is what makes engineers route around the control: they ask for a broader role so they stop needing approvals. The criterion is blast radius and reversibility. A change you can revert in a minute with no data loss doesn't need two approvers. Deleting a KMS key or an S3 bucket policy does. And tier 2 should be owned by the service team, not central security: if security is the only approver for 200 repos, PRs sit for days and the tier collapses.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

How would you prevent a bad baseline from spreading consistently?

Answer

What I'd say first

The question is underspecified, so I'd pin it down before answering. I'll take "baseline" to mean a versioned reference artifact a convergent system pushes to every target (a golden container image, a config default set, an IaC module, a schema version) and "spreading consistently" to mean the rollout is deterministic, so every target ends up matching the bad baseline rather than a random subset. That determinism is the whole problem: a flaky bad change self-limits, a convergent one reaches 100%.

So the answer isn't "review harder." Review catches intent, not effect. You break the spread in three places: make the artifact immutable and digest-pinned so nothing propagates by name; stage the rollout behind a promotion gate with a bounded blast radius; and make achieved state verifiable and reversible.

Why it spreads

A reconciler (Argo CD, Flux, Terraform, Puppet) compares desired to actual and drives actual to desired on every loop. Merge a bad baseline and the next reconcile applies it to every target that hasn't converged yet. Re-running doesn't help: idempotency reproduces the same bad intent instead of correcting it. The retry loop is the distribution mechanism.

Controls, and what each one actually stops

ControlStopsDoesn't stop
Immutable digest pin (sha256), promote by digestTag mutation: latest re-pull serving different content under one nameA bad digest that is bad everywhere
Canary 1% → 5% → 25% → 100% with bake windowsFleet-wide convergence before anyone sees the effectA canary that isn't representative
Automated analysis on SLOs (error rate, p99, saturation)Human-in-the-loop detection latencyMetrics that don't cover the failure
maxUnavailable/maxSurge, Terraform -parallelism, sync wavesSimultaneous convergence of all targetsSlow-burn bugs under the threshold
Pause/abort plus revert-by-new-commitContinued spread after detectionForward-only schema migrations

Worked trace (hypothetical: 200-node fleet, Argo CD reconciling every 3 min)

Bad baseline merged 14:00. No gate: all 200 nodes converge by 14:03, and the 14:06 reconcile re-asserts it. With a canary: 2 nodes at 14:00, 15-minute bake. Automated analysis trips at 14:12. P99 goes 40 ms → 180 ms as the new default connection pool of 20 saturates. Rollout aborts at 14:12, the revert commit lands 14:14, and those 2 nodes reconcile back by 14:18. Blast radius 2/200 = 1%, exposure 18 minutes.

Where this is wrong

Canary gating buys you a slow rollout, a 4-hour staged rollout where 10 minutes would do, plus duplicate capacity during the bake. Digest pinning means you can't hotfix by retagging; every fix is a new artifact and a new promotion. And if the baseline is a forward-only schema migration, rollback isn't a redeploy: you need expand/contract so old and new code both run against the new schema, or you're choosing between a bad schema and data loss.

Failure modes to name

  • Canary not representative: 1 node in one AZ, bug only fires on a specific instance type. Detect by comparing canary and fleet tag distributions, not just SLOs.
  • Silent partial convergence: apply fails on 3 of 200, retry loop hammers. Detect by alerting on reconcile failures and drift age, not on apply success.
  • Achieved state ≠ declared state: the controller reports Synced while a mutating webhook rewrites the object. Verify achieved state independently: read the running config back, don't trust the apply log.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-9

Plan a high-risk SSH configuration rollout.

Answer

The 90-second answer

Assume OpenSSH 9.x on Linux under systemd, config in /etc/ssh/sshd_config plus drop-ins, and an out-of-band console (IPMI, cloud serial, or a second sshd on a different port) that does not depend on the config you are changing. The rollout is: prove the new config is valid and does what you think, prove you can still get in when it doesn't, then widen by failure domain with a numeric abort threshold.

Three things make SSH different from a normal config push. The listener and the sessions are separate processes: systemctl reload sshd sends SIGHUP, the master re-execs and re-reads config, and every established session keeps running under the old image. That is why reload beats restart, but it also means a bad config is invisible until someone opens a new connection. A failed reload can kill the listener outright: if the re-exec'd daemon can't parse the config it exits, and you have no listener at all while your existing sessions still look healthy. And sshd -t only proves the file is valid to the daemon; it says nothing about whether AllowGroups names a group that exists.

Pre-flight

# 1. Validity, against the file you are about to install
sshd -t -f /etc/ssh/sshd_config.new

# 2. What the daemon actually resolves, before and after
sshd -T > /tmp/sshd.before
install -m 600 /etc/ssh/sshd_config.new /etc/ssh/sshd_config
sshd -T > /tmp/sshd.after
diff /tmp/sshd.before /tmp/sshd.after

# 3. Per-connection resolution — does the Match block fire for this user?
sshd -T -C user=alice,addr=10.0.0.5,host=bastion

sshd -T is the one that earns its keep: it prints the effective config after Include and Match resolution, so the diff shows the delta you actually shipped, not the one you intended. -C answers "what does alice get from 10.0.0.5" without guessing at Match precedence. (The unit is ssh.service on Debian/Ubuntu and sshd.service on RHEL.)

Rollout

stagecohortabort if
canary1 non-critical hostany fresh login fails that succeeded before
ring 15% of hosts, one rack>1% of new connections rejected, or any host loses all admin access
ring 225%, one AZauth failure rate >2× the pre-change baseline
fullremainder—

Pause at each ring for a full business day. SSH logins are bursty; a 30-minute soak tells you nothing. Keep the previous sshd_config on disk and revert by re-installing and reloading, not by hand-editing.

Failure modes

  • Semantically valid, operationally wrong. PermitRootLogin no or an AllowGroups typo parses fine and denies everyone. sshd -t passes. Detect it by opening a second, independent session and logging in as a real user before you close the one you have.
  • Bad reload kills the listener. Config that fails at re-exec leaves no daemon. Detect with systemctl status sshd and ss -ltnp | grep :22 immediately after reload; recover from console.
  • AuthorizedKeysFile points somewhere empty. Key auth fails for everyone while password auth still works and masks it. Detect with a key-only login from a host you don't normally use.
  • Lockout by attrition. You keep the old session open, it survives, and you never test a new login until it times out. This is the most common way people lose a fleet.

When this is wrong

If you have no out-of-band console and no second sshd, do not do a fleet-wide auth change. Build the break-glass path first, a separate sshd on another port with PermitRootLogin prohibit-password and a key you have tested, and only then roll. And if the change is cosmetic (banner text, LogLevel), the ring structure is overkill; sshd -t plus a reload on one host is enough.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

Recover from a partially applied fleet-wide configuration change.

Answer

First 90 seconds

Freeze, then look. Cancel running playbooks, disable the CD trigger, lock the config repo so nobody stacks a "fix" on a half-applied state. Then build a state map before touching anything.

The map comes from a version stamp the playbook writes as its last task, so a host only reports the new SHA once its whole apply succeeded:

YAML
- copy:
    content: "{{ deploy_sha }}\n"
    dest: /etc/app/deploy-version
ansible all -m command -a "cat /etc/app/deploy-version" -o

One line per host: 50 return the new SHA, 140 the old, and 10 either fail (rc=1, file missing) or don't answer at all. 50 + 10 + 140 = 200, so nothing is unaccounted for. The 10 are the ones to triage over SSH, not with another push; drain them at the load balancer first.

Why the fleet split: Ansible drops a failed host from the play and keeps going with the rest. With default serial (all 200 at once) and no max_fail_percentage, one bad host doesn't stop the other 199.

Rollback or forward

QuestionRollbackForward fix
Change idempotent?irrelevantrequired
Irreversible step (dropped column, revoked key)?blockedforced
Old and new hosts coexist (same schema, same contract)?yes → roll back in batchesyes → roll forward in batches
Time to a consistent fleetfast if config-onlyslower, no version skew

If a migration already ran, rolling back config alone leaves the app talking to a schema it doesn't expect: go forward. Config-only and the new config is broken: roll back.

Forward fix, traced

YAML
- hosts: web
  serial: [1, 5, 20, "100%"]
  max_fail_percentage: 20
  tasks:
    - template:
        src: nginx.conf.j2
        dest: /etc/nginx/nginx.conf
        validate: "nginx -t -c %s"
      notify: reload nginx

Trace: batch 1 is a single host. validate runs nginx -t against the rendered file at a temp path before it is moved into place, so a syntax error fails the task and leaves the old file untouched. Pass, and batch 2 is 5 hosts, then 20, then the remaining 174. If failures cross 20%, max_fail_percentage aborts the play and the rest of the fleet stays on the old config: blast radius bounded to the batch in flight. A list for serial gives the canary ramp in one run instead of four manual invocations.

Failure modes

  • Split-brain: 50 new, 140 old. Detect with the version map plus a per-version error-rate panel. Cost: writes land on two schemas.
  • Rollback blocked by migration: app won't start, logs show "unknown column". Cost: outage runs until the migration is reversed.
  • Idempotency bug: lineinfile without regexp appends a second server_name line every run; nginx -t still passes. Detect by diffing the rendered file across two runs.
  • Credential rotation: rollback restores a revoked key. Detect as 401s from the DB. Cost: total DB outage.

After

Keep the version stamp, set serial and max_fail_percentage in the base playbook, and add a post-batch health gate so the next partial apply aborts itself.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-1

Design configuration management for a mixed Linux fleet.

Answer

Assume 200–2000 Linux hosts, mixed RHEL 8/9 and Ubuntu 22.04/24.04, a few hundred reachable only through a jump host, no existing config management. My answer: one declarative pull-based system as the source of truth, with Ansible kept for orchestration and one-shot remediation. Pull agents converge on a schedule and keep enforcing when the control plane is down; push-only means a host that misses the run stays wrong until someone notices.

Transport decides everything else.

Ansible (push/SSH)Puppet (pull/agent)Salt (pull/agent)SSM (agentless, AWS)
transportSSH, no agentHTTPS 8140ZeroMQ 4505/4506SSM agent → AWS API
default cadenceon demand30 min runinterval60 s loop_intervalon demand / State Manager
self-healnoyesyesyes
secretsVault/SOPS at run timehiera-eyaml, Vaultpillar + GPG/VaultParameter Store SecureString

The arithmetic that decides it: 500 hosts, Ansible's default forks = 5, roughly 1.5 s of SSH plus fact-gathering overhead per host per task. A 20-task play is 500/5 × 20 × 1.5 s ≈ 50 minutes of wall clock. Raise forks to 50 with ControlPersist and pipelining and it drops to ~5 minutes, but now one box is fanning out to 500 hosts and nothing enforces state between runs. Puppet spreads the same work across a 30-minute window with no operator waiting.

Canary gate.

YAML
- hosts: fleet
  serial: "10%"           # 50 hosts at a time on a 500-host fleet
  max_fail_percentage: 5  # abort if >2 of the first 50 fail
  roles: [baseline]

Before that touches a host, run the same role under --check --diff against a container built from the same base image. A bad template or a missing package shows up there for free. Order the canary by OS version and failure domain, not alphabetically: RHEL 9 and Ubuntu 24.04 fail differently.

Failure modes, with detection and blast radius.

failuredetectionblast radius
stale agentPuppetDB "no report in 2× runinterval"; salt-run manage.status down listone host drifts, misses CVE patches
manual drift--noop / --check --diff diff, osquery, AIDEone host, or a whole class if a runbook was hand-applied
bad state pushedcanary batch fails, max_fail_percentage abortsbounded to the batch if serial is set; fleet-wide if it isn't
control plane downagent run failures, master health checkexisting nodes keep last catalog; new nodes can't bootstrap
minion key theftunexpected certname, salt-key -Lattacker gets that node's config and pillar secrets

Break-glass. Puppet caches the compiled catalog at /opt/puppetlabs/puppet/cache/client_data/catalog/<certname>.json; Salt caches states under /var/cache/salt/minion/. puppet apply and salt-call --local state.apply both work offline against those. Ansible has no cache: that is the real cost of push-only, and the reason I would not make it the source of truth.

Secrets and review. SOPS with age keys or Vault with AppRole; never plaintext in git, with gitleaks in pre-commit. Signed commits on a protected branch, CI running ansible-lint/puppet-lint plus the check-mode run, and short-lived SSH certificates from a Vault SSH CA instead of long-lived keys. Execution identity is a dedicated service account with become, not root over shared SSH.

Curated: · Written: · Reviewed:

Difficulty: Hard