Scenario Questions
Real-world Ansible scenarios: what you would do, why, and how to explain it in an interview
Inventory and Targeting
๐ฅ Learn this hands-on with DevOps Shack โ YouTube @devopsshack ยท Hindi @shackverse ยท Courses at devopsshack.com
Q1 You are handed a fresh Ansible project and 10 servers. How do you make sure Ansible can reach all of them before writing any playbook?
Beginner
Situation read โ No playbook yet; the first risk is connectivity, not logic.
What I'd do โ
- Write an inventory with the hosts and
ansible_user/key settings. - Run
ansible all -i inventory.ini -m ping. - For failures, rerun with
-vvvon one host.
ansible all -i inventory.ini -m ansible.builtin.ping
ansible web01 -i inventory.ini -m ansible.builtin.ping -vvvWhy โ ping tests SSH login, Python on the target and module execution in one shot, so a pong means real playbooks will run.
Interview tip โ Say that ping is not ICMP; it is a full Ansible round trip.
Q2 Your team keeps prod and staging hosts in one inventory file and someone ran a playbook on prod by mistake. How do you prevent it?
Intermediate
Situation read โ Environment separation is weak; the blast radius is controlled by a human typing the right -l.
What I'd do โ
- Split into
inventories/staging/andinventories/prod/, each with its ownhostsandgroup_vars/. - Make staging the default in
ansible.cfg(inventory = inventories/staging). - Require
-i inventories/prodexplicitly, and add a pre-task guard for prod. - In CI, only the prod pipeline job has the prod credentials.
- hosts: all
pre_tasks:
- ansible.builtin.pause:
prompt: "Type PROD to continue"
register: confirm
when: env_name == 'prod'
- ansible.builtin.assert:
that: confirm.user_input == 'PROD'
when: env_name == 'prod'Why โ Separate inventories mean separate variables and separate credentials, so a typo cannot cross environments.
Interview tip โ Mention that group_vars per environment also prevents prod secrets leaking into staging runs.
Q3 You need to run a playbook on only the web servers in Mumbai that are not in the canary group. How?
Beginner
Situation read โ A set-algebra host pattern: intersect two groups, exclude a third.
What I'd do โ
ansible-playbook site.yml --limit 'web:&mumbai:!canary'
ansible-playbook site.yml --limit 'web:&mumbai:!canary' --list-hostsAlways run --list-hosts first to see what the pattern resolves to.
Why โ :& is intersection and :! is exclusion; quoting prevents the shell from eating ! and &.
Interview tip โ Know that --limit narrows the play's hosts:; it cannot add hosts the play never targeted.
Q4 Servers are autoscaled in AWS and IPs change daily. How do you keep the inventory accurate?
Intermediate
Situation read โ A static file will always be stale; the source of truth is the cloud API.
What I'd do โ
- Use the
amazon.aws.aws_ec2inventory plugin. - Group by tags with
keyed_groups, and use private IPs as the connection address. - Enable caching so repeated runs are quick.
# inventories/aws_ec2.yml
plugin: amazon.aws.aws_ec2
regions: [ap-south-1]
filters:
tag:Env: prod
instance-state-name: running
keyed_groups:
- key: tags.Role
prefix: role
compose:
ansible_host: private_ip_address
cache: true
cache_timeout: 300Why โ Instances join groups automatically through tags, so new nodes get configured without editing any file.
Interview tip โ The file name must end in aws_ec2.yml or aws_ec2.yaml for the plugin to accept it.
Q5 A host is reachable by SSH on port 2222 with a different user from all others. How do you model that?
Beginner
Situation read โ One exception to otherwise uniform connection settings.
What I'd do โ Set host-level connection variables on that host only.
[web]
web01
web02
legacy01 ansible_port=2222 ansible_user=admin ansible_ssh_private_key_file=~/.ssh/legacy.pemWhy โ Inventory-level variables beat group defaults for that host while leaving everyone else untouched.
Interview tip โ If the exception grows to several settings, move it to host_vars/legacy01.yml.
Q6 You must configure servers in a private subnet that is only reachable through a bastion.
Intermediate
Situation read โ No direct route from the control node; SSH has to hop.
What I'd do โ
- Set a ProxyJump in the inventory group vars.
- Keep the bastion's key and the private hosts' key separate.
# group_vars/private.yml
ansible_ssh_common_args: >-
-o [email protected]
-o StrictHostKeyChecking=accept-newTest with ansible private -m ping.
Why โ Ansible shells out to OpenSSH, so any native SSH feature works with ansible_ssh_common_args.
Interview tip โ Mention SSM Session Manager as the bastion-less alternative in AWS (aws_ssm connection plugin).
Q7 You want to run a task on every host in the db group and also on localhost in the same playbook.
Beginner
db group and also on localhost in the same playbook.Situation read โ Two audiences in one run, with different connections.
What I'd do โ Use two plays, or delegate_to: localhost for a single task.
- hosts: db
tasks:
- ansible.builtin.dnf: { name: postgresql-server, state: present }
- hosts: localhost
connection: local
gather_facts: false
tasks:
- ansible.builtin.debug: { msg: "DB tier configured" }Why โ Plays are the unit of host selection; mixing hosts inside one play is what delegate_to is for.
Interview tip โ Implicit localhost is not in the all group, so it is not matched by hosts: all.
Q8 You do not know which of 300 servers still run the vulnerable OpenSSL version. How do you find out fast?
Intermediate
Situation read โ An audit task: read-only, wide, and urgent.
What I'd do โ
- Use an ad-hoc command or
package_factswith a high fork count. - Collect output to a file.
ansible all -f 50 -m ansible.builtin.shell -a "openssl version" -o | tee openssl-audit.txt
ansible all -m ansible.builtin.package_facts -a "manager=auto" --tree /tmp/facts-o gives one line per host, which is greppable.
Why โ Ad-hoc is the right tool for read-only questions; no playbook needed.
Interview tip โ For recurring audits, convert it to a playbook that writes a CSV with lineinfile or copy on the controller.
Q9 A teammate asks for a group that contains all hosts that have more than 16 GB RAM.
Advanced
Situation read โ Group membership depends on facts, which exist only at run time.
What I'd do โ Use group_by after fact gathering.
- hosts: all
tasks:
- ansible.builtin.group_by:
key: "bigmem_{{ ansible_memtotal_mb > 16384 }}"
- hosts: bigmem_True
tasks:
- ansible.builtin.debug: { msg: "large host" }Why โ group_by builds groups in memory for the rest of the run; inventory files cannot know facts in advance.
Interview tip โ Alternatively use the constructed inventory plugin with cached facts for a persistent version.
Q10 You inherited a 400-line INI inventory with repeated variables. How do you clean it up without breaking anything?
Intermediate
Situation read โ Refactor with a safety net: the effective variables per host must not change.
What I'd do โ
- Snapshot:
ansible-inventory -i old --list > before.json. - Move shared variables into
group_vars/and per-host ones intohost_vars/. - Snapshot again and diff.
ansible-inventory -i inventory --list > after.json
diff <(jq -S . before.json) <(jq -S . after.json)Why โ ansible-inventory --list shows merged hostvars, so an empty diff proves the refactor is behaviour-neutral.
Interview tip โ Use --graph --vars for a quick human-readable view of the group tree.
Q11 You need to add a newly provisioned EC2 instance to the inventory in the same playbook that creates it.
Intermediate
Situation read โ The host does not exist at inventory-parse time.
What I'd do โ Create it, wait for SSH, then add_host.
- hosts: localhost
tasks:
- amazon.aws.ec2_instance: { name: app1, image_id: ami-0abc, instance_type: t3.micro, wait: true }
register: ec2
- ansible.builtin.add_host:
name: "{{ ec2.instances[0].private_ip_address }}"
groups: new_app
- ansible.builtin.wait_for:
host: "{{ ec2.instances[0].private_ip_address }}"
port: 22
timeout: 300
- hosts: new_app
tasks:
- ansible.builtin.ping:Why โ add_host mutates the in-memory inventory, and a later play can target the new group.
Interview tip โ Alternatively call meta: refresh_inventory when using a dynamic inventory plugin.
Q12 Two groups define the same variable app_port with different values and a host is in both. Which wins and how do you control it?
Advanced
app_port with different values and a host is in both. Which wins and how do you control it?Situation read โ Same-precedence group variables with a merge conflict.
What I'd do โ
- Know the rule: at the same level, groups are merged in alphabetical order and the last one wins, unless
ansible_group_priorityis set. - Set
ansible_group_priorityin the group that should win (higher wins). - Better, avoid the conflict by defining the variable at one level.
# inventory source (not group_vars)
[canary:vars]
ansible_group_priority=20Why โ Relying on alphabetical order is fragile; an explicit priority documents intent.
Interview tip โ ansible_group_priority only works when set in the inventory source, not in group_vars/ files, and ansible-inventory --host confirms the winner.
Q13 Your inventory has hundreds of hosts named web001 through web300. How do you write it compactly?
Beginner
web001 through web300. How do you write it compactly?Situation read โ Repetition that ranges solve.
What I'd do โ
[web]
web[001:300].example.com
[db]
db-[a:c].example.comIn YAML inventory you can use the same bracket ranges as the host key.
Why โ Ranges expand at parse time, and zero padding is preserved when you write 001.
Interview tip โ Verify with ansible web --list-hosts | wc -l.
Q14 A playbook must target different hosts depending on a variable passed at the command line.
Intermediate
Situation read โ The target is a parameter, for example a CI job input.
What I'd do โ Template hosts: from an extra var, with a safe default.
- hosts: "{{ target | default('none') }}"
gather_facts: false
tasks:
- ansible.builtin.ping:ansible-playbook deploy.yml -e target=web:\&mumbaiWhy โ Extra vars are available when the play's hosts are resolved; defaulting to none means a forgotten variable does nothing instead of hitting all.
Interview tip โ Contrast with --limit, which narrows rather than defines.
Q15 You manage Windows and Linux servers from one controller. How do you structure the inventory?
Intermediate
Situation read โ Two connection types, two sets of modules.
What I'd do โ Separate groups with connection variables in group_vars.
# group_vars/windows.yml
ansible_connection: winrm
ansible_winrm_transport: ntlm
ansible_winrm_server_cert_validation: ignore
ansible_port: 5986# group_vars/linux.yml
ansible_connection: sshUse ansible.windows.* modules for the Windows group, and ansible_connection: psrp or SSH if WinRM is not allowed.
Why โ Keeping connection settings at group level lets playbooks stay platform-neutral where possible.
Interview tip โ Install pywinrm on the controller and mention that certificate validation should not be ignored outside labs.
Q16 Your playbook should skip hosts that are currently in maintenance, tracked in a CMDB.
Advanced
Situation read โ An external system decides membership; the inventory must reflect it.
What I'd do โ
- Write (or use) a dynamic inventory script/plugin that queries the CMDB and puts maintenance hosts into a
maintenancegroup. - Exclude it in every run with a default limit, or enforce it in the play.
- hosts: "all:!maintenance"
roles: [baseline]Why โ Excluding by group in the play makes the rule impossible to forget at the command line.
Interview tip โ Dynamic scripts must support --list and --host <name> and print JSON.
Q17 How would you run the same playbook against a single host to test, without editing the playbook?
Beginner
Situation read โ A safe canary run.
What I'd do โ
ansible-playbook site.yml --limit web01 --check --diff
ansible-playbook site.yml --limit web01Why โ --limit confines the blast radius, --check --diff previews the changes, and then the real run on one host tells you whether to proceed.
Interview tip โ Say you start with one host, then 10%, then everyone: that is serial in a production rollout.
Q18 A host appears in ansible-inventory --list but is not matched by hosts: webservers. What do you check?
Intermediate
ansible-inventory --list but is not matched by hosts: webservers. What do you check?Situation read โ A pattern or group-name mismatch.
What I'd do โ
ansible-inventory --graphto see the real group tree.ansible webservers --list-hoststo test the pattern.- Check for typos, case (
Webserversdiffers fromwebservers), and for groups with hyphens (use underscores).
Why โ Group names are case-sensitive, and a host can be present in all but in no matching group.
Interview tip โ Ansible warns "Could not match supplied host pattern" for a mistyped group; never ignore it.
Q19 You want a group of hosts derived from a variable, like every host with env: prod in its host_vars.
Advanced
env: prod in its host_vars.Situation read โ Persistent grouping derived from variables, not facts.
What I'd do โ Use the constructed inventory plugin alongside the static inventory.
# inventories/constructed.yml
plugin: ansible.builtin.constructed
strict: false
keyed_groups:
- key: env
prefix: env
groups:
prod_web: env == 'prod' and 'web' in group_namesWhy โ The plugin builds groups from hostvars at parse time, so every command sees the same groups.
Interview tip โ Put it in the inventory directory; it is loaded after the other sources.
Q20 A colleague hard-coded IP addresses in playbooks. How do you remove them?
Beginner
Situation read โ Data is baked into code.
What I'd do โ
- Put addresses in inventory variables (
ansible_host,db_host). - Refer to them with
hostvarsor group lookups in templates.
db_host: "{{ hostvars[groups['db'][0]].ansible_host }}"Why โ Moving data to inventory means the same playbook works in every environment.
Interview tip โ Prefer inventory hostnames and DNS where you can; IPs only as ansible_host.
Q21 You must apply a change to hosts in two regions with different SSH keys.
Intermediate
Situation read โ Credentials are per group.
What I'd do โ Group per region and set the key in group_vars.
# group_vars/eu.yml
ansible_ssh_private_key_file: ~/.ssh/eu-prod.pem
# group_vars/us.yml
ansible_ssh_private_key_file: ~/.ssh/us-prod.pemWhy โ The play stays identical; only the connection details vary by group.
Interview tip โ In AWX, use separate machine credentials per inventory source instead of file paths.
Q22 Your inventory plugin returns hosts, but variables from group_vars next to the playbook are ignored.
Advanced
group_vars next to the playbook are ignored.Situation read โ group_vars are loaded relative to the inventory source or to the playbook, and the location matters.
What I'd do โ
- Remember:
group_vars/is searched next to the inventory file and next to the playbook. - If the inventory is a plugin config in
inventories/prod/aws_ec2.yml, putgroup_vars/ininventories/prod/. - Check with
ansible-inventory -i inventories/prod --host <h>.
Why โ Playbook-adjacent group_vars load for any inventory; inventory-adjacent ones load only for that inventory's directory.
Interview tip โ When both exist, playbook-adjacent group_vars win over inventory-adjacent ones.
Q23 You need to send a one-off command to 500 hosts quickly without overloading the jump host.
Intermediate
Situation read โ High parallelism meets a bottleneck.
What I'd do โ
ansible all -m ansible.builtin.command -a "uptime" -f 20and enable SSH pipelining and ControlPersist in ansible.cfg.
Why โ -f caps concurrent connections (default 5); tune it to what the bastion's MaxStartups and CPU allow.
Interview tip โ Mention that the default forks = 5 is deliberately conservative.
Q24 Hosts are renamed but keep the same IP, and facts caching still shows old names.
Advanced
Situation read โ Stale fact cache keyed by inventory_hostname.
What I'd do โ
- Clear the cache entry: delete the file/key for the old name, or run
ansible-playbook ... --flush-cache. - Re-gather facts:
ansible renamed -m ansible.builtin.setup. - Reduce
fact_caching_timeoutwhere names change often.
Why โ The cache key is the inventory name, so renamed hosts leave orphaned entries and new names start empty.
Interview tip โ Cached facts speed up playbooks that use gather_facts: smart, but trade freshness.
Q25 A new engineer asks how you know which inventory variables actually apply to a host.
Beginner
Situation read โ Debugging variable merging.
What I'd do โ
ansible-inventory -i inventories/prod --host web01
ansible web01 -m ansible.builtin.debug -a "var=hostvars[inventory_hostname]"Why โ The first prints inventory-derived variables after merging; the second shows what a running play sees, including facts and extra vars.
Interview tip โ Mention --vars with --graph to show variables per group.
Playbook Design, Handlers and Idempotency
๐ฅ Learn this hands-on with DevOps Shack โ YouTube @devopsshack ยท Hindi @shackverse ยท Courses at devopsshack.com
Q26 Your playbook reports changed on every run for a task that runs a shell command. How do you fix it?
Beginner
changed on every run for a task that runs a shell command. How do you fix it?Situation read โ command and shell always report changed because Ansible cannot know the outcome.
What I'd do โ
- Prefer a real module.
- Otherwise add
creates:/removes:or an explicitchanged_when.
- ansible.builtin.command: /opt/app/bin/migrate
register: mig
changed_when: "'Applied' in mig.stdout"Why โ Honest change reporting is what makes idempotency checks and handlers trustworthy.
Interview tip โ A second run of a healthy playbook should show changed=0.
Q27 Nginx must reload only when its config file actually changes.
Beginner
Situation read โ Classic handler use case.
What I'd do โ
tasks:
- ansible.builtin.template:
src: nginx.conf.j2
dest: /etc/nginx/nginx.conf
validate: nginx -t -c %s
notify: Reload nginx
handlers:
- name: Reload nginx
ansible.builtin.service: { name: nginx, state: reloaded }Why โ Handlers run once at the end of the play, only if a notifying task reported changed; validate stops a broken file from being installed.
Interview tip โ Use meta: flush_handlers if later tasks depend on the reload.
Q28 A task fails halfway and its handler never ran, but the config file was changed. The next run shows no change and the service never reloads.
Advanced
Situation read โ Handlers are skipped for hosts that fail before the end of the play, and the next run sees the file as already correct.
What I'd do โ
- Set
force_handlers: trueon the play (or--force-handlers) so notified handlers run despite later failures. - Or flush handlers right after the change.
- Repair now by running the handler's action once.
- hosts: web
force_handlers: trueWhy โ Notifications are in memory only; if the run dies, they are lost.
Interview tip โ This is the best-known handler gotcha; naming it shows real experience.
Q29 You need three tasks to notify one handler, and want it to run once. Is that automatic?
Beginner
Situation read โ Several changes, one restart.
What I'd do โ Just add notify: Restart app to each task.
Why โ A handler runs once per play per host no matter how many tasks notified it. Use listen: to let one event trigger several handlers.
handlers:
- name: Restart app
ansible.builtin.systemd: { name: app, state: restarted }
listen: "app config changed"Interview tip โ Notify by listen topic to decouple task names from handler names.
Q30 You need to deploy a binary only if it is missing or its checksum differs.
Intermediate
Situation read โ Make a download idempotent.
What I'd do โ
- ansible.builtin.get_url:
url: "https://releases.example.com/app-{{ app_version }}.tar.gz"
dest: /opt/app/app-{{ app_version }}.tar.gz
checksum: "sha256:{{ app_sha256 }}"
mode: "0644"Why โ get_url with checksum downloads only when the destination is absent or differs, and verifies integrity.
Interview tip โ Versioned file names give you free rollbacks.
Q31 How do you safely edit one line in /etc/ssh/sshd_config and be sure SSH keeps working?
Intermediate
/etc/ssh/sshd_config and be sure SSH keeps working?Situation read โ A change that can lock you out of every server.
What I'd do โ
- ansible.builtin.lineinfile:
path: /etc/ssh/sshd_config
regexp: '^#?PasswordAuthentication'
line: 'PasswordAuthentication no'
validate: '/usr/sbin/sshd -t -f %s'
backup: true
notify: Reload sshdTest on one host first with --limit and keep an existing session open.
Why โ validate rejects a broken file, and reload keeps current connections alive.
Interview tip โ Prefer dropping a file in sshd_config.d/ where supported.
Q32 A task should run only on Debian-family hosts and a different one on RedHat.
Beginner
Situation read โ OS-conditional logic.
What I'd do โ
- ansible.builtin.apt: { name: nginx, state: present }
when: ansible_facts['os_family'] == 'Debian'
- ansible.builtin.dnf: { name: nginx, state: present }
when: ansible_facts['os_family'] == 'RedHat'Or just use ansible.builtin.package with a vars map for names that differ.
Why โ Facts give a stable OS signal; package is the generic wrapper.
Interview tip โ Use ansible_facts['...'] rather than injected ansible_os_family names.
Q33 You need to wait for an application to listen on port 8080 after a restart before continuing.
Beginner
Situation read โ Races between restart and the next step.
What I'd do โ
- ansible.builtin.wait_for:
port: 8080
delay: 2
timeout: 60
- ansible.builtin.uri:
url: http://localhost:8080/health
status_code: 200
register: r
retries: 10
delay: 3
until: r.status == 200Why โ Port open does not mean healthy; the uri retry loop proves the app answers.
Interview tip โ wait_for can also wait for a file, a string in a file, or a port to drain.
Q34 You want to run a task even in check mode, for example to read a version.
Intermediate
Situation read โ Check mode skips commands, which breaks later logic.
What I'd do โ
- ansible.builtin.command: cat /opt/app/VERSION
register: ver
check_mode: false
changed_when: falseWhy โ check_mode: false forces a real run for a read-only task; changed_when: false keeps the report clean.
Interview tip โ Use check_mode: true on a task to force it to be dry-run even in a normal run.
Q35 A step is allowed to fail, but you still need to react to the failure.
Intermediate
Situation read โ Not every failure is fatal.
What I'd do โ Use block/rescue/always, or ignore_errors plus register for simple cases.
- block:
- ansible.builtin.command: /opt/app/migrate
rescue:
- ansible.builtin.command: /opt/app/rollback
- ansible.builtin.fail: { msg: "migration failed, rolled back" }
always:
- ansible.builtin.debug: { msg: "cleanup done" }Why โ rescue runs on failure, always runs regardless, and re-failing keeps the run honest.
Interview tip โ ignore_errors hides failures; failed_when redefines them. Pick intentionally.
Q36 A command returns exit code 2 for "nothing to do", which Ansible counts as failure.
Intermediate
Situation read โ Tool semantics differ from Ansible's default rc != 0 rule.
What I'd do โ
- ansible.builtin.command: /usr/local/bin/sync-tool
register: r
failed_when: r.rc not in [0, 2]
changed_when: r.rc == 0Why โ failed_when and changed_when let you encode the tool's real contract.
Interview tip โ Prefer an official module; custom conditions are the fallback.
Q37 You must ensure a playbook can be re-run after any failure without cleaning up manually.
Advanced
Situation read โ Idempotent and restartable design.
What I'd do โ
- Use state-based modules everywhere (
state: present). - Guard commands with
creates:or astatcheck. - Write temp files to a path that is cleaned in
always. - Use
--start-at-taskor tags only for resuming, never as a requirement. - Prove it: run twice and require
changed=0in CI.
Why โ If a half-applied state breaks re-runs, the playbook encodes steps rather than a desired state.
Interview tip โ "Run it twice" is the single best idempotency test.
Q38 How do you run a playbook against a host without making any change but see what would differ?
Beginner
Situation read โ Pre-change review.
What I'd do โ
ansible-playbook site.yml --check --diff --limit web01Why โ --check predicts changes where modules support it and --diff shows file differences. Tasks using command/shell are skipped in check mode unless they set check_mode: false.
Interview tip โ Check mode is a prediction, not a guarantee, especially when later tasks depend on earlier ones.
Q39 You need a task to run once per play, not once per host, such as sending a Slack notification.
Intermediate
Situation read โ A play-wide side effect.
What I'd do โ
- ansible.builtin.uri:
url: "{{ slack_webhook }}"
method: POST
body_format: json
body: { text: "Deploy finished" }
run_once: true
delegate_to: localhostWhy โ run_once executes on the first host in the batch; delegate_to: localhost makes the call from the controller.
Interview tip โ With serial, run_once fires once per batch; use a condition on ansible_play_hosts if you need once overall.
Q40 A handler needs to run in the middle of a play, before the next set of tasks.
Beginner
Situation read โ Ordering dependency on a handler.
What I'd do โ
- ansible.builtin.template: { src: app.conf.j2, dest: /etc/app.conf }
notify: Restart app
- ansible.builtin.meta: flush_handlers
- ansible.builtin.uri: { url: http://localhost:8080/health }Why โ flush_handlers runs pending handlers immediately instead of waiting for the end of the play.
Interview tip โ Handlers also flush at the end of each of pre_tasks, roles/tasks and post_tasks sections.
Q41 You want to loop over a list of users and create each with its own groups.
Beginner
Situation read โ A data-driven loop.
What I'd do โ
vars:
team:
- { name: asha, groups: [sudo, docker] }
- { name: ravi, groups: [docker] }
tasks:
- ansible.builtin.user:
name: "{{ item.name }}"
groups: "{{ item.groups }}"
append: true
loop: "{{ team }}"
loop_control:
label: "{{ item.name }}"Why โ loop_control.label keeps output short and avoids leaking big dicts into logs.
Interview tip โ append: true is vital, or you remove existing group memberships.
Q42 You need to retry a flaky task, like a package mirror, up to five times.
Beginner
Situation read โ Transient network failures.
What I'd do โ
- ansible.builtin.apt: { name: nginx, update_cache: true }
register: r
retries: 5
delay: 10
until: r is succeededWhy โ until re-evaluates after each attempt; delay avoids hammering the mirror.
Interview tip โ Retries mask real problems if overused; log and alert on repeated retries.
Q43 A deployment must stop on the first host that fails and not touch the rest.
Intermediate
Situation read โ Fail-fast rollout.
What I'd do โ
- hosts: web
serial: 1
max_fail_percentage: 0
any_errors_fatal: trueWhy โ serial: 1 isolates risk, and any_errors_fatal aborts the play for all hosts when any task fails.
Interview tip โ Without serial, max_fail_percentage is evaluated across the whole play, so it behaves differently.
Q44 You want to keep a backup of every config file Ansible replaces.
Beginner
Situation read โ Safety net for rollbacks.
What I'd do โ
- ansible.builtin.template:
src: app.conf.j2
dest: /etc/app/app.conf
backup: trueWhy โ The module saves a timestamped copy next to the original, and returns backup_file.
Interview tip โ Backups pile up; long-term, rely on Git for the source and keep backups for emergencies.
Q45 Your playbook has 80 tasks and a failure at task 63. You fixed the cause. How do you resume efficiently?
Intermediate
Situation read โ Avoid re-running everything.
What I'd do โ
ansible-playbook site.yml --start-at-task "Deploy application"
ansible-playbook site.yml --limit @site.retry # retry file if enabledIf the playbook is idempotent, re-running the whole thing is also safe.
Why โ --start-at-task skips earlier tasks (and their registered vars), so use it only when later tasks do not depend on skipped ones.
Interview tip โ Retry files are disabled by default; use --limit with failed hosts from the recap.
Q46 How would you ensure a package is at an exact version and never upgraded accidentally?
Intermediate
Situation read โ Version pinning.
What I'd do โ
- ansible.builtin.apt:
name: nginx=1.24.0-2ubuntu7
state: present
allow_downgrade: true
- ansible.builtin.dpkg_selections:
name: nginx
selection: holdWhy โ The version string pins the install and hold blocks upgrades from apt upgrade.
Interview tip โ On RHEL use dnf with name: nginx-1.24.0 and the versionlock plugin.
Q47 You need a task to run only the first time a server is built.
Intermediate
Situation read โ One-time bootstrap.
What I'd do โ Use a marker file with creates.
- ansible.builtin.command: /opt/bootstrap.sh
args:
creates: /var/lib/bootstrap.done
- ansible.builtin.file:
path: /var/lib/bootstrap.done
state: touch
modification_time: preserve
access_time: preserveWhy โ creates makes the task skip once the marker exists.
Interview tip โ Better still, make bootstrap itself idempotent so a marker is optional.
Q48 A task prints a password in the logs. How do you stop that?
Beginner
Situation read โ Secret exposure in output.
What I'd do โ
- ansible.builtin.user:
name: svc
password: "{{ svc_pw | password_hash('sha512') }}"
no_log: trueWhy โ no_log: true hides the task's arguments and results, including from -v output.
Interview tip โ It also hides errors; toggle it off briefly in a safe environment to debug.
Q49 How would you delay a restart until a maintenance window?
Advanced
Situation read โ Changes should apply now but disruptive actions later.
What I'd do โ
- Let the config deploy normally and write a flag file or notify a handler that only sets a "restart pending" marker.
- A scheduled AWX job (or cron on the controller) runs a play with
tags: restartinside the window. - Report pending restarts using
needs-restarting -ror/var/run/reboot-required.
Why โ Separating configuration from disruption keeps deploys safe and auditable.
Interview tip โ Mention AWX schedules with a survey-less, tag-limited template.
Q50 Your teammate used command: systemctl restart app in tasks. What do you say in review?
Beginner
command: systemctl restart app in tasks. What do you say in review?Situation read โ Non-idempotent and reports changed every run.
What I'd do โ Replace with a module and a handler.
handlers:
- name: Restart app
ansible.builtin.systemd:
name: app
state: restarted
daemon_reload: trueWhy โ Modules report real state; handlers restart only when something changed.
Interview tip โ Use state: started plus enabled: true in a normal task for the "ensure running" part.
Variables, Facts and Templates
๐ฅ Learn this hands-on with DevOps Shack โ YouTube @devopsshack ยท Hindi @shackverse ยท Courses at devopsshack.com
Q51 A variable you set in group_vars is being overridden and you do not know where. How do you find the source?
Intermediate
group_vars is being overridden and you do not know where. How do you find the source?Situation read โ Precedence conflict across up to 22 levels.
What I'd do โ
- Print the final value:
ansible web01 -m debug -a "var=app_port". - Search the repo:
grep -rn "app_port" .. - Check the usual suspects:
-eextra vars,set_fact, rolevars/(higher thangroup_vars), playvars:, andhost_vars. - Run with
-vvvand look at where each var file loads.
Why โ Role vars/main.yml, set_fact, include_vars and -e all outrank group_vars.
Interview tip โ Say you keep tunable defaults in role defaults/ precisely because it has the lowest precedence.
Q52 You need different values per environment without copying playbooks.
Beginner
Situation read โ One code, many configurations.
What I'd do โ One inventory per environment, each with group_vars/all.yml and group files.
inventories/
staging/group_vars/all.yml # app_replicas: 2
prod/group_vars/all.yml # app_replicas: 6Run ansible-playbook -i inventories/prod site.yml.
Why โ Environment data lives with the inventory; the playbook stays generic.
Interview tip โ Avoid if env == 'prod' branches in tasks; use variables.
Q53 You must render an Nginx config with one server block per site from a list.
Intermediate
server block per site from a list.Situation read โ Template with a loop.
What I'd do โ
{# templates/sites.conf.j2 #}
{% for s in sites %}
server {
listen {{ s.port | default(80) }};
server_name {{ s.name }};
root {{ s.root }};
}
{% endfor %}- ansible.builtin.template:
src: sites.conf.j2
dest: /etc/nginx/conf.d/sites.conf
validate: nginx -t -c /etc/nginx/nginx.confWhy โ Data in YAML, structure in the template; adding a site is a one-line variable change.
Interview tip โ Use {%- -%} whitespace control or trim_blocks to keep output tidy.
Q54 A template needs the IPs of all hosts in the db group, for example for a replication config.
Intermediate
db group, for example for a replication config.Situation read โ Cross-host data inside a template.
What I'd do โ
{% for h in groups['db'] %}
host replication repl {{ hostvars[h].ansible_default_ipv4.address }}/32 md5
{% endfor %}Make sure facts for the db hosts exist, either by gathering in an earlier play or via fact caching.
Why โ hostvars exposes other hosts' variables and facts, but only if gathered in this run or cached.
Interview tip โ Facts missing causes 'ansible_default_ipv4' is undefined; gather facts for db hosts first.
Q55 Nothing should be rendered unless a mandatory variable is supplied.
Beginner
Situation read โ Fail early on missing input.
What I'd do โ
- ansible.builtin.assert:
that:
- db_password is defined
- db_password | length >= 12
fail_msg: "db_password must be set and 12+ chars"and use {{ db_host | mandatory }} in templates.
Why โ A clear early failure beats a half-rendered config.
Interview tip โ assert in pre_tasks or tasks/validate.yml of a role is common.
Q56 Per-host values, like server_id for MySQL, must be unique and stable.
Intermediate
server_id for MySQL, must be unique and stable.Situation read โ Generate unique but deterministic values.
What I'd do โ Either set them in host_vars/, or derive from inventory position.
mysql_server_id: "{{ groups['db'].index(inventory_hostname) + 1 }}"Why โ Index in the group is stable as long as hosts are only appended. If you reorder, IDs change, so explicit host_vars is safer for databases.
Interview tip โ Call out the trade-off between convenience and stability.
Q57 A fact you need is not collected by default, such as a custom application version.
Intermediate
Situation read โ Extend facts.
What I'd do โ Drop a script or JSON into /etc/ansible/facts.d/ on the target.
- ansible.builtin.copy:
dest: /etc/ansible/facts.d/app.fact
content: '{"version": "{{ app_version }}"}'
mode: "0644"
- ansible.builtin.setup:
filter: ansible_localThen use ansible_local.app.version.
Why โ Files ending in .fact (JSON, INI or an executable printing JSON) become ansible_local.
Interview tip โ Re-run setup after creating the file to refresh within the same play.
Q58 Gathering facts takes minutes on 500 hosts and you only need the OS family.
Intermediate
Situation read โ Fact gathering is overkill.
What I'd do โ
- hosts: all
gather_facts: false
tasks:
- ansible.builtin.setup:
gather_subset: [min]
filter: ansible_os_familyOr set gather_subset = min in ansible.cfg, and enable fact caching.
Why โ The full subset runs hardware and network probes you rarely need.
Interview tip โ gather_facts: false on plays that never use facts is free speed.
Q59 You have to merge two dictionaries, with one overriding the other, such as defaults plus per-site settings.
Intermediate
Situation read โ Deep merge of structured data.
What I'd do โ
app_config: "{{ app_defaults | combine(app_overrides, recursive=True) }}"Why โ combine merges dicts; without recursive=True nested keys are replaced wholesale.
Interview tip โ For lists use + or union, and unique to dedupe.
Q60 Passwords in a template must not be world readable.
Beginner
Situation read โ File permission hygiene.
What I'd do โ
- ansible.builtin.template:
src: db.env.j2
dest: /etc/app/db.env
owner: app
group: app
mode: "0600"Why โ Quote the mode as a string; an unquoted 0600 is read by YAML as octal in some contexts and as an int in others.
Interview tip โ Always set mode explicitly on secrets.
Q61 You want a variable value computed once from a command and reused through the play.
Intermediate
Situation read โ Store results for reuse.
What I'd do โ
- ansible.builtin.command: git -C /opt/app rev-parse --short HEAD
register: git_rev
changed_when: false
- ansible.builtin.set_fact:
release: "{{ git_rev.stdout }}"
cacheable: trueWhy โ register lives for the play on that host; set_fact with cacheable can persist into the fact cache.
Interview tip โ set_fact has high precedence and can shadow inventory variables.
Q62 A list of strings in a variable needs to be passed as a comma-separated argument.
Beginner
Situation read โ Basic filter use.
What I'd do โ
servers: [a, b, c]
line: "{{ servers | join(',') }}"Why โ join is a Jinja filter; others you will use daily are default, map, select, regex_replace, to_nice_json.
Interview tip โ Know map(attribute='name') | list for extracting a field from a list of dicts.
Q63 Your template renders True in a config that expects true.
Intermediate
True in a config that expects true.Situation read โ Python vs JSON/YAML boolean casing.
What I'd do โ
enabled: {{ feature_x | bool | lower }}
{{ app_settings | to_nice_json }}Why โ Jinja prints Python's True; to_json, to_nice_yaml or | lower produce the target-format spelling.
Interview tip โ Serialise whole structures with to_nice_json rather than hand-assembling braces.
Q64 A template for a config file must not be overwritten by Ansible if an admin edited it, but must exist.
Intermediate
Situation read โ Seed once, never clobber.
What I'd do โ
- ansible.builtin.template:
src: app.conf.j2
dest: /etc/app/app.conf
force: falseWhy โ With force: false the file is only created if it does not exist.
Interview tip โ Explain the drift trade-off: this is intentional for admin-owned files; otherwise own the file fully.
Q65 A cluster needs a per-host list of all peers except itself.
Intermediate
Situation read โ Peer lists in templates.
What I'd do โ
{% for h in groups['cluster'] if h != inventory_hostname %}
peer {{ hostvars[h].ansible_host | default(h) }}
{% endfor %}Or in YAML: {{ groups['cluster'] | difference([inventory_hostname]) }}.
Why โ difference is clean and testable; the loop-with-if form is fine inside templates.
Interview tip โ ansible_play_hosts is better than groups[...] when you want only hosts still alive in this run.
Q66 You need to pull a secret from AWS Secrets Manager at run time rather than keep it in Git.
Advanced
Situation read โ Dynamic secret lookup.
What I'd do โ
db_password: "{{ lookup('amazon.aws.secretsmanager_secret', 'prod/db/password', region='ap-south-1') }}"Mark consuming tasks no_log: true, and give the controller an IAM role with secretsmanager:GetSecretValue on that ARN only.
Why โ Lookups run on the controller, so targets never need AWS permissions.
Interview tip โ Compare with Vault (file-based), HashiCorp Vault lookup and AWX credential injection.
Q67 Different servers need different values but the template has dozens of if blocks. How do you simplify?
Intermediate
if blocks. How do you simplify?Situation read โ Template complexity is a smell.
What I'd do โ
- Push decisions into variables (
group_vars), not template branching. - Use a dictionary lookup by OS or role instead of if/elif chains.
- Split into several templates if the files genuinely differ.
pkg: "{{ {'Debian':'apache2','RedHat':'httpd'}[ansible_facts['os_family']] }}"Why โ Data-driven config is easier to review and test.
Interview tip โ Templates should format data, not decide policy.
Q68 Your play uses with_items and you have been asked to modernise. What changes?
Beginner
with_items and you have been asked to modernise. What changes?Situation read โ Legacy loop syntax.
What I'd do โ Replace with_items: "{{ list }}" by loop: "{{ list }}". For nested or flattened lists use filters.
loop: "{{ users | product(groups) | list }}" # was with_nested
loop: "{{ dict | dict2items }}" # was with_dictWhy โ loop is the recommended keyword; with_* still works but hides what is happening.
Interview tip โ with_items flattens one level automatically; loop does not, so use | flatten(1).
Q69 A variable contains Jinja that should not be evaluated at definition time, like a string for another system.
Advanced
Situation read โ Escaping templating.
What I'd do โ
prom_label: "{% raw %}{{ $labels.instance }}{% endraw %}"
motd: !unsafe "Welcome {{ user }}"Why โ {% raw %} stops Jinja from evaluating the braces, and !unsafe marks a YAML string as never templated.
Interview tip โ Prometheus alert and Grafana templates inside Ansible templates are the classic example.
Q70 How do you detect that a registered result was skipped or failed and branch on it?
Intermediate
Situation read โ Use result tests rather than raw fields.
What I'd do โ
- ansible.builtin.command: grep -q ready /tmp/state
register: r
failed_when: false
- ansible.builtin.debug: { msg: "not ready" }
when: r is failed
- ansible.builtin.debug: { msg: "changed" }
when: r is changedWhy โ is failed, is changed, is skipped and is succeeded are readable and robust.
Interview tip โ Avoid the legacy r|failed filter syntax.
Q71 You want to read a YAML file on the controller and use its contents as variables.
Intermediate
Situation read โ External data source.
What I'd do โ
- ansible.builtin.include_vars:
file: "vars/{{ env_name }}.yml"
name: env_cfg
- ansible.builtin.debug: { var: env_cfg.api_url }Or lookup('ansible.builtin.file', ...) | from_yaml.
Why โ include_vars loads at run time and name: namespaces it to avoid precedence surprises.
Interview tip โ include_vars outranks group_vars and play vars (it's a "role/include vars" level).
Q72 A play uses a variable that is defined only for some hosts. How do you handle the rest?
Beginner
Situation read โ Optional variable.
What I'd do โ
- ansible.builtin.debug:
msg: "{{ proxy_url | default(omit) }}"
- ansible.builtin.apt: { name: curl }
environment:
http_proxy: "{{ proxy_url | default('') }}"
when: proxy_url is definedWhy โ default(omit) drops a module parameter entirely; is defined guards a task.
Interview tip โ default('') with empty string does not trigger for variables set to empty; use default(x, true) for that.
Q73 You must generate a config containing a random password once and then keep it stable on later runs.
Intermediate
Situation read โ Idempotent random data.
What I'd do โ
app_secret: "{{ lookup('ansible.builtin.password', '/secure/creds/' ~ inventory_hostname ~ '.txt length=32 chars=ascii_letters,digits') }}"Why โ The password lookup creates the file on the first call and reads it back later, so the value stays the same. It runs on the controller, so protect that directory.
Interview tip โ Better for production: generate in a secrets manager and look it up.
Q74 A teammate puts ansible_python_interpreter in every play. Where should it live?
Beginner
ansible_python_interpreter in every play. Where should it live?Situation read โ Connection config duplicated.
What I'd do โ Move it to inventory (group_vars/all.yml or host vars), or set interpreter_python = auto_silent in ansible.cfg.
# group_vars/legacy.yml
ansible_python_interpreter: /usr/bin/python3.9Why โ It is a property of the host, not the play.
Interview tip โ Modern Ansible discovers Python automatically (auto).
Q75 A Jinja expression builds a path from several variables and sometimes yields a double slash.
Beginner
Situation read โ String concatenation sloppiness.
What I'd do โ
dest: "{{ base_dir | trim('/') }}/{{ app }}"
dest2: "{{ [base_dir, app] | join('/') | regex_replace('/+', '/') }}"
dest3: "{{ (base_dir ~ '/' ~ app) | path_join }}"Why โ path_join (Ansible 2.10+) normalises separators; plain concatenation does not.
Interview tip โ Use ~ for string concatenation; + can fail on mixed types.
Roles, Collections and Project Structure
๐ฅ Learn this hands-on with DevOps Shack โ YouTube @devopsshack ยท Hindi @shackverse ยท Courses at devopsshack.com
Q76 You have a 600-line playbook that sets up web, db and monitoring. How do you restructure it?
Beginner
Situation read โ A monolith that is hard to reuse and test.
What I'd do โ
- Create roles:
roles/common,roles/nginx,roles/postgres,roles/node_exporter. - Make
site.ymlimport small playbooks, such asweb.ymlanddb.yml. - Move values to
defaults/main.ymland inventory.
- hosts: web
roles: [common, nginx, node_exporter]Why โ Roles give reuse, a standard layout and a natural unit for Molecule tests.
Interview tip โ Keep playbooks as thin mappings of hosts to roles.
Q77 Where do you put a variable users of your role are expected to override?
Beginner
Situation read โ Public vs internal role variables.
What I'd do โ defaults/main.yml for the public interface, vars/main.yml for internal constants.
# roles/nginx/defaults/main.yml
nginx_worker_processes: auto
nginx_listen_port: 80Why โ Defaults have the lowest precedence, so any inventory or play var wins; vars/ is high precedence and hard to override.
Interview tip โ Prefix variables with the role name to avoid collisions.
Q78 Two roles need to run in a fixed order, such as common before nginx.
Beginner
common before nginx.Situation read โ Dependency between roles.
What I'd do โ Declare it in meta/main.yml.
# roles/nginx/meta/main.yml
dependencies:
- role: commonWhy โ Dependencies run first, and by default only once per play even if several roles list them.
Interview tip โ Prefer explicit ordering in the playbook when the dependency is policy rather than a hard requirement.
Q79 A role is used twice with different parameters in one play, but only runs once.
Intermediate
Situation read โ Role de-duplication.
What I'd do โ Set allow_duplicates: true in the role's meta/main.yml, or use include_role with vars.
# meta/main.yml
allow_duplicates: true- ansible.builtin.include_role: { name: vhost, vars: { site: a.example.com } }
- ansible.builtin.include_role: { name: vhost, vars: { site: b.example.com } }Why โ Roles with identical parameters are deduplicated by default.
Interview tip โ A loop over include_role is another common pattern.
Q80 You want to share roles across several repos and teams.
Intermediate
Situation read โ Distribution and versioning.
What I'd do โ
- Package roles in a collection (
namespace.collection) or keep one repo per role. - Pin versions in
requirements.yml.
collections:
- name: acme.platform
version: 1.4.2
source: https://galaxy.internal.example.com
roles:
- src: git+https://git.example.com/ansible/nginx.git
version: v2.1.0
name: acme.nginxInstall with ansible-galaxy install -r requirements.yml.
Why โ Pinned versions give reproducible builds.
Interview tip โ Use a private Galaxy/Automation Hub or Artifactory for internal content.
Q81 How do you pin Ansible itself so a CI run today behaves like one last month?
Intermediate
Situation read โ Tool-version drift.
What I'd do โ
- Pin
ansible-coreand Python dependencies inrequirements.txt(and lock hashes). - Pin collections in
requirements.yml. - Better, bake both into an Execution Environment image or a container used by CI.
ansible-core==2.17.*Why โ Module behaviour changes between versions; a floating install makes failures irreproducible.
Interview tip โ Say you upgrade deliberately on a schedule with a test run.
Q82 A role installs a package and writes a config, but must support Ubuntu and Rocky Linux.
Intermediate
Situation read โ OS-specific variables.
What I'd do โ
# tasks/main.yml
- ansible.builtin.include_vars: "{{ lookup('ansible.builtin.first_found', params) }}"
vars:
params:
files:
- "{{ ansible_facts['distribution'] }}-{{ ansible_facts['distribution_major_version'] }}.yml"
- "{{ ansible_facts['os_family'] }}.yml"
- default.yml
paths: [vars]
- ansible.builtin.package: { name: "{{ nginx_pkg }}", state: present }Why โ The data differs per OS and the tasks stay the same.
Interview tip โ This first_found pattern is what well-known community roles use.
Q83 Your role's tasks directory has grown to a single 400-line file.
Beginner
Situation read โ Poor readability.
What I'd do โ Split into files and include them.
# tasks/main.yml
- ansible.builtin.import_tasks: install.yml
- ansible.builtin.import_tasks: configure.yml
- ansible.builtin.import_tasks: service.ymlTag each import so users can run only configure.
Why โ Small files with a clear name map to the lifecycle and are easy to review.
Interview tip โ import_tasks is static (parsed upfront); include_tasks is dynamic (needed for loops or runtime filenames).
Q84 When would you pick include_tasks over import_tasks?
Intermediate
include_tasks over import_tasks?Situation read โ Static vs dynamic reuse.
What I'd do โ Use include_tasks when the file name depends on a variable, when you loop over the include, or when you need when applied once at runtime. Use import_tasks when you want tags and --list-tasks to see everything.
- ansible.builtin.include_tasks: "{{ ansible_facts['os_family'] }}.yml"Why โ Imports are expanded before the run; includes are evaluated as the play reaches them, so tags on the include apply only to the include itself.
Interview tip โ --list-tasks does not show tasks inside dynamic includes.
Q85 A role should work on Ansible 2.15 to 2.18 and you must declare that.
Advanced
Situation read โ Metadata for consumers and Galaxy.
What I'd do โ Fill meta/main.yml, and for collections set requires_ansible in meta/runtime.yml.
galaxy_info:
role_name: nginx
min_ansible_version: "2.15"
platforms:
- { name: Ubuntu, versions: [jammy, noble] }# collection meta/runtime.yml
requires_ansible: ">=2.15.0,<2.19"Why โ Consumers get a clear error instead of an obscure failure, and CI can test the matrix.
Interview tip โ Test the declared matrix in CI, otherwise the range is wishful.
Q86 You have to ship a custom module and filter with your role.
Advanced
Situation read โ Role-local plugins.
What I'd do โ Put them in the role: roles/myrole/library/my_module.py, roles/myrole/filter_plugins/my_filters.py. They become available to that role and anything after it in the play.
For wider reuse, put them in a collection under plugins/modules and plugins/filter, then call them by FQCN.
Why โ Collections give namespacing, versioning and documentation hooks.
Interview tip โ Mention ansible-doc and DOCUMENTATION strings for modules.
Q87 A teammate wants to publish an internal collection. What goes in it and how do you build it?
Intermediate
Situation read โ Packaging for sharing.
What I'd do โ
ansible-galaxy collection init acme.platform
# add roles/, plugins/, playbooks/, galaxy.yml
ansible-galaxy collection build
ansible-galaxy collection publish acme-platform-1.4.2.tar.gz --server internalAdd galaxy.yml metadata with namespace, name, version, dependencies.
Why โ A tarball is versioned and installable anywhere.
Interview tip โ Lint with ansible-lint and sanity-test with ansible-test sanity before publishing.
Q88 Your project needs a standard layout. What do you show a new hire?
Beginner
Situation read โ Project structure.
What I'd do โ
ansible.cfg
requirements.yml
site.yml
inventories/{staging,prod}/{hosts,group_vars/,host_vars/}
playbooks/
roles/
collections/
molecule/ # per roleWhy โ Predictable placement means anyone can find variables and roles quickly.
Interview tip โ Mention one repo, one ansible.cfg checked in, and .gitignore for vault password files.
Q89 A role has a task that should run only if the user opts in, e.g. install the monitoring agent.
Beginner
Situation read โ Feature toggle.
What I'd do โ
# defaults/main.yml
app_enable_monitoring: false
# tasks/main.yml
- ansible.builtin.import_tasks: monitoring.yml
when: app_enable_monitoring | boolWhy โ Boolean flags in defaults give a documented switch.
Interview tip โ | bool guards against the string "false" passed with -e.
Q90 How do you test that a role does not break when its variable x is missing?
Intermediate
x is missing?Situation read โ Validate input handling.
What I'd do โ Add an argument_specs file so Ansible validates inputs before the role runs.
# roles/nginx/meta/argument_specs.yml
argument_specs:
main:
options:
nginx_listen_port: { type: int, default: 80 }
nginx_sites: { type: list, elements: dict, required: true }Why โ Missing or wrongly typed variables fail early with a readable message and documented defaults.
Interview tip โ ansible-doc -t role can display those specs.
Q91 You need to upgrade a community role without surprising changes.
Intermediate
Situation read โ Third-party update risk.
What I'd do โ
- Read the changelog and diff old vs new tag.
- Bump the pin in a branch.
- Run Molecule/
--check --diffagainst staging. - Roll to prod via the normal pipeline.
Why โ Roles change defaults over time; a pinned, reviewed upgrade avoids silent behaviour shifts.
Interview tip โ Fork when upstream is abandoned, but track it.
Q92 Roles in your repo access each other's internal variables. How do you reduce coupling?
Intermediate
Situation read โ Tight coupling.
What I'd do โ
- Define a clear public interface in
defaults/andargument_specs. - Pass data in via role parameters, not by reading another role's vars.
- Share common facts via a
commonrole or inventory variables.
Why โ Roles that only depend on declared inputs are replaceable and testable alone.
Interview tip โ Say "a role is a function: inputs in defaults, effects on the host".
Q93 A role must run a task on another host, such as registering with a load balancer.
Intermediate
Situation read โ Delegation inside a role.
What I'd do โ
- community.general.haproxy:
backend: web
host: "{{ inventory_hostname }}"
state: enabled
delegate_to: "{{ groups['lb'][0] }}"Why โ Variables still resolve for the original host, while the action runs on the LB.
Interview tip โ Be aware ansible_* connection vars come from the delegate host in newer versions; check with -vvv.
Q94 How do you apply only part of a role, for instance only its configuration?
Beginner
Situation read โ Selective execution.
What I'd do โ Tag tasks and use --tags.
- ansible.builtin.template: { src: app.conf.j2, dest: /etc/app.conf }
tags: [config]ansible-playbook site.yml --tags configWhy โ Tags let you apply a slice without editing code.
Interview tip โ Tags on import_tasks apply to every task inside; on include_tasks only to the include.
Q95 Migrating a legacy pre-2.10 playbook that uses short module names to modern Ansible.
Intermediate
Situation read โ Short names such as yum: or ec2: break or are ambiguous.
What I'd do โ
- Run
ansible-lintand let it flagfqcn. - Use
ansible-lint --fixfor mechanical changes. - Install the collections they now live in (
amazon.aws,community.general). - Replace removed modules (
ec2becomesec2_instance).
Why โ FQCNs make the source of every module explicit.
Interview tip โ Core builtins are ansible.builtin.*.
Q96 You are asked to make a role idempotent and prove it.
Intermediate
Situation read โ Evidence required.
What I'd do โ Use Molecule's default scenario, which runs converge then idempotence.
molecule testThe idempotence step fails if the second converge reports any changed task.
Why โ It automates "run twice, expect zero changes".
Interview tip โ Fix offenders with changed_when or a proper module, not by disabling the check.
Q97 A role requires a handler from another role.
Advanced
Situation read โ Cross-role notification.
What I'd do โ Handlers are global to the play, so a task can notify by name. But this couples roles; better to use listen topics.
# role A
notify: "reload web stack"
# role B handler
- name: Reload nginx
ansible.builtin.service: { name: nginx, state: reloaded }
listen: "reload web stack"Why โ A topic name is a stable contract; handler names are not.
Interview tip โ Include roles dynamically with include_role and handlers become visible only after that point.
Q98 You need to run roles in a loop for each tenant.
Intermediate
Situation read โ Multi-tenancy.
What I'd do โ
- ansible.builtin.include_role:
name: tenant
vars:
tenant_name: "{{ item.name }}"
tenant_port: "{{ item.port }}"
loop: "{{ tenants }}"
loop_control: { label: "{{ item.name }}" }Why โ include_role supports loops; roles: does not.
Interview tip โ Use allow_duplicates or unique params so tasks aren't skipped.
Q99 How would you review a pull request that adds a new role?
Intermediate
Situation read โ Quality gate.
What I'd do โ Check: FQCNs, ansible-lint clean, idempotent (Molecule), defaults documented, no secrets, no_log where needed, handlers used instead of restarts, become scoped narrowly, README with variables, tags where useful, supports declared OS list.
Why โ A checklist avoids opinion-based review.
Interview tip โ Mention automating the checklist in CI.
Q100 A role repo and a playbook repo each carry their own ansible.cfg. Which one wins?
Intermediate
ansible.cfg. Which one wins?Situation read โ Config lookup order.
What I'd do โ Know the order: ANSIBLE_CONFIG env var, then ./ansible.cfg in the current directory, then ~/.ansible.cfg, then /etc/ansible/ansible.cfg. Only one file is used; they do not merge. Check with ansible --version (shows config file) and ansible-config dump --only-changed.
Why โ The working directory at invocation decides; world-writable directories are ignored for security.
Interview tip โ Mention the "ignoring ansible.cfg in a world writable directory" warning.
Rolling Updates, Delegation and Orchestration
๐ฅ Learn this hands-on with DevOps Shack โ YouTube @devopsshack ยท Hindi @shackverse ยท Courses at devopsshack.com
Q101 You must deploy a new app version to 40 web servers behind a load balancer with zero downtime.
Advanced
Situation read โ Rolling update: take a few nodes out, update, verify, put back.
What I'd do โ
- Use
serialto limit the batch size. - Drain each node from the LB with
delegate_to. - Deploy, health check, re-enable.
- hosts: web
serial: [1, "10%", "25%"]
max_fail_percentage: 10
pre_tasks:
- community.general.haproxy: { backend: web, host: "{{ inventory_hostname }}", state: disabled, wait: true }
delegate_to: lb01
roles: [app]
post_tasks:
- ansible.builtin.uri: { url: "http://{{ inventory_hostname }}:8080/health" }
register: h
until: h.status == 200
retries: 15
delay: 4
- community.general.haproxy: { backend: web, host: "{{ inventory_hostname }}", state: enabled }
delegate_to: lb01Why โ The canary-first serial list limits risk, and the health gate stops the roll before it spreads.
Interview tip โ Mention max_fail_percentage and any_errors_fatal as stop conditions.
Q102 What does serial: [1, 5, "50%"] do?
Beginner
serial: [1, 5, "50%"] do?Situation read โ Escalating batches.
What I'd do โ Explain: first batch is 1 host, the next is 5, then 50% of the total in each remaining batch until all hosts are done.
Why โ You pay a small cost to learn early whether the release is bad.
Interview tip โ serial batches run the whole play to completion on one batch before starting the next.
Q103 During a rolling update, 3 of 10 hosts in a batch fail. Does the play continue?
Intermediate
Situation read โ Failure thresholds.
What I'd do โ Check max_fail_percentage. Default behaviour: failed hosts drop out and the rest continue. If the failure percentage in a batch exceeds max_fail_percentage, the play stops for all hosts. any_errors_fatal: true stops everything on the first failure.
Why โ Thresholds are evaluated per batch when serial is used.
Interview tip โ A percentage of 0 means "any failure aborts".
Q104 You must restart database replicas one at a time but never the primary first.
Advanced
Situation read โ Ordering matters and roles differ.
What I'd do โ Two plays: replicas with serial: 1, then the primary after a controlled failover.
- hosts: db_replicas
serial: 1
tasks:
- ansible.builtin.include_role: { name: pg_upgrade }
- ansible.builtin.command: pg_isready
register: r
until: r.rc == 0
retries: 20
delay: 5
- hosts: db_primary
tasks:
- ansible.builtin.command: patronictl switchover --force --candidate "{{ new_primary }}"
run_once: true
- ansible.builtin.include_role: { name: pg_upgrade }Why โ Ansible plays run in order, so order is explicit and each stage is gated.
Interview tip โ Check replication lag before moving on.
Q105 You need a task to run on the LB for every web host, without logging into each web host.
Intermediate
Situation read โ delegate_to use.
What I'd do โ Use delegate_to: lb01 on the task; it runs on the LB once per web host, with inventory_hostname still the web host.
Why โ Useful for registering and deregistering backends, DNS updates and monitoring downtimes.
Interview tip โ Add run_once: true only if the action should happen a single time.
Q106 A shell command must run on localhost for each remote host, e.g. a CLI call to a cloud API.
Beginner
Situation read โ Controller-side call per host.
What I'd do โ
- ansible.builtin.command: "aws ec2 create-tags --resources {{ instance_id }} --tags Key=Patched,Value=true"
delegate_to: localhost
become: falseWhy โ become: false stops it from trying sudo on the controller.
Interview tip โ Prefer the collection module over the CLI.
Q107 A deployment should run strictly one host at a time, but fact gathering should not be slow.
Intermediate
Situation read โ serial: 1 gathers facts per batch, increasing wall time.
What I'd do โ Gather facts in a first play for all hosts, then run the serial play with gather_facts: false, or with cached facts.
- hosts: web
gather_facts: true
tasks: []
- hosts: web
serial: 1
gather_facts: falseWhy โ Facts are collected in parallel once, not 40 times sequentially.
Interview tip โ Facts live in memory for the whole run, so the second play still sees them.
Q108 Hosts need rebooting after a kernel patch, one at a time, and the play must wait for them to return.
Intermediate
Situation read โ Safe reboot.
What I'd do โ
- hosts: all
serial: 1
tasks:
- ansible.builtin.reboot:
reboot_timeout: 900
post_reboot_delay: 20
test_command: systemctl is-system-running --waitWhy โ The reboot module handles the disconnect, polls until SSH returns and runs a test command.
Interview tip โ Never use shell: reboot with async; the module exists for this.
Q109 You need to check a condition on all hosts first and only then change any of them.
Advanced
Situation read โ All-or-nothing gate.
What I'd do โ Use a preflight play with any_errors_fatal.
- hosts: db
any_errors_fatal: true
tasks:
- ansible.builtin.assert:
that: ansible_facts['mounts'] | selectattr('mount','equalto','/') | map(attribute='size_available') | first > 5000000000
fail_msg: "Less than 5 GB free on /"
- hosts: db
roles: [upgrade]Why โ Failing in the first play means no host has changed yet.
Interview tip โ A strong answer includes a rollback strategy, not only a gate.
Q110 How do you run a long job (a 45-minute backup) on many hosts without holding SSH sessions?
Advanced
Situation read โ Long tasks and connection timeouts.
What I'd do โ
- ansible.builtin.command: /opt/backup/run.sh
async: 3600
poll: 0
register: job
- ansible.builtin.async_status:
jid: "{{ job.ansible_job_id }}"
register: res
until: res.finished
retries: 120
delay: 30Why โ poll: 0 fires and forgets, and async_status checks later, so no session is held open between polls.
Interview tip โ async tasks do not work with check mode and some connection types.
Q111 You must run a play on hosts in a certain order, such as db, then app, then web.
Beginner
Situation read โ Tier ordering.
What I'd do โ Use several plays in one playbook in that order.
- import_playbook: db.yml
- import_playbook: app.yml
- import_playbook: web.ymlWhy โ Plays execute strictly in file order; order: sorted|reverse_sorted|shuffle only controls host order inside a play.
Interview tip โ Put import_playbook at the top level only.
Q112 A task on host A needs data produced by host B in the same play.
Advanced
Situation read โ Cross-host data flow.
What I'd do โ Register on B, read with hostvars from A, and make sure B's task ran first (strategy linear guarantees that per task).
- hosts: db_primary
tasks:
- ansible.builtin.command: pg_current_wal_lsn
register: lsn
- hosts: db_replica
tasks:
- ansible.builtin.debug: { msg: "{{ hostvars[groups['db_primary'][0]].lsn.stdout }}" }Why โ hostvars exposes registered variables from earlier plays in the same run.
Interview tip โ In a single play with free strategy ordering is not guaranteed.
Q113 What is the free strategy and when would you use it?
Beginner
free strategy and when would you use it?Situation read โ Hosts have very different speeds.
What I'd do โ Set strategy: free on the play so each host proceeds as fast as it can instead of waiting for the slowest host at each task.
Why โ Great for independent long-running work like package updates; bad when later tasks depend on all hosts finishing earlier steps.
Interview tip โ Output is interleaved, so logs are harder to read.
Q114 Two engineers run the same playbook against production at the same time. How do you prevent it?
Intermediate
Situation read โ Concurrency control.
What I'd do โ Run Ansible only through AWX or a CI job with a concurrency group, so only one job per inventory runs. As a fallback, take a lock via a task on localhost:
- ansible.builtin.command: flock -n /tmp/deploy.lock true
delegate_to: localhost
run_once: trueIn AWX, disable "Allow Simultaneous Runs" on the template.
Why โ Concurrent runs cause races on the same hosts and unpredictable handler behaviour.
Interview tip โ CI "concurrency" or AWX job slicing are the cleaner answers.
Q115 How would you do a blue/green deployment with Ansible?
Advanced
Situation read โ Two identical stacks, switch traffic at the end.
What I'd do โ
- Determine the idle colour from a variable or the LB state.
- Deploy and smoke test the idle stack.
- Switch the LB target group or DNS.
- Keep the old stack for the rollback window, then destroy.
- hosts: "{{ idle_color }}"
roles: [app]
- hosts: localhost
tasks:
- amazon.aws.elb_application_lb:
name: app-alb
listeners:
- Protocol: HTTP
Port: 80
DefaultActions: [{ Type: forward, TargetGroupName: "tg-{{ idle_color }}" }]
state: presentWhy โ Cutover is one atomic change, and rollback is flipping it back.
Interview tip โ Compare with rolling for cost and database migration complexity.
Q116 A handler restarts a service but the restart takes 30 seconds and later tasks fail on connection refused.
Intermediate
Situation read โ Race after restart.
What I'd do โ Flush handlers, then wait for readiness.
- ansible.builtin.meta: flush_handlers
- ansible.builtin.wait_for: { port: 5432, timeout: 120 }Why โ Handlers normally run at the end of the section, so you must flush before dependent tasks.
Interview tip โ Use health-check endpoints rather than only port checks.
Q117 You must update a cluster where only one node can be down at a time and you must know the quorum is healthy before the next node.
Advanced
Situation read โ Stateful clusters (etcd, Kafka, Elasticsearch).
What I'd do โ
serial: 1.- Pre-check cluster health from the node or via delegation.
- Update, restart, wait for rejoin.
- Post-check health; fail the play otherwise.
- ansible.builtin.uri:
url: "http://{{ inventory_hostname }}:9200/_cluster/health"
return_content: true
register: ch
until: ch.json.status == 'green'
retries: 60
delay: 10Why โ The gate prevents a second node going down while the cluster is still recovering.
Interview tip โ Mention disabling shard allocation first for Elasticsearch.
Q118 A playbook should send a notification when it starts and when it finishes, even if it fails.
Advanced
Situation read โ Lifecycle notifications.
What I'd do โ Wrap the work in block/always, or use callback plugins. A simple pattern:
- hosts: web
tasks:
- block:
- ansible.builtin.include_role: { name: app }
always:
- community.general.slack:
token: "{{ slack_token }}"
msg: "Deploy {{ 'FAILED' if ansible_failed_task is defined else 'ok' }} on {{ inventory_hostname }}"
delegate_to: localhostWhy โ always runs after both success and failure, though not if the host is unreachable.
Interview tip โ AWX has native notification templates for start/success/fail.
Q119 You need to throttle a task so only 2 hosts hit the artifact server at once, while others run in parallel.
Beginner
Situation read โ Per-task concurrency.
What I'd do โ
- ansible.builtin.get_url: { url: "{{ artifact_url }}", dest: /opt/app.tar.gz }
throttle: 2Why โ throttle limits workers for that task only, without changing forks or serial.
Interview tip โ throttle is also useful for rate-limited APIs.
Q120 After a deployment you want to run smoke tests from the controller against each host.
Beginner
Situation read โ Post-deploy verification.
What I'd do โ
- ansible.builtin.uri:
url: "https://{{ inventory_hostname }}/health"
validate_certs: true
status_code: 200
delegate_to: localhostWhy โ The controller tests the same path users take; failures stop the batch.
Interview tip โ Fail the play on a failed smoke test to prevent promoting a broken release.
Q121 Your rolling update stopped halfway because of a failure. How do you finish safely?
Advanced
Situation read โ Partial rollout, mixed versions.
What I'd do โ
- Identify updated vs pending hosts from the PLAY RECAP or a version check.
- Fix the root cause.
- Re-run limited to the remaining hosts.
- Confirm the final version everywhere.
ansible web -m ansible.builtin.command -a "/opt/app/bin/app --version" -o
ansible-playbook deploy.yml --limit @/tmp/pending.txtWhy โ An idempotent play skips hosts that are already correct.
Interview tip โ Design for mixed-version tolerance during rollouts.
Q122 A play must act on a host that is unreachable at the start but may come back soon.
Advanced
Situation read โ Unreachable hosts are dropped from the play.
What I'd do โ Use wait_for_connection early, and meta: clear_host_errors to re-include hosts that failed earlier.
- hosts: all
gather_facts: false
tasks:
- ansible.builtin.wait_for_connection: { timeout: 300 }
- ansible.builtin.setup:Why โ Hosts marked unreachable stay out for the rest of the play; waiting before facts gathering prevents that.
Interview tip โ meta: clear_host_errors resets failed state for the play.
Q123 You want one task to run only on the last host of a batch.
Advanced
Situation read โ Batch-end action.
What I'd do โ
- ansible.builtin.debug: { msg: "last in batch" }
when: inventory_hostname == ansible_play_batch[-1]Why โ ansible_play_batch lists the hosts in the current serial batch, and ansible_play_hosts lists all active hosts in the play.
Interview tip โ run_once combined with serial is the more common route.
Q124 How do you orchestrate steps across tiers where each depends on the previous, like provision, configure, deploy, test?
Advanced
Situation read โ Multi-stage workflow.
What I'd do โ Build a top-level playbook that imports stage playbooks. In AWX, express it as a workflow job template with success/failure edges and approvals.
- import_playbook: provision.yml
- import_playbook: configure.yml
- import_playbook: deploy.yml
- import_playbook: verify.ymlWhy โ Each stage is independently runnable and testable, while the workflow gives order and approval gates.
Interview tip โ Mention approval nodes for production.
Q125 You need to patch hosts in a specific order, lowest-traffic first, and the order is stored as a variable.
Advanced
Situation read โ Custom host ordering that order: cannot express.
What I'd do โ Define explicit numeric tiers per host and run one play per tier, or give serial a fixed ordering through group membership.
# host_vars: patch_wave: 1 / 2 / 3
- hosts: all
gather_facts: false
tasks:
- ansible.builtin.group_by:
key: "wave_{{ patch_wave }}"
- import_playbook: patch.yml
vars: { wave_group: wave_1 }
- import_playbook: patch.yml
vars: { wave_group: wave_2 }with hosts: "{{ wave_group }}" and serial inside patch.yml.
Why โ Play order only supports inventory, reverse_inventory, sorted, reverse_sorted and shuffle; anything else needs explicit grouping.
Interview tip โ If you cannot do it simply, ask whether the ordering is truly required.
Security: Vault, Become and Compliance
๐ฅ Learn this hands-on with DevOps Shack โ YouTube @devopsshack ยท Hindi @shackverse ยท Courses at devopsshack.com
Q126 Database passwords are sitting in plain text in group_vars. How do you fix it?
Beginner
group_vars. How do you fix it?Situation read โ Secrets in Git.
What I'd do โ
- Encrypt the file:
ansible-vault encrypt group_vars/prod/vault.yml. - Keep a plain
vars.ymlthat referencesvault_variables. - Pass the password via
--vault-password-fileor--vault-id. - Rotate any password that was ever committed in plain text.
# group_vars/prod/vars.yml
db_password: "{{ vault_db_password }}"Why โ The prefix pattern keeps names greppable while values stay encrypted.
Interview tip โ Rotating is non-negotiable; Git history still holds the old value.
Q127 You need separate vault passwords for staging and prod.
Intermediate
Situation read โ Different trust domains.
What I'd do โ Use vault IDs.
ansible-vault encrypt --vault-id staging@prompt group_vars/staging/vault.yml
ansible-vault encrypt --vault-id prod@~/.vault_prod group_vars/prod/vault.yml
ansible-playbook site.yml --vault-id staging@~/.vault_stg --vault-id prod@~/.vault_prodWhy โ Each file's header carries its label, and Ansible tries the matching password, so developers can hold staging only.
Interview tip โ Production vault password lives in CI/AWX credentials, not on laptops.
Q128 How do you change the vault password for all encrypted files?
Intermediate
Situation read โ Rotation after someone leaves.
What I'd do โ
ansible-vault rekey --vault-id prod@old_pw_file --new-vault-id prod@new_pw_file group_vars/prod/*.ymlThen rotate the underlying secrets too, because the ex-employee may have read them.
Why โ Rekey protects future access to the files, not secrets already seen.
Interview tip โ Say both: rekey the vault and rotate the secrets.
Q129 A CI pipeline needs the vault password without storing it in the repo.
Intermediate
Situation read โ Secure delivery to automation.
What I'd do โ Store it as a masked CI secret and write it to a temp file or use a script that prints it from a secret manager.
echo "$VAULT_PASS" > "$RUNNER_TEMP/vp" && chmod 600 "$RUNNER_TEMP/vp"
ansible-playbook site.yml --vault-password-file "$RUNNER_TEMP/vp"
shred -u "$RUNNER_TEMP/vp"A cleaner method: --vault-password-file ./vault-pass.sh where the script fetches from AWS Secrets Manager.
Why โ If the file is executable, Ansible runs it and uses stdout.
Interview tip โ Never echo the secret in logs; mask it.
Q130 You want to see the value inside an encrypted file without writing a decrypted copy to disk.
Beginner
Situation read โ Inspecting a secret safely.
What I'd do โ
ansible-vault view group_vars/prod/vault.yml
ansible-vault edit group_vars/prod/vault.ymlWhy โ view shows it in the pager, and edit uses a temp file then re-encrypts.
Interview tip โ Set EDITOR and be careful with shell history for encrypt_string.
Q131 Only one value in a vars file is secret and you want it in the same file as plain values.
Beginner
Situation read โ Inline encryption.
What I'd do โ
ansible-vault encrypt_string --vault-id prod@prompt 's3cr3t' --name 'db_password'Paste the resulting !vault | block into the YAML.
Why โ It keeps diffs readable for non-secret lines.
Interview tip โ Whole-file encryption hides structure from reviewers; inline shows the keys. Choose by team preference.
Q132 A task needs root on the target but your user has only limited sudo rights.
Intermediate
Situation read โ Least-privilege become.
What I'd do โ
- Scope
becometo tasks that need it, not the whole play. - Ask ops to give a sudoers drop-in for specific commands if possible.
- Use
become_userfor service accounts.
- ansible.builtin.command: systemctl restart app
become: true
- ansible.builtin.command: /opt/app/bin/report
become: true
become_user: appsvcWhy โ Minimal escalation reduces blast radius and audit scope.
Interview tip โ NOPASSWD for a service account over a fixed command list is the production norm.
Q133 become_user to an unprivileged account fails with "Failed to set permissions on the temporary files".
Advanced
become_user to an unprivileged account fails with "Failed to set permissions on the temporary files".Situation read โ Both users are unprivileged, so the temp module file isn't readable by become_user.
What I'd do โ Enable pipelining (pipelining = True), which avoids temp files, or install acl so Ansible can use setfacl, or set allow_world_readable_tmpfiles = true (less secure).
[ssh_connection]
pipelining = TrueWhy โ Without pipelining Ansible writes the module as login user and needs the become user to read it.
Interview tip โ Pipelining requires requiretty to be off in sudoers.
Q134 You must prove to auditors which changes were made and by whom.
Intermediate
Situation read โ Audit trail.
What I'd do โ
- Run everything through AWX/CI so each job records user, inventory, commit, and output.
- Forward job events to SIEM.
- Use named SSH users, not shared ones, and sudo logging on targets.
- Enable
log_pathor callbacks (json,ara) on the controller.
Why โ Git tells what was intended; the job log tells what ran.
Interview tip โ ARA Records Ansible gives a searchable run history.
Q135 You are asked to enforce a CIS baseline on 300 Linux hosts and show drift reports.
Advanced
Situation read โ Compliance as code.
What I'd do โ
- Use a maintained role (for example, the CIS role set) or write controls as tasks tagged by control ID.
- Run in
--check --diffmode on a schedule to report drift without changing anything. - Run in enforce mode on a change window.
- Export results to a report.
ansible-playbook cis.yml --check --diff --tags level1 | tee drift-$(date +%F).logWhy โ Check mode as a scheduled audit turns Ansible into a drift detector.
Interview tip โ Be honest that check mode has gaps; pair with OpenSCAP scans.
Q136 A playbook sets ansible_ssh_pass in plain text for a Cisco device.
Intermediate
ansible_ssh_pass in plain text for a Cisco device.Situation read โ Hard-coded password.
What I'd do โ Move the credential to Vault or an AWX credential and reference it via a variable. Prefer key-based auth for SSH.
ansible_password: "{{ vault_cisco_password }}"Why โ Any value in version control must be encrypted, and logs must not show it (no_log).
Interview tip โ AWX credentials inject into jobs without being visible to users.
Q137 How do you disable root SSH login and password authentication across the fleet safely?
Intermediate
Situation read โ High-risk hardening change.
What I'd do โ
- Confirm key-based sudo access works for the Ansible user on a canary.
- Apply with
validateand areloadhandler. - Open a second SSH session before the change.
- Roll with
serial.
- ansible.builtin.copy:
dest: /etc/ssh/sshd_config.d/10-hardening.conf
content: |
PermitRootLogin no
PasswordAuthentication no
mode: "0600"
validate: /usr/sbin/sshd -t -f %s
notify: Reload sshdWhy โ A mistake here removes your own access.
Interview tip โ Note that validate with a drop-in file only validates syntax of the fragment; test the full config when possible.
Q138 A sudo password is required on the targets. How does Ansible get it without prompting each time?
Beginner
Situation read โ Interactive become password.
What I'd do โ Use -K (--ask-become-pass) interactively, or supply ansible_become_password from Vault in unattended runs. Better, use passwordless sudo restricted to needed commands for the automation user.
Why โ Prompting breaks automation; plain text breaks security; vault or sudoers rules are the compromise.
Interview tip โ AWX stores it in a credential.
Q139 A teammate committed .vault_pass to Git. What now?
Beginner
.vault_pass to Git. What now?Situation read โ Leaked master secret.
What I'd do โ
- Treat every vault encrypted with it as compromised.
- Rekey vaults with a new password and rotate the secrets inside.
- Remove the file from history if policy requires (
git filter-repo), but assume it is already exposed. - Add it to
.gitignoreand a pre-commit secret scanner.
Why โ Deleting the file does not delete history or clones.
Interview tip โ Say "rotate first, clean history second".
Q140 You need to store an SSH private key that Ansible deploys to hosts.
Intermediate
Situation read โ Secret file distribution.
What I'd do โ Encrypt the whole key file with vault and use copy with content.
- ansible.builtin.copy:
content: "{{ vault_deploy_key }}\n"
dest: /home/deploy/.ssh/id_ed25519
owner: deploy
mode: "0600"
no_log: trueWhy โ no_log avoids exposing the key in output and diffs.
Interview tip โ Use --diff carefully; it can print file contents. Use no_log or diff: false.
Q141 Running --diff on a template leaks a secret into the CI log.
Intermediate
--diff on a template leaks a secret into the CI log.Situation read โ Diff output reveals file content.
What I'd do โ Disable diff on that task.
- ansible.builtin.template:
src: db.env.j2
dest: /etc/app/db.env
mode: "0600"
diff: false
no_log: trueWhy โ The diff: false task keyword suppresses diff output for the task.
Interview tip โ Both keywords exist: diff shows content differences, no_log hides module args and result.
Q142 A new hire needs access to staging vault only. How do you set that up?
Beginner
Situation read โ Least-privilege secrets.
What I'd do โ Give them only the staging vault ID password and use separate vault files per environment so the prod files remain unreadable.
Why โ The prod password is never shared, so prod files stay opaque to them.
Interview tip โ Combine with separate inventories and CI roles.
Q143 How do you ensure an unattended playbook run cannot execute arbitrary commands via extra vars?
Advanced
Situation read โ User input reaching command/shell is code execution.
What I'd do โ
- Validate inputs with
assertandargument_specs. - Quote with
| quotein shell strings. - Avoid
shellwhen a module exists. - In AWX, use surveys with typed fields and disallow ad hoc
-efor non-admins ("prompt on launch" off).
- ansible.builtin.shell: "rm -rf {{ cleanup_dir | quote }}"Why โ Unvalidated variables into shell lines are injection vectors.
Interview tip โ Mention !unsafe for data that must not template.
Q144 You want to use HashiCorp Vault instead of Ansible Vault.
Advanced
Situation read โ Central secrets management with dynamic secrets.
What I'd do โ
db_password: "{{ lookup('community.hashi_vault.hashi_vault', 'secret=kv/data/prod/db:password auth_method=approle role_id=... secret_id=... url=https://vault.example.com:8200') }}"Use AppRole/JWT or cloud auth, short TTLs, and no_log. Install hvac on the controller.
Why โ Central policy, audit and rotation instead of files in Git.
Interview tip โ AWX can inject credentials via credential lookup plugins for Vault.
Q145 You discover that become tasks leave module temp files in the user's home. How do you reduce that exposure?
Advanced
become tasks leave module temp files in the user's home. How do you reduce that exposure?Situation read โ Temporary files and permissions.
What I'd do โ Enable pipelining to avoid writing modules, set remote_tmp to a protected location, and make sure ansible_remote_tmp is not world-readable.
[defaults]
remote_tmp = /tmp/.ansible-${USER}/tmp
[ssh_connection]
pipelining = TrueWhy โ Pipelining streams the module over stdin and leaves nothing on disk (except for async).
Interview tip โ Pipelining plus sudo requires !requiretty.
Q146 How do you make sure a password given to user module is stored hashed?
Beginner
user module is stored hashed?Situation read โ The user module expects a hash in password:.
What I'd do โ
- ansible.builtin.user:
name: svc
password: "{{ vault_svc_pw | password_hash('sha512', 'fixedsalt') }}"
update_password: on_createWhy โ A fixed salt keeps the hash stable between runs, or update_password: on_create prevents repeated changes.
Interview tip โ Plain text in password: would set a literal (invalid) hash.
Q147 Compliance requires that all package installs come from an internal mirror.
Intermediate
Situation read โ Controlled supply chain.
What I'd do โ Manage repo files with Ansible, remove others, and verify GPG.
- ansible.builtin.yum_repository:
name: internal-base
description: Internal base
baseurl: https://mirror.example.com/rhel9/baseos/
gpgcheck: true
gpgkey: https://mirror.example.com/RPM-GPG-KEY-internal
- ansible.builtin.file: { path: /etc/yum.repos.d/rocky.repo, state: absent }Why โ Ansible enforces the repo list on every run, so drift is corrected.
Interview tip โ Add a firewall rule blocking outbound internet to back it up.
Q148 An engineer asks if ansible_become_pass in an inventory is acceptable.
Beginner
ansible_become_pass in an inventory is acceptable.Situation read โ Secret in inventory.
What I'd do โ Only if the value is vaulted or injected from a credential store; plain text is not acceptable.
Why โ Inventory is checked in and widely readable.
Interview tip โ Offer the alternative: sudoers NOPASSWD for the automation account with limited commands.
Q149 You must rotate the SSH key used by Ansible across all hosts without losing access.
Advanced
Situation read โ Key rotation with rollback safety.
What I'd do โ
- Add the new public key (keep the old one).
- Verify login with the new key on every host.
- Switch the controller/AWX credential.
- Remove the old key.
- ansible.posix.authorized_key:
user: ansible
key: "{{ lookup('file', 'new_ansible.pub') }}"
state: present
# later
- ansible.posix.authorized_key:
user: ansible
key: "{{ lookup('file', 'old_ansible.pub') }}"
state: absentWhy โ Overlap prevents lockouts.
Interview tip โ Use exclusive: true only after you are sure.
Q150 How would you scan your Ansible repo for security problems before merge?
Intermediate
Situation read โ Shift-left.
What I'd do โ In CI run ansible-lint (with the production profile), yamllint, a secret scanner such as gitleaks, and ansible-playbook --syntax-check. Fail the build on findings.
ansible-lint --profile production
gitleaks detect --source .Why โ Cheap automated gates catch plain-text secrets and bad practices before they reach a server.
Interview tip โ ansible-lint profiles go from min to production.
Performance, Testing and CI/CD
๐ฅ Learn this hands-on with DevOps Shack โ YouTube @devopsshack ยท Hindi @shackverse ยท Courses at devopsshack.com
Q151 A playbook that touches 200 hosts takes 40 minutes. Where do you start tuning?
Intermediate
Situation read โ Unknown bottleneck; measure first.
What I'd do โ
- Enable timing callbacks:
callbacks_enabled = profile_tasks, timerinansible.cfg. - Raise
forks(for example 50), enablepipelining, and SSHControlPersist. - Turn off or reduce fact gathering and add fact caching.
- Replace loops of package installs with one
name: [list]call. - Use
asyncfor long independent tasks andstrategy: freewhere safe.
[defaults]
forks = 50
gathering = smart
callbacks_enabled = profile_tasks, timer
[ssh_connection]
pipelining = True
ssh_args = -o ControlMaster=auto -o ControlPersist=60sWhy โ Most time is connection overhead and slow tasks; profiling points at the few that matter.
Interview tip โ Say "measure, then tune" and name profile_tasks.
Q152 You install 15 packages with a loop and it is slow.
Beginner
Situation read โ One module call per package means 15 round trips and 15 package-manager runs.
What I'd do โ
- ansible.builtin.apt:
name: [git, curl, htop, jq, unzip]
state: present
update_cache: true
cache_valid_time: 3600Why โ The package manager resolves everything in one transaction.
Interview tip โ cache_valid_time avoids repeated apt update.
Q153 How would you test a role in CI before it reaches production?
Intermediate
Situation read โ Automated role testing.
What I'd do โ Use Molecule with a container driver (Docker/Podman).
# molecule/default/molecule.yml
driver: { name: docker }
platforms:
- name: ubuntu24
image: geerlingguy/docker-ubuntu2404-ansible
pre_build_image: true
command: ""
privileged: true
provisioner: { name: ansible }
verifier: { name: ansible }molecule test # create, converge, idempotence, verify, destroyWhy โ The sequence proves the role applies, is idempotent, and meets assertions.
Interview tip โ Add a matrix of OS images to check portability.
Q154 What would a Molecule verify.yml check for an Nginx role?
Intermediate
verify.yml check for an Nginx role?Situation read โ Assertions on the end state.
What I'd do โ
- name: Verify
hosts: all
gather_facts: false
tasks:
- ansible.builtin.service_facts:
- ansible.builtin.assert:
that: "ansible_facts.services['nginx.service'].state == 'running'"
- ansible.builtin.uri:
url: http://localhost
status_code: 200Why โ Assert behaviour (running, listening, responding), not implementation details.
Interview tip โ Testinfra (Python) is the older verifier option.
Q155 Molecule's idempotence step fails. How do you find the offending task?
Intermediate
Situation read โ Some task changes on the second run.
What I'd do โ
- Read the log: Molecule prints the tasks that changed.
- Run
molecule convergetwice and look at the second output forchanged:. - Fix with real modules,
changed_when, orcreates.
Why โ Typical causes: command/shell without guards, lineinfile with a bad regexp, templates containing timestamps.
Interview tip โ Never "fix" by skipping the idempotence step.
Q156 Design a CI pipeline for an Ansible repo.
Advanced
Situation read โ End-to-end quality gates.
What I'd do โ
- Lint:
yamllint,ansible-lint. - Syntax:
ansible-playbook --syntax-checkfor each playbook. - Unit/integration: Molecule per changed role.
- Dry run on staging:
--check --diff. - Deploy to staging; smoke tests.
- Manual approval; deploy to prod with
serial.
flowchart LR A["Commit"] --> B["Lint"] --> C["Syntax check"] --> D["Molecule"] --> E["Staging check mode"] --> F["Staging deploy"] --> G["Approval"] --> H["Prod rolling deploy"]
Why โ Cheaper checks run first; expensive ones only after they pass.
Interview tip โ Run only changed roles in Molecule to keep the pipeline fast.
Q157 --check shows no change but the real run changes things. Why?
Advanced
--check shows no change but the real run changes things. Why?Situation read โ Check mode is a prediction.
What I'd do โ Look for tasks that depend on earlier skipped tasks' results, command/shell tasks skipped in check mode (so registered values are empty), and modules without check support.
Why โ If task B reads a file task A would have created, B sees the old state in check mode.
Interview tip โ Use check_mode: false only for read-only tasks, and test in a throwaway environment for full confidence.
Q158 How do you lint playbooks and fail the build only on serious issues?
Beginner
Situation read โ Gradual lint adoption.
What I'd do โ
# .ansible-lint
profile: moderate
skip_list: [yaml[line-length]]
warn_list: [experimental]ansible-lintWhy โ Profiles raise the bar over time (min, basic, moderate, safety, shared, production).
Interview tip โ Use # noqa rule-name sparingly with a comment on why.
Q159 How do you test a playbook that talks to real cloud APIs without paying for resources?
Advanced
Situation read โ Cloud provisioning tests are slow and costly.
What I'd do โ
- Separate provisioning from configuration; test configuration with containers (Molecule).
- Test provisioning against a sandbox account with tagged, auto-expiring resources.
- Use LocalStack for supported AWS services via
endpoint_url. - Always run a
destroyinalways.
Why โ Config logic is where most bugs live and it tests cheaply in containers.
Interview tip โ Tag all test resources and run a nightly janitor.
Q160 A pipeline step must fail if a run had any changed tasks (drift detection).
Intermediate
changed tasks (drift detection).Situation read โ Use Ansible as a drift checker.
What I'd do โ Run in check mode and parse the recap, or use the JSON callback.
ANSIBLE_STDOUT_CALLBACK=json ansible-playbook site.yml --check > out.json
jq '[.stats[] | .changed] | add' out.jsonFail when the sum is greater than zero.
Why โ In check mode changed means "would change", which is drift.
Interview tip โ Schedule it in AWX nightly with notifications.
Q161 Fact gathering is the slowest part of a nightly run. How do you cache facts?
Advanced
Situation read โ Repeated expensive probing.
What I'd do โ
[defaults]
gathering = smart
fact_caching = jsonfile
fact_caching_connection = /var/cache/ansible/facts
fact_caching_timeout = 86400Use Redis for a shared cache across controllers.
Why โ smart gathers only when no valid cache exists.
Interview tip โ Don't cache facts for fast-changing values like free memory in decisions.
Q162 You want an Ansible run to execute on the target host itself, pulling config from Git, instead of pushing from a controller.
Intermediate
Situation read โ Pull model for autoscaled or firewalled hosts.
What I'd do โ Use ansible-pull from cron or a systemd timer, or from user-data at boot.
ansible-pull -U https://git.example.com/infra/ansible.git -C main -i localhost, local.ymlWhy โ Hosts configure themselves and scale without a central push.
Interview tip โ You lose central visibility, so report results to a webhook or use AWX callbacks.
Q163 Your controller runs out of memory with forks=200.
Advanced
forks=200.Situation read โ Each fork is a Python process with the playbook loaded.
What I'd do โ
- Lower forks to what memory allows (roughly 100โ150 MB per fork for big runs).
- Split the inventory with AWX job slicing, or run multiple smaller jobs.
- Reduce the data in hostvars; avoid huge registered results.
- Use
no_logorloop_control.labelto avoid giant output.
Why โ Memory scales with forks and the size of inventory data.
Interview tip โ AWX job slicing is the scalable answer.
Q164 You want a nightly job that runs a safe subset of tasks: health checks only.
Beginner
Situation read โ Tagged read-only tasks.
What I'd do โ
- ansible.builtin.command: df -h /
changed_when: false
tags: [healthcheck, never]ansible-playbook site.yml --tags healthcheckWhy โ The special tag never keeps tasks out of normal runs unless you ask for their other tag.
Interview tip โ always runs every time; never runs only if explicitly selected.
Q165 A teammate asks if tags are enough to protect production from partial runs.
Intermediate
Situation read โ Tags are convenience, not safety.
What I'd do โ Explain they are easy to misuse (a missing tag skips a needed task). For safety, use separate playbooks or workflow nodes, limits enforced in AWX, and approval gates.
Why โ --tags can leave dependencies unexecuted, such as a package install skipped before a config task.
Interview tip โ Use always tags for prerequisites like fact gathering and variable loading.
Q166 How do you run a quick syntax and dry run check on all playbooks locally before pushing?
Beginner
Situation read โ Fast local feedback.
What I'd do โ
ansible-playbook playbooks/*.yml --syntax-check
ansible-lint
yamllint .Add them as a pre-commit hook.
Why โ Syntax check catches parse errors; lint catches bad practice.
Interview tip โ --syntax-check doesn't validate module arguments; Molecule and check mode do.
Q167 A job must produce machine-readable reports for a dashboard.
Advanced
Situation read โ Structured output.
What I'd do โ Use the json or junit callback, or write a CSV from the play.
ANSIBLE_STDOUT_CALLBACK=yaml ansible-playbook site.yml
ANSIBLE_CALLBACKS_ENABLED=junit JUNIT_OUTPUT_DIR=./reports ansible-playbook site.ymlWhy โ JUnit XML plugs into CI test reports natively.
Interview tip โ AWX exposes job events through its REST API too.
Q168 How would you validate Jinja templates without a real server?
Beginner
Situation read โ Template testing.
What I'd do โ Render with ansible localhost -m template or ansible.builtin.template into /tmp in Molecule, then check the output.
ansible localhost -m ansible.builtin.template \
-a "src=templates/app.conf.j2 dest=/tmp/app.conf" -e @tests/vars.ymlRun the target tool's own validator (nginx -t) on the rendered file in Molecule.
Why โ You catch undefined variables and syntax early.
Interview tip โ Keep test vars files in the role's molecule/ folder.
Q169 Playbook runs against 1000 hosts are failing intermittently with SSH timeouts.
Advanced
Situation read โ Likely concurrency overload on the control node or network.
What I'd do โ
- Check forks vs. bastion
MaxStartupsand controller CPU. - Set
timeout = 30andretries = 3under[ssh_connection]. - Reduce forks, enable ControlPersist and pipelining.
- Use
serialto limit batch size.
Why โ Too many simultaneous handshakes drop connections.
Interview tip โ Distinguish "unreachable" (connection) from "failed" (task) in the recap.
Q170 How do you keep a task from running when invoked with --check, because it only makes sense for real runs?
Beginner
--check, because it only makes sense for real runs?Situation read โ Check-mode-aware logic.
What I'd do โ
- ansible.builtin.command: /opt/app/send-metrics
when: not ansible_check_modeWhy โ ansible_check_mode is a special variable that is true during --check.
Interview tip โ ansible_diff_mode is the equivalent for --diff.
Q171 You need to confirm a role runs on both Ubuntu 22.04 and Rocky 9.
Intermediate
Situation read โ Multi-platform testing.
What I'd do โ Add platforms to molecule.yml and pass the image via env var so CI can matrix it.
platforms:
- name: instance
image: "${MOLECULE_DISTRO:-ubuntu2404}"In CI run a job matrix over ubuntu2204, rockylinux9.
Why โ Parallel CI jobs per distro keep wall time low.
Interview tip โ Use images with systemd for service tests.
Q172 How do you promote the same tested change through dev, staging and prod using Git?
Intermediate
Situation read โ Release process.
What I'd do โ Trunk-based: merge to main, pipeline runs on staging automatically, a tag or manual approval triggers prod with the same commit and pinned requirements.
Why โ The artefact (repo + pinned deps / EE image) is identical across environments; only inventory differs.
Interview tip โ Avoid per-environment branches; they drift.
Q173 Developers complain that the Ansible toolchain differs across laptops and CI.
Advanced
Situation read โ Reproducibility.
What I'd do โ Build an Execution Environment with ansible-builder, and run it locally with ansible-navigator.
# execution-environment.yml
version: 3
images:
base_image: { name: quay.io/ansible/ansible-runner:latest }
dependencies:
galaxy: requirements.yml
python: requirements.txt
system: bindep.txtansible-builder build -t acme/ee:1.0
ansible-navigator run site.yml --eei acme/ee:1.0 -m stdoutWhy โ Same image in AWX, CI and laptops means same behaviour.
Interview tip โ EEs replaced Tower's virtualenvs.
Q174 A task intermittently shows changed due to timestamps in a templated file.
Intermediate
changed due to timestamps in a templated file.Situation read โ Non-deterministic template output.
What I'd do โ Remove {{ ansible_date_time.iso8601 }} or similar from templates, or use ansible_managed (a static string).
# {{ ansible_managed }}Why โ Any value that changes per run makes the file differ each time.
Interview tip โ Idempotency means output depends only on inputs.
Q175 You are asked to estimate the effect of a change on production without applying it.
Intermediate
Situation read โ Safe preview.
What I'd do โ
ansible-playbook site.yml -i inventories/prod --check --diff --limit web01,db01Review changes, then run on a canary.
Why โ Check plus diff shows concrete deltas, though not everything.
Interview tip โ Say the preview is advisory; a staged rollout is the real safety.
AWX, Cloud and Large-Scale Operations
๐ฅ Learn this hands-on with DevOps Shack โ YouTube @devopsshack ยท Hindi @shackverse ยท Courses at devopsshack.com
Q176 Your company wants a self-service UI for running playbooks with RBAC. What do you propose?
Beginner
Situation read โ Central execution with access control.
What I'd do โ Deploy AWX (or Red Hat Ansible Automation Platform). Model: Organization, Project (Git), Inventory, Credentials, Job Template, then RBAC roles (Execute, Admin, Read) per team.
Why โ Users can run approved automation without seeing credentials, and every run is logged.
Interview tip โ AWX is the upstream of AAP's automation controller.
Q177 How do you run AWX on Kubernetes?
Beginner
Situation read โ Modern AWX deployment.
What I'd do โ Install the AWX Operator, then create an AWX custom resource.
apiVersion: awx.ansible.com/v1beta1
kind: AWX
metadata: { name: awx }
spec:
service_type: ClusterIP
ingress_type: ingress
hostname: awx.example.comJob pods run in the cluster through container groups.
Why โ The operator manages Postgres, upgrades and the task/web/ee components.
Interview tip โ The old docker-compose installer is gone.
Q178 A job template should prompt for the target limit and a version, with validation.
Intermediate
Situation read โ Safe user input in AWX.
What I'd do โ Enable "Prompt on launch" for limit and add a Survey with typed fields (multiple choice for version).
Why โ A survey constrains values, unlike free-form extra vars.
Interview tip โ Survey answers become extra vars, which have the highest precedence.
Q179 You need provisioning followed by configuration followed by an approval and then deploy.
Intermediate
Situation read โ AWX workflow.
What I'd do โ Build a Workflow Job Template with nodes: provision, configure, approval, deploy; use "on success" and "on failure" edges, and a notification on failure.
Why โ Visual flow, approvals and branching without custom scripting.
Interview tip โ Workflows can pass data between nodes with set_stats.
Q180 A dynamic inventory source in AWX syncs slowly and stale hosts remain.
Intermediate
Situation read โ Inventory sync settings.
What I'd do โ Enable "Overwrite" and "Update on launch", set a cache timeout, and set a schedule.
Why โ Overwrite removes hosts no longer in the source; update-on-launch keeps data fresh per job.
Interview tip โ Use source_vars to apply the same keyed_groups as the CLI plugin.
Q181 You manage 5,000 servers and a single job takes hours.
Advanced
Situation read โ Needs horizontal scaling.
What I'd do โ
- Enable Job Slicing (for example 10 slices) so the inventory is split into parallel jobs.
- Add execution nodes or instance groups.
- Tune forks per template.
- Use fact caching and skip unnecessary gathering.
Why โ Slices run on different nodes in parallel with isolated memory.
Interview tip โ Slicing divides hosts, not tasks, so plays must be host-independent.
Q182 How do you let a team run jobs in a private network without exposing the controller to it?
Advanced
Situation read โ Remote execution.
What I'd do โ Use Receptor mesh with an execution node (or hop node) inside the private network; assign it to an instance group and attach that to the inventory or template.
Why โ The control plane stays central while jobs execute locally to the targets.
Interview tip โ Automation mesh replaced isolated nodes.
Q183 A job template needs the same playbook but different credentials per environment.
Beginner
Situation read โ Credential separation.
What I'd do โ Create separate machine credentials (and vault credentials) and templates per environment, or allow credential prompt-on-launch with RBAC.
Why โ Teams only get Use permission on the credentials for their environment.
Interview tip โ Credentials are never shown after saving, even to admins.
Q184 You must provision AWS infrastructure with Ansible. How would you structure it?
Advanced
Situation read โ Cloud provisioning.
What I'd do โ
- Use
amazon.awsmodules (ec2_instance,ec2_security_group,elb_application_lb). - Run on
localhostwithconnection: local. - Auth with an IAM role or environment credentials, not keys in the repo.
- Make every call idempotent by naming and tagging.
- hosts: localhost
connection: local
gather_facts: false
tasks:
- amazon.aws.ec2_instance:
name: app-01
image_id: "{{ ami }}"
instance_type: t3.small
vpc_subnet_id: "{{ subnet }}"
tags: { Env: prod, Role: app }
state: runningWhy โ Tags identify existing resources, so reruns do not create duplicates.
Interview tip โ Be ready to say Terraform provisions, Ansible configures, and why.
Q185 Terraform creates instances and Ansible must configure them. How do you hand over?
Intermediate
Situation read โ Tool boundary.
What I'd do โ Tag instances in Terraform and use aws_ec2 dynamic inventory in Ansible, or export a Terraform output to an inventory file. Trigger Ansible after apply in CI.
Why โ Tags decouple the tools; no static file to sync.
Interview tip โ cloud-init can bootstrap a minimal Ansible user and Python.
Q186 You need to rotate TLS certificates on 200 hosts without downtime.
Intermediate
Situation read โ Rolling cert update.
What I'd do โ Distribute with copy (vaulted or fetched from a secret store), validate, reload service (not restart), serial: 10%, and verify with openssl s_client or uri.
- ansible.builtin.copy:
src: "{{ cert_src }}"
dest: /etc/ssl/app.pem
mode: "0640"
notify: Reload nginxWhy โ Reload swaps certs without dropping connections.
Interview tip โ Better: automate renewal (ACME) and let Ansible only distribute.
Q187 How do you manage Kubernetes resources with Ansible?
Intermediate
Situation read โ Ansible and k8s.
What I'd do โ Use kubernetes.core.k8s and kubernetes.core.helm modules from localhost.
- kubernetes.core.helm:
name: ingress
chart_ref: ingress-nginx/ingress-nginx
release_namespace: ingress
create_namespace: true
values: { controller: { replicaCount: 3 } }Why โ Good for bootstrapping clusters and glue; GitOps tools (Argo CD) own the steady state.
Interview tip โ Install the kubernetes Python package on the controller.
Q188 A 2 AM incident: a bad config went to all web servers. How do you roll back with Ansible?
Advanced
Situation read โ Fast, controlled rollback.
What I'd do โ
- Check out the last known good commit/tag.
- Run the same playbook with
serialand the previous version variable. - Verify health; notify.
- Fix forward later through the normal pipeline.
git checkout v1.8.3
ansible-playbook deploy.yml -e app_version=1.8.3 --limit webWhy โ Config as code means rollback is a redeploy of an older commit.
Interview tip โ Keep previous release directories on the host for instant symlink rollback.
Q189 How do you onboard 300 existing hand-built servers into Ansible management safely?
Advanced
Situation read โ Brownfield adoption.
What I'd do โ
- Start read-only: inventory and facts audit.
- Write roles to match reality, run in
--check --diffto find drift. - Fix intentional drift in code; fix accidental drift in hosts.
- Roll enforce mode out by tier.
Why โ Jumping straight to enforce can break unknown snowflakes.
Interview tip โ Mention "converge to code, not code to servers" decisions made per diff.
Q190 How would you use Ansible to patch Linux servers monthly?
Advanced
Situation read โ Patch management.
What I'd do โ
- hosts: all
serial: "20%"
tasks:
- ansible.builtin.dnf: { name: "*", state: latest, security: true }
register: upd
- ansible.builtin.reboot:
when: upd is changedSchedule in AWX, patch non-prod a week earlier, and skip hosts in maintenance.
Why โ Rings and batches catch issues early.
Interview tip โ needs-restarting -r decides if a reboot is really required.
Q191 A playbook should run daily and email results only on change or failure.
Intermediate
Situation read โ Schedules and notifications.
What I'd do โ AWX schedule plus a notification template on "failure" and "success" with message templates. Without AWX use cron and the mail module in a final play based on a registered changed count.
Why โ Notify on exception keeps noise low.
Interview tip โ Use separate templates for audit and enforce jobs.
Q192 You need to run a playbook against devices that only support SSH CLI, such as switches.
Intermediate
Situation read โ Network automation.
What I'd do โ Use ansible_connection: ansible.netcommon.network_cli, ansible_network_os, and platform collections.
ansible_connection: ansible.netcommon.network_cli
ansible_network_os: cisco.ios.ios
ansible_become: true
ansible_become_method: enableUse resource modules (for example cisco.ios.ios_vlans) for idempotent config.
Why โ Network modules run on the controller, not the device.
Interview tip โ Use state: gathered and rendered for audit workflows.
Q193 An ops team wants Ansible results visible in a dashboard of what changed where.
Intermediate
Situation read โ Run history and reporting.
What I'd do โ Use AWX job history and its API, or install ARA Records Ansible as a callback for non-AWX runs.
Why โ Searchable run data helps audits and incident review.
Interview tip โ Stream AWX logs to an external aggregator (Splunk/ELK) via logging settings.
Q194 How do you manage per-host differences for hundreds of hosts without hundreds of files?
Advanced
Situation read โ Scalable variable design.
What I'd do โ Define attributes (role, tier, region) as groups or tags, and derive values via group_vars and keyed_groups. Use host_vars only for true exceptions.
Why โ Fewer files, more consistent fleet, easier audit.
Interview tip โ "Cattle not pets": hosts are described by attributes.
Q195 A play needs to destroy a test environment on schedule to save money.
Beginner
Situation read โ Scheduled teardown.
What I'd do โ
- amazon.aws.ec2_instance:
filters: { "tag:Env": test, instance-state-name: running }
state: absentSchedule the job in AWX nightly, and use a protection tag to exempt instances.
Why โ Filters make it declarative and repeatable.
Interview tip โ Dry-run with --check and require approval for anything tagged prod.
Q196 How do you roll out Ansible changes to the automation platform itself safely?
Advanced
Situation read โ Operating the controller.
What I'd do โ Keep AWX/EE versions pinned, upgrade a staging AWX first, take Postgres backups before operator upgrades, test job templates after upgrade.
Why โ The platform is a high-privilege system with credentials to everything.
Interview tip โ Restrict who can edit projects and credentials; treat AWX as production.
Q197 A developer wants to run playbooks directly from their laptop against prod. Your policy?
Intermediate
Situation read โ Change control.
What I'd do โ Allow laptops for dev/staging and --check; require AWX/CI for prod with approvals so credentials stay centralised and runs are logged.
Why โ Personal machines are unaudited and credentials leak.
Interview tip โ Offer break-glass access with logging.
Q198 A new region must be bootstrapped with the exact same stack as an existing one.
Intermediate
Situation read โ Repeatable environment creation.
What I'd do โ Create a new inventory directory (inventories/prod-eu/) with its group_vars, and run the same site playbook; infrastructure comes from the same Terraform module with different variables.
Why โ A parameterised codebase reproduces identically.
Interview tip โ Differences should be only variables and inventory.
Q199 How do you decide between a push model with AWX and ansible-pull for a fleet of 10,000 edge devices?
Advanced
ansible-pull for a fleet of 10,000 edge devices?Situation read โ Scale and connectivity trade-off.
What I'd do โ Edge devices behind NAT and intermittently connected favour pull: they run ansible-pull on a timer. For centrally controlled data-centre fleets, push through AWX with mesh nodes. A hybrid is common: pull for baseline, push for urgent change.
Why โ Pull scales without inbound access but loses real-time orchestration and central logging.
Interview tip โ Add a signed Git tag or commit verification for pull.
Q200 Explain to a manager why you chose Ansible and what its limits are.
Beginner
Situation read โ Business justification.
What I'd do โ Say: agentless, readable YAML, large module ecosystem, good for configuration, orchestration and glue, low learning curve. Limits: not a state-tracking provisioner like Terraform, slower at massive scale than agent-based tools, and large inventories need AWX or tuning.
Why โ Choosing the tool for the job and naming its limits builds trust.
Interview tip โ Pair Ansible with Terraform and GitOps rather than defending it for everything.