Back to interview questions

100+ Ansible Interview Questions and Answers

100+ Ansible Interview Questions and Answers

Explore 120 Ansible interview questions and answers on inventories, playbooks, variables, roles, handlers, idempotence, delegation and safe operations.

Explore 120 Ansible interview questions and answers on inventories, playbooks, variables, roles, handlers, idempotence, delegation and safe operations.

By

Team Sherlock.sh

Add Sherlock as a preferred source on Google

Ansible interviews should reveal whether a candidate can make infrastructure changes repeatable, explain their scope and recognize when a successful run does not prove that a service is healthy. Recruiters should ask candidates to reason about the inventory, the state a task manages and what happens when a host, variable or external dependency behaves unexpectedly.

These 100+ Ansible Interview Questions and Answers cover 120 questions across beginner, intermediate and experienced levels. They progress from inventories, playbooks and idempotence to roles, variable behavior, orchestration and operational safeguards. Practical examples help interviewers evaluate both YAML fluency and the judgment needed to automate changes across different systems.

How can recruiters distinguish genuine Ansible experience from a memorized playbook?

Ask the candidate to explain which hosts a play targets and predict the second run before changing one condition: a task fails, a variable is overridden or the play runs in batches. Strong candidates can trace the effect on handlers, registered results and later tasks. They also distinguish what a module guarantees from the checks needed to establish that an application is working.

Sherlock AI helps hiring teams assess signals of potential AI cheating, deepfakes, impersonation and unauthorized assistance during remote interviews. Combine those signals with playbook walkthroughs and follow-up questions about expected changes and failure behavior. Use them as context for a fair review alongside demonstrated understanding, rather than as conclusive proof of misconduct.

Ansible Interview Questions

Choose questions that match the role’s configuration-management and deployment responsibilities. Supply the relevant inventory, variable values and platform context, and ask candidates to predict outcomes before proposing changes. The complete question bank appears first, followed by identically numbered answers.

Ansible Interview Questions for Beginners

Check the candidate’s understanding of inventories, tasks, modules and desired state. Small examples should reveal whether they can identify the target hosts, distinguish controller work from managed-node work and explain why a second run may differ from the first.

  1. What problem does Ansible solve?

  2. How do ansible-core and the Ansible community package differ?

  3. What is the difference between a control node and a managed node?

  4. What does agentless mean in Ansible?

  5. Which platforms can act as Ansible controllers or managed targets?

  6. Why does Python availability matter on managed Unix-like hosts?

  7. What is an Ansible inventory?

  8. How do inventory groups help organize a playbook?

  9. How do an inventory hostname and ansible_host differ?

  10. How can you inspect inventory without running configuration tasks?

  11. What does the hosts field in a play select?

  12. What does --limit do when running a playbook?

  13. How are a playbook, a play and a task related?

  14. Why does YAML indentation matter in an Ansible playbook?

  15. What is an Ansible module, and why prefer it to a generic command?

  16. What is a fully qualified collection name?

  17. What does desired state mean in an Ansible task?

  18. What is idempotence, and how would you check it?

  19. What is the difference between an OK result and a changed result?

  20. How do command and shell differ?

  21. Why is command argv useful?

  22. How can creates make a command safer to rerun?

  23. When would you use copy rather than template?

  24. Where are template source files rendered?

  25. How do you define and use a simple play variable?

  26. What does register store?

  27. What are Ansible facts?

  28. When would you disable automatic fact gathering?

  29. How do you write a simple when condition?

  30. How can you handle an optional variable without hiding a required one?

  31. How does a basic loop operate over a list?

  32. How does register behave on a looped task?

  33. What is a handler, and when is it notified?

  34. Why is a handler not the same as the next ordinary task?

  35. What does become do?

  36. What does check mode tell you, and what can it miss?

  37. What does diff mode add, and why must its output be handled carefully?

  38. What is an ad hoc Ansible command useful for?

  39. What does ansible.builtin.ping actually test?

  40. How would you begin troubleshooting an unfamiliar Ansible failure?

Ansible Interview Questions for Intermediate

Explore how the candidate organizes reusable automation and handles variables, facts, handlers and errors. Ask for the value or execution order they expect, then introduce an override or a partial failure.

  1. How would you investigate a variable that ignores an inventory override?

  2. How do play, task and host variable scopes affect later tasks?

  3. How do you preserve Boolean and numeric types when passing extra variables?

  4. When does the default filter preserve false, zero and empty values?

  5. Why use default(omit) for an optional module parameter?

  6. When would you use mandatory instead of assert to validate input?

  7. How do you merge nested configuration dictionaries without accidentally replacing lists?

  8. Why can dictionary bracket notation be safer than dot notation in templates?

  9. How do you select and transform a list of host or service records?

  10. Why might hostvars contain an inventory variable but not a requested fact?

  11. How should a role separate tasks, handlers, templates and static files?

  12. Which role settings belong in defaults rather than vars?

  13. How do role dependencies affect execution order and repeated execution?

  14. How can a role validate its public arguments before running its main work?

  15. How can module_defaults reduce repetition without making role behavior surprising?

  16. How do you make collection dependencies reproducible across runners?

  17. When are variables from an included role visible outside that role?

  18. How do you choose between import_tasks and include_tasks?

  19. How do you repeat a group of tasks for each application?

  20. Why does tagging an include not necessarily tag the tasks it includes?

  21. How can you gather only the facts a playbook actually needs?

  22. How should a task decide whether cached facts are fresh enough to use?

  23. Why can clear_facts leave a value created by cacheable set_fact visible?

  24. How do you expand parent records and their child lists without losing context?

  25. How does until behave when a task also has a loop?

  26. How do you prevent nested loops from overwriting each other’s item value?

  27. Does loop_control label protect sensitive fields in loop items?

  28. How would you make a command task report changes accurately?

  29. Why can a list of failed_when conditions fail to catch an error?

  30. How does listen let several handlers respond to one notification?

  31. What happens if a handler is notified before and after flush_handlers?

  32. What does force_handlers change after a task failure?

  33. How do you use rescue without hiding a failed operation?

  34. Why is an always section not a guarantee that cleanup will run?

  35. Which host does inventory_hostname refer to in a delegated task?

  36. How does delegate_facts change where gathered facts are stored?

  37. How do serial and forks limit different parts of execution?

  38. When is throttle useful even if serial and forks are already configured?

  39. What remains exposed after a variable is protected with Ansible Vault?

  40. How do you retain useful diagnostics when using no_log?

Ansible Interview Questions for Experienced

Probe the candidate’s reasoning about concurrent work, failure boundaries, secrets and changes that span systems. Ask which guarantees Ansible provides and which require application checks or external coordination.

  1. How does run_once behave when a play uses serial batches?

  2. Why can delegated tasks race when they all write the same file?

  3. When can the free strategy violate a playbook’s coordination assumptions?

  4. How would you distinguish connection, task and asynchronous runtime timeouts?

  5. What does poll: 0 leave unfinished from an orchestration perspective?

  6. How should asynchronous job cleanup be handled?

  7. How does max_fail_percentage affect a rolling deployment?

  8. When is any_errors_fatal useful, and what does it not guarantee?

  9. How can handler name collisions change which operation runs?

  10. Why is block/rescue not equivalent to a database transaction?

  11. What makes a playbook rollback plan credible?

  12. How would you structure a rolling deployment around service health?

  13. How can a template be validated before replacing a live configuration file?

  14. Why can a derived set_fact value stop tracking changes to its input?

  15. How would you distinguish configuration drift from an intentionally unmanaged setting?

  16. When should you fetch a file instead of loading it with slurp?

  17. Why does a lookup’s execution location matter?

  18. What changed in the template trust model in ansible-core 2.19?

  19. How should later tasks handle a registered result from a skipped task?

  20. Why is constructing a conditional expression as a string fragile?

  21. Do different Vault IDs create separate access-control boundaries?

  22. How does rekeying a vault differ from rotating the secret stored inside it?

  23. How would you manage secret-bearing destination files and their backups?

  24. What changes when copy uses remote_src: true?

  25. Why can a task work over one connection type and fail over another?

  26. Why can the same playbook use a different ansible.cfg in another working directory?

  27. How would you review a third-party collection before trusting it in a privileged workflow?

  28. How can stale dynamic inventory cause a correct playbook to target the wrong machine?

  29. How do end_host, end_batch and end_play change a recovery workflow?

  30. What changes when add_host creates inventory entries during a playbook run?

  31. Why does serial: 1 not protect against two simultaneous playbook runs?

  32. How would you respect an API rate limit from Ansible?

  33. How should a playbook retry an API call after an uncertain timeout?

  34. What should a custom module’s changed result mean?

  35. How should a custom module implement check mode honestly?

  36. Why can explicitly defining localhost change the Python used for delegated work?

  37. How would you plan an ansible-core or collection upgrade?

  38. Why can rerunning only failed hosts be unsafe after a partial deployment?

  39. How would you validate that an Ansible run changed only its intended scope?

  40. How would you make a lineinfile edit converge without leaving duplicate configuration keys?

Ansible Interview Questions and Answers

Examples use ansible-core 2.21 behavior unless an answer identifies another version boundary. Module availability and target requirements also depend on the installed collection and managed platform. A control node, a Unix-like managed node, a Windows host and a network device do not share identical execution requirements. Short task fragments belong inside a play or role; complete plays identify their hosts and other required context.

Ansible Interview Questions and Answers for Beginners

These answers establish the foundations of Ansible execution and playbook syntax. They connect common modules and keywords to concrete results and explain where platform requirements or module support affect an example.

1. What problem does Ansible solve?

Ansible automates repeatable work across systems by connecting to selected targets and executing tasks that describe actions or desired state. It can configure files, manage packages and coordinate deployments, while inventory and variables determine which systems receive which configuration.

For example, a playbook can state that a configuration file must contain a particular rendered value instead of asking an operator to edit every host manually. The benefit is a reviewable procedure that can be rerun and inspected. Ansible does not automatically make an unsafe command safe or turn an unclear operational requirement into a correct configuration; the playbook author still defines the intended outcome and verification.

2. How do ansible-core and the Ansible community package differ?

ansible-core supplies the execution engine, command-line tools and built-in content. The larger Ansible community package combines a compatible core release with a curated set of collections. Collections can also be installed separately, so the package name alone does not describe every module available in an environment.

If a playbook calls a cloud or Windows module, I would check the required collection and its version rather than assume installing ansible-core includes it. I would record both the core version and collection dependencies for reproducibility. Core and community-package version numbers follow different release lines, so comparing them as if they were the same product version is misleading.

3. What is the difference between a control node and a managed node?

The control node runs Ansible and coordinates execution. A managed node is a target whose state or behavior Ansible controls. The inventory describes targets, while connection plugins and modules determine how the controller interacts with them.

A Linux workstation can act as the controller for several Linux servers, but a task may also target localhost. Files referenced as a template source normally live on the controller, while their destination is on the managed node. That distinction matters when troubleshooting “file not found”: the same path string can refer to different machines depending on the module and parameter.

4. What does agentless mean in Ansible?

Agentless generally means Ansible does not require its own continuously running agent on every managed host. It uses supported connection methods and executes the necessary module work, rather than relying on an Ansible-specific daemon installed everywhere.

It does not mean the target has no prerequisites. Unix-like targets commonly need SSH access and a suitable Python interpreter for many modules; Windows and network devices have different connection and execution requirements. I would identify the target platform and module requirements before promising that a machine can be managed without any preparation. Authentication, permissions and network reachability still have to be established.

5. Which platforms can act as Ansible controllers or managed targets?

A controller must meet the supported operating-system and Python requirements of the installed ansible-core release. Unix-like environments are the conventional controller platforms; native Windows is not a supported control-node platform in the same way, although supported Linux environments can be used from Windows setups.

Managed targets are broader and can include Unix-like hosts, Windows systems, network equipment and services accessed through APIs. They are not all managed with the same modules or transport. I would check the current support matrix and collection documentation for the actual platform, rather than assume that a playbook using a Linux package module can be run unchanged against Windows.

6. Why does Python availability matter on managed Unix-like hosts?

Many Ansible modules execute Python code on the managed Unix-like host, so that host needs an interpreter compatible with the installed Ansible release and module. The controller’s Python interpreter and the target’s interpreter are separate requirements.

If SSH works but a simple module fails with an interpreter error, I would inspect the discovered interpreter and the target’s supported Python installation. The raw module is a special tool that can run commands without the normal Python module subsystem, but it is not a reason to ignore prerequisites for later tasks. Interpreter configuration should be explicit when discovery would choose the wrong environment.

7. What is an Ansible inventory?

Inventory identifies the hosts Ansible can target and organizes them into groups with relevant variables. It can come from static files, inventory plugins or other supported sources. Inventory is not merely a list of IP addresses: host aliases, group membership and connection settings influence execution.

all:
  children:
    web:
      hosts:
        web01:
          ansible_host: 192.0.2.10
        web02:
          ansible_host: 192.0.2.11
all:
  children:
    web:
      hosts:
        web01:
          ansible_host: 192.0.2.10
        web02:
          ansible_host: 192.0.2.11
all:
  children:
    web:
      hosts:
        web01:
          ansible_host: 192.0.2.10
        web02:
          ansible_host: 192.0.2.11

This illustrative inventory uses documentation-only addresses and does not imply reachable hosts. The names web01 and web02 are inventory identities, while ansible_host supplies connection destinations. I would validate the resolved inventory before running changes, especially when several inventory sources are combined.

8. How do inventory groups help organize a playbook?

Groups let a play target a meaningful set of hosts and share relevant variables. A host can belong to several groups, such as web and staging, so group membership can express different dimensions of the environment.

I might select all staging web hosts for a deployment rehearsal while retaining separate database and worker groups. Grouping does not duplicate a host into several independent machines; it gives the same inventory host multiple memberships. I would use clear group names and inspect the resulting memberships because an incorrect group can expand the scope of a change before any task logic runs.

9. How do an inventory hostname and ansible_host differ?

The inventory hostname is Ansible’s logical identity for a host. ansible_host supplies the address or hostname used to connect when it differs. Keeping them distinct allows a stable inventory label while the connection address changes.

For example, app_primary can connect to 192.0.2.20 through ansible_host. Play patterns and host-variable references use the inventory identity, not necessarily that address. I would avoid defining the same real machine under several aliases unintentionally, because Ansible can then treat those aliases as separate inventory hosts and run work more than once against the same system.

10. How can you inspect inventory without running configuration tasks?

Use inventory inspection commands to view the resolved hosts, groups and variables before selecting a target set. This separates scope validation from execution and can reveal a malformed inventory or unexpected membership early.

ansible-inventory -i inventory.yml --graph
ansible-inventory -i inventory.yml --host

ansible-inventory -i inventory.yml --graph
ansible-inventory -i inventory.yml --host

ansible-inventory -i inventory.yml --graph
ansible-inventory -i inventory.yml --host

The graph helps verify group relationships, while the host view shows the variables resolved for a particular inventory host. The commands still depend on the chosen inventory source; a dynamic inventory plugin may contact its configured service to discover hosts. I would also avoid sharing raw variable output if it contains credentials or other sensitive values.

11. What does the hosts field in a play select?

The hosts field is an inventory pattern identifying the hosts on which the play applies. It can name a host, a group or a combination of patterns. It does not create a host merely because a name appears there.

- name: Inspect selected web hosts
  hosts: web
  gather_facts: false
  tasks:
    - name: Show selected inventory identity
      ansible.builtin.debug:
        var

- name: Inspect selected web hosts
  hosts: web
  gather_facts: false
  tasks:
    - name: Show selected inventory identity
      ansible.builtin.debug:
        var

- name: Inspect selected web hosts
  hosts: web
  gather_facts: false
  tasks:
    - name: Show selected inventory identity
      ansible.builtin.debug:
        var

This play reports the inventory identities in the web group. If the group is absent or a limit excludes all its hosts, no matching work will run. Before a change, I would inspect the selected hosts rather than interpret an empty successful-looking run as evidence that the intended systems were configured.

12. What does --limit do when running a playbook?

--limit narrows the inventory hosts eligible for a run in addition to the play’s own hosts pattern. It is useful for selecting a small test subset, but it does not replace correct inventory design or a review of what the tasks do.

ansible-playbook -i inventory.yml site.yml --limit web01 --list-hosts
ansible-playbook -i inventory.yml site.yml --limit web01 --list-hosts
ansible-playbook -i inventory.yml site.yml --limit web01 --list-hosts

This lists the hosts that would be selected without executing the playbook’s tasks. A host must satisfy the play selection and the limit. I would check that the result includes the intended host and excludes others before removing --list-hosts for an authorized run. A misspelled limit can yield no useful work rather than a configuration success.

13. How are a playbook, a play and a task related?

A playbook is an ordered list of plays. Each play selects hosts and defines settings and tasks for those hosts. A task invokes a module or another supported action to perform one unit of work.

- name: Explain a local play
  hosts: localhost
  connection: local
  gather_facts: false
  tasks:
    - name: Report the example purpose
      ansible.builtin.debug:
        msg: "This task runs in one local play."
- name: Explain a local play
  hosts: localhost
  connection: local
  gather_facts: false
  tasks:
    - name: Report the example purpose
      ansible.builtin.debug:
        msg: "This task runs in one local play."
- name: Explain a local play
  hosts: localhost
  connection: local
  gather_facts: false
  tasks:
    - name: Report the example purpose
      ansible.builtin.debug:
        msg: "This task runs in one local play."

This is a complete playbook with one play and one task. A tasks-only list copied from documentation is not automatically a complete playbook; it needs the surrounding play or role context. Understanding that structure makes YAML indentation errors and misplaced keywords easier to diagnose.

14. Why does YAML indentation matter in an Ansible playbook?

YAML indentation expresses structure. A keyword at play level has a different meaning from a keyword inside a task or module argument mapping, and tabs should not be used for indentation. Valid YAML can still be invalid Ansible if a field appears in the wrong context.

For example, register belongs beside the module invocation as a task keyword, not inside the module’s arguments. I would keep indentation consistent and use syntax checking to catch structural errors. Quoting values that resemble booleans or numbers can also matter when the intended value is text, although unnecessary quoting should not be used to hide a type mismatch the module expects to validate.

15. What is an Ansible module, and why prefer it to a generic command?

A module is a unit of Ansible functionality with defined inputs, behavior and results. A purpose-built module can understand state and report whether it changed, whereas a generic command often lacks that knowledge unless the author supplies suitable guards and result interpretation.

For example, a file module can ensure a directory exists with a required mode. Repeatedly invoking mkdir through a command would require handling the already-exists case and reporting change accurately. Modules still have limitations and platform requirements, so I would read the module documentation instead of assuming every module is idempotent in every mode.

16. What is a fully qualified collection name?

A fully qualified collection name, or FQCN, identifies content by namespace, collection and plugin name, such as ansible.builtin.copy. It makes the selected implementation clear and avoids ambiguity when different collections provide similarly named modules.

Using ansible.builtin.debug explicitly also helps reviewers find the correct documentation. Short names can work in many contexts, but they obscure the dependency when several collections are involved. I would pin the necessary collection versions separately; writing an FQCN identifies the content but does not freeze its version or guarantee that it is installed.

17. What does desired state mean in an Ansible task?

Desired state describes the condition that should hold after a task, rather than only the sequence of shell commands to attempt. The module compares relevant current state with the requested state and performs the supported adjustment when needed.

- name: Ensure the example directory exists
  ansible.builtin.file:
    path: "{{ scratch_dir }}/reports"
    state: directory
    mode: "0700"
- name: Ensure the example directory exists
  ansible.builtin.file:
    path: "{{ scratch_dir }}/reports"
    state: directory
    mode: "0700"
- name: Ensure the example directory exists
  ansible.builtin.file:
    path: "{{ scratch_dir }}/reports"
    state: directory
    mode: "0700"

This task fragment assumes scratch_dir is an explicitly supplied disposable directory. If the directory already exists with the requested mode, no adjustment should be needed. Desired state is limited to the properties expressed in the task: creating a directory does not establish that its application content is valid or that the surrounding service is healthy.

18. What is idempotence, and how would you check it?

An idempotent operation reaches the requested state without making another change merely because it is repeated with the same inputs and relevant environment. In Ansible, a useful check is to run a bounded fixture twice and inspect whether the second run reports unnecessary changes.

If a copy task writes fixed content, the first run may change the file and the second should usually report no change. But a template containing the current time can change on every run even though the template module itself compares content correctly. I would inspect both the resulting state and change reporting; a task forced to say “unchanged” is not necessarily safe or idempotent.

19. What is the difference between an OK result and a changed result?

An OK result means the task completed successfully; changed indicates that it also reports a modification or action classified as a change. The distinction helps identify drift and controls mechanisms such as handler notification.

A file already containing the desired content can complete successfully without changed, while replacing that content should report changed. A generic command may report changed even if it only printed information unless the playbook specifies appropriate reporting. I would not equate changed with failure or assume OK proves the entire application works; both are task-level results that need to match the task’s actual purpose.

20. How do command and shell differ?

ansible.builtin.command executes a program without passing the command through a shell. Shell metacharacters such as pipes and redirection therefore do not have their usual shell meaning. ansible.builtin.shell runs through a shell and is appropriate only when its features are actually needed.

- name: Print a literal value without a shell
  ansible.builtin.command:
    argv:
      - /usr/bin/printf
      - "%s\n"
      - "hello | world"
    expand_argument_vars: false
  changed_when: false
- name: Print a literal value without a shell
  ansible.builtin.command:
    argv:
      - /usr/bin/printf
      - "%s\n"
      - "hello | world"
    expand_argument_vars: false
  changed_when: false
- name: Print a literal value without a shell
  ansible.builtin.command:
    argv:
      - /usr/bin/printf
      - "%s\n"
      - "hello | world"
    expand_argument_vars: false
  changed_when: false

This task prints the pipe character as data. The executable path is an example for a Unix-like target and must exist there. Modern command versions can expand argument environment variables through Python, so disabling expand_argument_vars makes this literal example explicit. A shell increases quoting and injection responsibilities; prefer a module or command when no shell interpretation is required.

21. Why is command argv useful?

The argv form supplies an explicit argument list, preserving boundaries without relying on a shell-like command string to split values. It is especially helpful when an argument contains spaces or punctuation.

- name: Preserve a value containing spaces
  ansible.builtin.command:
    argv:
      - /usr/bin/printf
      - "%s\n"
      - "two words"
    expand_argument_vars: false
  register: printed_value
  changed_when: false
- name: Preserve a value containing spaces
  ansible.builtin.command:
    argv:
      - /usr/bin/printf
      - "%s\n"
      - "two words"
    expand_argument_vars: false
  register: printed_value
  changed_when: false
- name: Preserve a value containing spaces
  ansible.builtin.command:
    argv:
      - /usr/bin/printf
      - "%s\n"
      - "two words"
    expand_argument_vars: false
  register: printed_value
  changed_when: false

The final argument remains one value, and stdout is two words. This does not validate whether the program itself interprets an argument as an option or a dangerous instruction, so external input still needs an appropriate contract. argv solves argument separation, not every security or correctness issue in the command being invoked.

22. How can creates make a command safer to rerun?

The command module’s creates parameter skips execution when the specified path already exists. It can provide a useful guard for a one-time initialization step, but the existence of a file is only as strong a completion signal as the process that creates it.

If a setup command creates its marker before finishing and then fails, later runs may skip incomplete work. I would choose a reliable output or completion marker and consider whether changed input should invalidate it. A creates guard is not a general desired-state comparison: it will not notice that the file’s contents are stale or that the initialization contract has changed.

23. When would you use copy rather than template?

Use copy for content that should be transferred as a file or supplied literally; use template when controller-side Jinja rendering should produce host-specific content. The choice depends on whether values need substitution, not simply on the file extension.

- name: Write fixed example text
  ansible.builtin.copy:
    content: "managed example\n"
    dest: "{{ scratch_dir }}/notice.txt"
    mode: "0600"
- name: Write fixed example text
  ansible.builtin.copy:
    content: "managed example\n"
    dest: "{{ scratch_dir }}/notice.txt"
    mode: "0600"
- name: Write fixed example text
  ansible.builtin.copy:
    content: "managed example\n"
    dest: "{{ scratch_dir }}/notice.txt"
    mode: "0600"

This task fragment writes the same text for every selected target and assumes scratch_dir exists. A template could instead render a port or environment name from variables. I would specify ownership and mode where the real destination requires them, and avoid putting secrets into content that will be exposed through logs or diff output.

24. Where are template source files rendered?

The template module reads its source on the controller and renders it with the relevant variables before placing the result on the managed target. The source path and destination path therefore refer to different sides of the connection in the normal workflow.

A source file containing port={{ service_port }} can produce different configuration content for each host. I would validate that service_port has the expected type and value and use the module’s supported validation facility when the application offers a configuration checker. Successful rendering only proves the template produced text; it does not prove the target application accepts that text.

25. How do you define and use a simple play variable?

A play variable gives a value a meaningful name that tasks can reference through Jinja expressions. Keeping the value separate from the task makes the play easier to adapt and reduces repeated literal strings.

- name: Demonstrate a play variable
  hosts: localhost
  connection: local
  gather_facts: false
  vars:
    environment_name: training
  tasks:
    - name: Show the selected environment
      ansible.builtin.debug:
        msg: "Environment: {{ environment_name }}"
- name: Demonstrate a play variable
  hosts: localhost
  connection: local
  gather_facts: false
  vars:
    environment_name: training
  tasks:
    - name: Show the selected environment
      ansible.builtin.debug:
        msg: "Environment: {{ environment_name }}"
- name: Demonstrate a play variable
  hosts: localhost
  connection: local
  gather_facts: false
  vars:
    environment_name: training
  tasks:
    - name: Show the selected environment
      ansible.builtin.debug:
        msg: "Environment: {{ environment_name }}"

This prints Environment: training. Quoting a YAML value that starts with a Jinja expression avoids parsing ambiguity. I would choose clear names and inspect where a value is defined if the result differs from expectation, because inventory and other variable sources can also participate in the final value.

26. What does register store?

Register stores a task’s result in a variable for subsequent tasks in the relevant host context. The result is a structured object whose fields depend on the module and execution outcome, rather than just the text printed by the task.

- name: Read a fixed value
  ansible.builtin.command:
    argv: [/usr/bin/printf, "%s\n", ready]
    expand_argument_vars: false
  register: readiness
  changed_when: false

- name: Show command output
  ansible.builtin.debug:
    var

- name: Read a fixed value
  ansible.builtin.command:
    argv: [/usr/bin/printf, "%s\n", ready]
    expand_argument_vars: false
  register: readiness
  changed_when: false

- name: Show command output
  ansible.builtin.debug:
    var

- name: Read a fixed value
  ansible.builtin.command:
    argv: [/usr/bin/printf, "%s\n", ready]
    expand_argument_vars: false
  register: readiness
  changed_when: false

- name: Show command output
  ansible.builtin.debug:
    var

For this successful command, stdout is ready. Other useful fields can include rc, stderr and changed. I would inspect the documented return structure and handle skipped or failed tasks before assuming a field exists. A registered result is not automatically written back to inventory or persisted for future runs.

27. What are Ansible facts?

Facts are information gathered about a managed host, such as its operating-system family, interfaces or interpreter details, and made available for task logic. Gathering them is work performed against the target, not a guarantee that every possible host attribute is known.

A play can use ansible_facts['os_family'] to select a suitable configuration path. I would distinguish discovered facts from inventory variables that describe intended configuration. Facts can become stale during a long run if the host changes, and gathering may fail when connection or interpreter prerequisites are missing. Sensitive environment details should not be dumped into shared logs unnecessarily.

28. When would you disable automatic fact gathering?

I would set gather_facts to false when a play does not need facts, when a targeted discovery step is sufficient or when initial setup must happen before ordinary fact modules can run. It can reduce unnecessary work, but tasks must not then assume facts have been populated.

A local debug-only demonstration does not need a full host inventory, so disabling gathering makes its dependency smaller. A task conditioned on operating-system facts does need those values, either from gathering or an explicitly justified source. I would not disable facts merely to make a failing run appear successful; the missing prerequisite still needs to be addressed if later tasks require it.

29. How do you write a simple when condition?

A when condition is a Jinja expression evaluated for the task’s host; it does not need surrounding {{ }} delimiters. It should evaluate to a boolean condition rather than depend on accidental truthiness of a string.

- name: Explain an enabled option
  ansible.builtin.debug:
    msg: "The option is enabled."
  when

- name: Explain an enabled option
  ansible.builtin.debug:
    msg: "The option is enabled."
  when

- name: Explain an enabled option
  ansible.builtin.debug:
    msg: "The option is enabled."
  when

This task fragment expects feature_enabled to be supplied. The bool filter is useful when an agreed input representation needs conversion, but input validation should still reject values outside the contract. Modern Ansible versions enforce conditional typing more strictly, so I would use explicit comparisons or boolean values rather than a quoted string such as “false” and assume it behaves like a boolean.

30. How can you handle an optional variable without hiding a required one?

The default filter can provide a fallback when a variable is undefined, but the fallback should be semantically valid. A required deployment value should normally fail with a clear assertion rather than silently receive an arbitrary default.

- name: Display an optional label
  ansible.builtin.debug:
    msg: "Label: {{ optional_label | default('unlabeled') }}"
- name: Display an optional label
  ansible.builtin.debug:
    msg: "Label: {{ optional_label | default('unlabeled') }}"
- name: Display an optional label
  ansible.builtin.debug:
    msg: "Label: {{ optional_label | default('unlabeled') }}"

This fragment prints unlabeled if the variable is undefined. By default, default does not replace every false-like value; an explicitly empty string is a different case. I would distinguish “not supplied” from “supplied but empty” when that matters, and avoid using a default production hostname or credential that could redirect work unexpectedly.

31. How does a basic loop operate over a list?

A loop repeats a task for each item, with the current value available as item unless the loop variable is customized. The module still runs separately for those items, and the result can differ for each one.

- name: Show each requested component
  ansible.builtin.debug:
    msg: "Component: {{ item }}"
  loop

- name: Show each requested component
  ansible.builtin.debug:
    msg: "Component: {{ item }}"
  loop

- name: Show each requested component
  ansible.builtin.debug:
    msg: "Component: {{ item }}"
  loop

The messages identify api and worker. For modules that accept a list natively, supplying the list directly can be more appropriate than creating many separate task invocations. I would also avoid treating loop order as a substitute for a well-defined dependency plan when the items affect one another.

32. How does register behave on a looped task?

A registered loop result contains a results list with per-item results. It is not equivalent to the single-result structure from a task that ran once, so accessing the top-level stdout as if only one command ran is a common mistake.

If a command loop checks two independent tools, I would inspect each element’s item, rc and stdout and explain which item failed. The aggregate task can report failure when an item fails, while still retaining results from other iterations. For a simple reporting loop, the returned item context is useful evidence; I would not discard it and present only the last output as the result of the whole loop.

33. What is a handler, and when is it notified?

A handler is a named task that runs when another task notifies it after reporting a change. It is useful for follow-up work that should occur only when configuration changes, such as reloading an application after a relevant file update.

If three tasks notify the same handler before the normal handler execution point, the handler is normally run once for that host rather than once per notification. A task that reports no change does not notify it. I would give handlers clear names and ensure the notifying task’s changed reporting is accurate; otherwise a necessary follow-up may be skipped or an unnecessary one triggered.

34. Why is a handler not the same as the next ordinary task?

An ordinary task follows the play’s task flow whether or not a previous task changed, subject to its conditions. A notified handler normally runs at designated handler execution points rather than immediately after the notifying task. This timing allows several related changes to trigger one follow-up.

If a later task requires a service to have already reloaded its new configuration, placing the reload only in a handler may not satisfy that dependency at that moment. I would examine the ordering deliberately rather than assume notify means “run now.” The appropriate design can include an explicit handler flush or a different task sequence, depending on the required behavior.

35. What does become do?

Become enables privilege escalation for tasks using a configured method, such as sudo on a suitable Unix-like target. It is separate from the connection identity: connecting as one user and executing a task as another are distinct steps.

For example, a deployment account might connect over SSH while a specific task uses elevated permissions to update an application-owned path. Setting become_user alone does not necessarily enable escalation; the task or play must enable become as required. I would scope privilege to the tasks that need it and confirm the target’s permitted escalation method rather than assume every connection user can become root.

36. What does check mode tell you, and what can it miss?

Check mode asks supporting modules to predict changes without applying them. It is useful for reviewing likely effects, but its coverage depends on module support and on whether later tasks require real outputs from earlier changes.

ansible-playbook -i inventory.yml site.yml --check
ansible-playbook -i inventory.yml site.yml --check
ansible-playbook -i inventory.yml site.yml --check

A task explicitly configured with check_mode: false can still run normally during a check-mode invocation, so the playbook must be reviewed before treating the flag as a no-change guarantee. Commands may be skipped or only partially supported, and conditional paths can differ when preceding work was simulated. I would combine check mode with syntax validation and a bounded real rehearsal where appropriate.

37. What does diff mode add, and why must its output be handled carefully?

Diff mode asks supporting modules to show before-and-after differences, such as changes to file content. Combined with check mode, it can make a proposed configuration edit easier to review without applying the supported change.

ansible-playbook -i inventory.yml site.yml --check --diff
ansible-playbook -i inventory.yml site.yml --check --diff
ansible-playbook -i inventory.yml site.yml --check --diff

A diff may reveal passwords, tokens or private configuration values, so it should not be enabled indiscriminately for secret-bearing tasks. It also depends on module support and does not prove that the application will accept the changed content. I would disable diff for sensitive tasks and use relevant configuration validation rather than treat a readable text difference as complete deployment verification.

38. What is an ad hoc Ansible command useful for?

An ad hoc command runs a module against selected inventory hosts without writing a full playbook. It is useful for a small, well-understood inspection or one-off action, while repeatable multi-step work is usually clearer in a versioned playbook.

ansible localhost -i localhost, -c local -m ansible.builtin.debug -a "msg=hello"
ansible localhost -i localhost, -c local -m ansible.builtin.debug -a "msg=hello"
ansible localhost -i localhost, -c local -m ansible.builtin.debug -a "msg=hello"

This explicit local example reports hello. The trailing comma makes localhost, an inline host list rather than a filename. Ad hoc does not mean harmless: selecting all hosts with a mutating module can have a large effect. I would verify the target pattern and module arguments just as carefully as for a playbook.

39. What does ansible.builtin.ping actually test?

The built-in ping module is not an ICMP network ping. For its supported targets, it checks that Ansible can connect and execute the module, normally returning pong. That exercises more of the Ansible path than a simple network reachability test.

An ICMP response can succeed while authentication or Python execution fails, and an ICMP-blocked host may still be manageable over its allowed transport. I would use the platform-appropriate module, such as the Windows collection’s equivalent for Windows targets. A pong response is a useful connectivity and execution check, but it does not establish application health or permission for every future task.

40. How would you begin troubleshooting an unfamiliar Ansible failure?

I would identify the installed version, selected configuration, inventory scope and first meaningful error, then inspect the relevant module’s documentation. A syntax failure, unreachable host, failed module and skipped task represent different stages and should not be diagnosed interchangeably.

ansible --version
ansible-doc ansible.builtin.copy
ansible-playbook -i inventory.yml site.yml --syntax-check
ansible --version
ansible-doc ansible.builtin.copy
ansible-playbook -i inventory.yml site.yml --syntax-check
ansible --version
ansible-doc ansible.builtin.copy
ansible-playbook -i inventory.yml site.yml --syntax-check

Verbosity such as -v or -vvv can expose additional execution details, but may also reveal sensitive paths or values, so I would collect only the needed evidence. Syntax checking catches structural issues without proving target-side behavior. I would reproduce the smallest safe case and avoid rerunning a broad mutating playbook merely to obtain more logs.

Ansible Interview Questions and Answers for Intermediate

The intermediate answers develop practical playbook and role patterns. Examples make variable scope, registered results, task selection and delegation explicit so the reasoning can be followed beyond the YAML itself.

41. How would you investigate a variable that ignores an inventory override?

Find every definition of the variable and compare their precedence before editing the inventory. A role default is intentionally easy to override; a value in vars/main.yml, a task variable, or an extra variable can defeat the inventory value. Also distinguish a variable such as ansible_user from a play keyword such as remote_user: they participate in different precedence categories.

Suppose app_port is 8080 in role defaults, 8081 in host variables and 9090 in role vars. The role-vars definition wins among these sources. Moving an operator-configurable setting into defaults restores the intended inventory interface; adding another override in each task merely hides the design problem.

Inspect the effective nonsecret value close to the consuming task and check the launch command for -e. Inventory inspection alone cannot reveal every playbook-time override. Record the intended owner of the setting so the next maintainer does not recreate the conflict.

42. How do play, task and host variable scopes affect later tasks?

A task variable applies to its task; a play variable belongs to that play; a registered variable or a value assigned by set_fact is associated with the inventory host and remains available to subsequent tasks and plays in the same run. Scope describes where a value is available, while precedence decides which available definition wins.

- name: Temporary task override
  ansible.builtin.debug:
    var: display_mode
  vars:
    display_mode: compact

- name: Remember a derived result for this host
  ansible.builtin.set_fact:
    selected_port: 8443
- name: Temporary task override
  ansible.builtin.debug:
    var: display_mode
  vars:
    display_mode: compact

- name: Remember a derived result for this host
  ansible.builtin.set_fact:
    selected_port: 8443
- name: Temporary task override
  ansible.builtin.debug:
    var: display_mode
  vars:
    display_mode: compact

- name: Remember a derived result for this host
  ansible.builtin.set_fact:
    selected_port: 8443

The first task does not establish display_mode for the next task. The second establishes selected_port for the current host, not for every host in the inventory. A later play targeting that host can read it during this run. Do not assume it survives a separate invocation unless fact caching is deliberately configured.

43. How do you preserve Boolean and numeric types when passing extra variables?

Use JSON or a YAML/JSON variables file when types matter. The command-line key=value form produces strings, so a value spelled false is not automatically the Boolean false expected by a strict conditional or an argument contract.

ansible-playbook site.yml -e '{"feature_enabled":false,"worker_count":4}'
ansible-playbook site.yml -e

ansible-playbook site.yml -e '{"feature_enabled":false,"worker_count":4}'
ansible-playbook site.yml -e

ansible-playbook site.yml -e '{"feature_enabled":false,"worker_count":4}'
ansible-playbook site.yml -e

With the JSON call, feature_enabled is boolean and worker_count is integer should both hold. Validate inputs at the role boundary rather than relying on incidental coercion deep in a template. For a deliberately string-based interface, convert explicitly with an appropriate filter and reject unsupported values; converting every unexpected value into a default can conceal a mistyped deployment option.

Extra variables have high precedence and can override intended configuration. Treat the launch parameters as part of the reproducible input, and keep secrets out of shell history and process arguments.

44. When does the default filter preserve false, zero and empty values?

By default, default substitutes only for an undefined value. Adding its second argument as true also substitutes for false-like values. That distinction matters when false disables a feature or zero is a legitimate setting.

- name: Check fallback semantics
  ansible.builtin.assert:
    that

- name: Check fallback semantics
  ansible.builtin.assert:
    that

- name: Check fallback semantics
  ansible.builtin.assert:
    that

Use default(7) when absence means “use seven” but an explicit zero means “disable retries.” Use default(7, true) only if the interface intentionally treats zero and empty values as absent. A fallback is not validation: a defined string such as many still requires a type or range check.

45. Why use default(omit) for an optional module parameter?

omit tells Ansible to leave an argument out of the module invocation. That allows the module’s documented default behavior to apply. Passing an empty string or null can have a different meaning and may be invalid for that parameter.

- name: Set an optional file mode
  ansible.builtin.file:
    path: "{{ managed_path }}"
    state: file
    mode: "{{ requested_mode | default(omit) }}"
- name: Set an optional file mode
  ansible.builtin.file:
    path: "{{ managed_path }}"
    state: file
    mode: "{{ requested_mode | default(omit) }}"
- name: Set an optional file mode
  ansible.builtin.file:
    path: "{{ managed_path }}"
    state: file
    mode: "{{ requested_mode | default(omit) }}"

This task fragment assumes the file already exists and managed_path is supplied. If requested_mode is undefined, no mode argument is sent. If it is defined, use a quoted mode such as "0640" and validate it as the role requires. Do not equate leaving permissions unchanged with making permissions safe.

Avoid blindly chaining ordinary filters after default(omit); the special omission value is not normal input data. Compute and validate a transformed optional value first, or use a documented conditional expression that preserves omission.

46. When would you use mandatory instead of assert to validate input?

mandatory establishes that a value must be defined when an expression is evaluated. assert can enforce a fuller contract: type, range, allowed values and relationships between settings. A defined null or empty string may satisfy the first requirement but violate the application’s requirements.

- name: Validate the worker interface
  ansible.builtin.assert:
    that:
      - worker_count is defined
      - worker_count is integer
      - worker_count > 0
      - worker_count <= 32
    fail_msg

- name: Validate the worker interface
  ansible.builtin.assert:
    that:
      - worker_count is defined
      - worker_count is integer
      - worker_count > 0
      - worker_count <= 32
    fail_msg

- name: Validate the worker interface
  ansible.builtin.assert:
    that:
      - worker_count is defined
      - worker_count is integer
      - worker_count > 0
      - worker_count <= 32
    fail_msg

Put validation before tasks that make changes, and make the error describe the operator’s input rather than an internal template failure. A sequence of assertions is evaluated safely until a failing assertion stops the task; do not scatter conversions that turn invalid input into a misleading acceptable number. Role argument specifications can provide reusable interface validation, with assertions reserved for cross-field business rules.

47. How do you merge nested configuration dictionaries without accidentally replacing lists?

Use combine with explicit recursive and list policies. A shallow merge replaces an entire nested mapping, while a recursive merge retains unrelated nested keys. Lists still require a deliberate choice: replacement, append or another documented policy.

- name: Build a predictable effective configuration
  ansible.builtin.set_fact:
    effective: "{{ base | combine(override, recursive=true, list_merge='replace') }}"
  vars:
    base:
      server: {port: 8080, tls: false}
      zones: [east, west]
    override:
      server: {tls: true}
      zones

- name: Build a predictable effective configuration
  ansible.builtin.set_fact:
    effective: "{{ base | combine(override, recursive=true, list_merge='replace') }}"
  vars:
    base:
      server: {port: 8080, tls: false}
      zones: [east, west]
    override:
      server: {tls: true}
      zones

- name: Build a predictable effective configuration
  ansible.builtin.set_fact:
    effective: "{{ base | combine(override, recursive=true, list_merge='replace') }}"
  vars:
    base:
      server: {port: 8080, tls: false}
      zones: [east, west]
    override:
      server: {tls: true}
      zones

The result retains port 8080, changes TLS to true and sets zones to exactly [central]. Appending would instead retain the old zones, which could unintentionally expand a deployment. Document whether each list represents a replacement configuration, an ordered sequence or a set; a single global merge rule may not fit every field. Validate the merged result, because individually valid fragments can combine into an invalid configuration.

48. Why can dictionary bracket notation be safer than dot notation in templates?

Bracket notation unambiguously selects a dictionary key. Dot notation can collide with attributes or methods such as items or keys, making an innocent data field behave unexpectedly.

- name: Read keys that resemble dictionary methods
  ansible.builtin.assert:
    that:
      - payload['items'] == 3
      - payload['keys'] == 'external-id'
  vars:
    payload: {items: 3, keys

- name: Read keys that resemble dictionary methods
  ansible.builtin.assert:
    that:
      - payload['items'] == 3
      - payload['keys'] == 'external-id'
  vars:
    payload: {items: 3, keys

- name: Read keys that resemble dictionary methods
  ansible.builtin.assert:
    that:
      - payload['items'] == 3
      - payload['keys'] == 'external-id'
  vars:
    payload: {items: 3, keys

This is particularly useful for JSON responses whose field names you do not control and for keys containing punctuation. It does not remove the need to check that the parent mapping and key exist. Validate the response shape before indexing deeply rather than treating a missing field as proof that the remote operation succeeded with an empty result.

49. How do you select and transform a list of host or service records?

Use filters to express the transformation explicitly: select matching records, extract the needed attribute and materialize a list where a list is required. State how missing attributes are handled instead of assuming every record has the same shape.

- name: Select enabled service names
  ansible.builtin.set_fact:
    enabled_names: "{{ services | selectattr('enabled', 'defined') | selectattr('enabled', 'equalto', true) | map(attribute='name') | list }}"
  vars:
    services:
      - {name: api, enabled: true}
      - {name: worker, enabled: false}
      - {name

- name: Select enabled service names
  ansible.builtin.set_fact:
    enabled_names: "{{ services | selectattr('enabled', 'defined') | selectattr('enabled', 'equalto', true) | map(attribute='name') | list }}"
  vars:
    services:
      - {name: api, enabled: true}
      - {name: worker, enabled: false}
      - {name

- name: Select enabled service names
  ansible.builtin.set_fact:
    enabled_names: "{{ services | selectattr('enabled', 'defined') | selectattr('enabled', 'equalto', true) | map(attribute='name') | list }}"
  vars:
    services:
      - {name: api, enabled: true}
      - {name: worker, enabled: false}
      - {name

The result is [api]; the record without enabled is intentionally excluded. Validate that selected records have a name, and decide whether a missing flag should instead be an error. Keeping complex transformations in a named variable makes the consuming task easier to review, but it should not obscure the original data or the selection rule.

50. Why might hostvars contain an inventory variable but not a requested fact?

hostvars exposes variables associated with inventory hosts, but it does not automatically gather their facts. An inventory-defined address may be available immediately while ansible_facts remains absent until facts are gathered or loaded from an enabled cache.

Suppose a template on an application host needs a database host’s operating-system family. Targeting only the application group does not guarantee that the database facts have been collected. Gather the required facts in an earlier play or use deliberate delegated fact gathering, then read hostvars[database_host]["ansible_facts"]["os_family"].

For connection endpoints, prefer an explicit inventory variable when that is the actual contract; a discovered interface address may be wrong for client traffic. Avoid replacing missing essential facts with plausible defaults that silently route traffic to the wrong place.

51. How should a role separate tasks, handlers, templates and static files?

Use the role directories to separate responsibilities and make the input interface visible. The main tasks coordinate work, handlers represent deferred reactions, templates generate variable-dependent content and files hold content copied without templating.

  • defaults/main.yml: caller-configurable default values.

  • tasks/main.yml: the main task entry point.

  • handlers/main.yml: named deferred reactions.

  • templates/app.conf.j2: variable-dependent configuration source.

  • files/banner.txt: static content copied without templating.

  • meta/main.yml: role metadata and declared dependencies.

For example, a template task can refer to app.conf.j2 in the role’s template directory and notify a named handler only when the rendered file changes. Do not put configuration values directly into a static file if callers need to override them. Conversely, templating a fixed binary or certificate file is unnecessary and can corrupt its content.

Keep task entry points small enough to understand, with descriptive internal task files for coherent units. A role is easier to reuse when it has explicit inputs and outputs rather than depending on unrelated variables created by whichever role happened to run first.

52. Which role settings belong in defaults rather than vars?

Put caller-configurable settings in defaults/main.yml. Use vars/main.yml for internal mappings or implementation constants that should outrank ordinary inventory choices. A higher-precedence location does not make a value truly immutable; it simply changes which overrides can win.

Setting

Likely location

Reason

http_port: 8080

defaults/main.yml

Operators can choose a different port in inventory.

Package-name mapping by operating system

vars/main.yml or an explicitly loaded internal file

The role needs a maintained implementation mapping.

Namespace inputs, such as web_config_port, to reduce collisions. If an internal mapping also needs extension, expose a separate documented override and combine it deliberately. This gives callers a stable interface without requiring them to know every precedence rule or patch the role source.

53. How do role dependencies affect execution order and repeated execution?

A role can declare dependencies in its metadata so prerequisite roles run before it. Ansible also applies role deduplication rules: repeating a dependency does not necessarily rerun an identical invocation, while different parameters or explicit duplicate allowances can change that behavior.

If both an application role and a monitoring role depend on a common account role with the same invocation, do not build logic that assumes the account role runs twice. Make the prerequisite idempotent and declare the actual dependency rather than relying on accidental order in a long playbook.

Prefer dependencies for genuine prerequisites, not as a hidden workflow engine. Review the effective role graph and parameters when diagnosing unexpected repetition. Dynamic include_role also has an allow_duplicates option, so check the invocation mechanism and version rather than assuming every role entry point has identical deduplication behavior.

54. How can a role validate its public arguments before running its main work?

Define a role argument specification in meta/argument_specs.yml. It documents the supported interface and checks supplied arguments when the role is invoked with validation enabled. Use additional assertions for relationships that cannot be expressed by the argument specification alone.

# roles/web_config/meta/argument_specs.yml
argument_specs:
  main:
    short_description: Configure a web endpoint
    options:
      web_config_port:
        type: int
        required: true
      web_config_mode:
        type: str
        choices: [internal, public]
        default

# roles/web_config/meta/argument_specs.yml
argument_specs:
  main:
    short_description: Configure a web endpoint
    options:
      web_config_port:
        type: int
        required: true
      web_config_mode:
        type: str
        choices: [internal, public]
        default

# roles/web_config/meta/argument_specs.yml
argument_specs:
  main:
    short_description: Configure a web endpoint
    options:
      web_config_port:
        type: int
        required: true
      web_config_mode:
        type: str
        choices: [internal, public]
        default

Argument-spec validation is available in ansible-core 2.11 and later. Supply operational defaults through the role’s actual variables interface rather than assuming this specification populates every missing variable for task use. A port still needs a range check, and public mode might require an additional certificate input. Keep the documentation, defaults and assertions consistent as the role evolves.

55. How can module_defaults reduce repetition without making role behavior surprising?

Use module_defaults to provide shared module arguments within a play, block or task scope. An explicit argument on an individual task overrides the corresponding default. This is useful for repeated connection or formatting options, but a broad default can also affect tasks inside included roles.

- name: Use a scoped message default
  block:
    - name: Inherit the block default
      ansible.builtin.debug: {}
    - name: Override the default explicitly
      ansible.builtin.debug:
        msg: task-specific
  module_defaults:
    ansible.builtin.debug:
      msg

- name: Use a scoped message default
  block:
    - name: Inherit the block default
      ansible.builtin.debug: {}
    - name: Override the default explicitly
      ansible.builtin.debug:
        msg: task-specific
  module_defaults:
    ansible.builtin.debug:
      msg

- name: Use a scoped message default
  block:
    - name: Inherit the block default
      ansible.builtin.debug: {}
    - name: Override the default explicitly
      ansible.builtin.debug:
        msg: task-specific
  module_defaults:
    ansible.builtin.debug:
      msg

The first task prints block-default and the second prints task-specific. Scope a default to the smallest coherent block instead of surprising unrelated roles with arguments defined far away. You can clear defaults for a module in a narrower scope with an empty argument mapping.

Use the module’s fully qualified name, and review whether an action group is deliberately supported before applying defaults across a family of modules. Shared defaults remove repeated syntax; they should not hide which endpoint, credentials or resource ownership a task actually uses.

56. How do you make collection dependencies reproducible across runners?

Record collection versions in a requirements file and install them into the execution environment used by the runner. Pin ansible-core and controller dependencies as well; pinning a collection alone does not pin its Python libraries or the behavior of the engine.

# Illustrative requirements.yml: use a reviewed available version.
collections:
  - name: company.platform
    version: "1.4.2"
# Illustrative requirements.yml: use a reviewed available version.
collections:
  - name: company.platform
    version: "1.4.2"
# Illustrative requirements.yml: use a reviewed available version.
collections:
  - name: company.platform
    version: "1.4.2"

The example names a hypothetical internal collection, not an instruction to install an unverified public package. An exact version reduces unplanned changes; an allowed version range permits updates within that range and therefore requires dependency resolution evidence for each build. Record the installed collection list or execution-environment image digest with the run.

Test dependency upgrades in a separate environment before updating the pin. A reproducible old version can still have defects, so reproducibility should support controlled upgrades rather than freezing dependencies indefinitely.

57. When are variables from an included role visible outside that role?

For include_role, public: false keeps the role’s defaults and vars from being exposed to the surrounding play through that include; public: true exposes them to following tasks. Dynamic exposure happens when the include runs, so an earlier task cannot rely on it.

- name: Load the role and expose its defaults afterward
  ansible.builtin.include_role:
    name: web_config
    public: true
- name: Load the role and expose its defaults afterward
  ansible.builtin.include_role:
    name: web_config
    public: true
- name: Load the role and expose its defaults afterward
  ansible.builtin.include_role:
    name: web_config
    public: true

This differs from static role loading, where public variable exposure can happen during parsing. Static-role privacy controls and defaults depend on the invocation and ansible-core configuration/version, so make the chosen interface explicit instead of using leakage as an undocumented dependency.

Privacy here concerns role defaults and vars, not a security boundary or a general ban on outputs. A role can still create host variables using set_fact or register results. Prefer documented outputs with namespaced names over consumers reading arbitrary internal role variables.

58. How do you choose between import_tasks and include_tasks?

Choose import_tasks for a static task structure known while the playbook is parsed. Choose include_tasks when the selected task file or repetition depends on runtime state. Static imports expand into tasks early; dynamic includes are evaluated as execution reaches them.

Need

Typical choice

Consequence

A fixed validation task list

import_tasks

Tasks can be inspected as part of the expanded play.

Select a file from a registered runtime result

include_tasks

The file is selected during execution.

Repeat a task group for each item

include_tasks with a loop

Each include invocation gets its own loop value.

Conditionals also deserve attention: an import’s condition applies to its imported tasks, so those tasks may reevaluate a variable that earlier imported tasks change. An include condition controls whether the include happens. Test the actual behavior when a task file mutates the variable used in its selection condition.

59. How do you repeat a group of tasks for each application?

Loop over include_tasks and give the outer loop a descriptive variable. A block cannot itself accept a loop, and static task imports are not the right mechanism for iterating a runtime task group.

- name: Process each application
  ansible.builtin.include_tasks: application.yml
  loop: [api, worker]
  loop_control:
    loop_var: application_name

# application.yml contains a task list, for example:
# - ansible.builtin.debug:
#     msg: "Processing {{ application_name }}"
- name: Process each application
  ansible.builtin.include_tasks: application.yml
  loop: [api, worker]
  loop_control:
    loop_var: application_name

# application.yml contains a task list, for example:
# - ansible.builtin.debug:
#     msg: "Processing {{ application_name }}"
- name: Process each application
  ansible.builtin.include_tasks: application.yml
  loop: [api, worker]
  loop_control:
    loop_var: application_name

# application.yml contains a task list, for example:
# - ansible.builtin.debug:
#     msg: "Processing {{ application_name }}"

Inside the included file, use application_name consistently and use a different variable for any inner loop. This creates two include invocations, not one task that processes a single combined application value. Keep per-application results explicitly keyed by application if they must be compared later; a repeatedly assigned register variable otherwise represents its most recent assignment.

60. Why does tagging an include not necessarily tag the tasks it includes?

A tag on a dynamic include controls selection of the include statement. It does not automatically propagate to the child tasks. Use apply to apply tags to the included tasks, and tag the include itself so a tag-filtered run reaches it.

- name: Include the configuration task group
  ansible.builtin.include_tasks:
    file: configure.yml
    apply:
      tags: configure
  tags

- name: Include the configuration task group
  ansible.builtin.include_tasks:
    file: configure.yml
    apply:
      tags: configure
  tags

- name: Include the configuration task group
  ansible.builtin.include_tasks:
    file: configure.yml
    apply:
      tags: configure
  tags

With --tags configure, the include is selected and its child tasks receive the configure tag. Static imports generally propagate tags to imported tasks, so mechanically replacing an import with an include can change a filtered run.

Treat tags as an execution interface: a partial run can skip prerequisites, and merely listing tags does not prove the selected path is operationally complete. Test the supported tagged workflows and document any required state before encouraging operators to use them.

61. How can you gather only the facts a playbook actually needs?

Use ansible.builtin.setup with deliberate gather_subset choices, and use filter to reduce the returned fact names. A return-value filter is not the same thing as preventing collection work; subset selection controls which groups of facts are gathered.

- name: Gather operating-system distribution facts explicitly
  ansible.builtin.setup:
    gather_subset:
      - '!all'
      - '!min'
      - distribution
    filter

- name: Gather operating-system distribution facts explicitly
  ansible.builtin.setup:
    gather_subset:
      - '!all'
      - '!min'
      - distribution
    filter

- name: Gather operating-system distribution facts explicitly
  ansible.builtin.setup:
    gather_subset:
      - '!all'
      - '!min'
      - distribution
    filter

Run this in a play with automatic gathering disabled when the task should be the sole collection step. Check the supported subsets and returned keys for the target platform. Consumers can then use the documented ansible_facts fields rather than assuming every network, hardware or package fact exists. Measure the actual savings and retain the facts required by downstream roles; minimizing a list without tracing its consumers can create intermittent undefined-variable failures.

62. How should a task decide whether cached facts are fresh enough to use?

Treat a cached fact as a past observation with an expiry policy, not as a live query. Decide how quickly the property can change and what an incorrect value would cause. Operating-system family may remain stable for a long period, while an address, mount or available resource can change during the same run.

A cache timeout limits reuse but does not guarantee the property stayed unchanged inside that interval. After a task changes something that a later decision reads from gathered facts, gather the relevant facts again or query the authoritative module result. Do not assume a configuration task automatically refreshes all related facts.

For example, do not calculate a current-time deadline from an ansible_date_time value gathered an hour ago. Likewise, inventory membership is not proof that facts were gathered for that host. Keep cache ownership, expiration and invalidation explicit, especially when a targeted run reads another host’s cached data.

63. Why can clear_facts leave a value created by cacheable set_fact visible?

A cacheable set_fact creates both a high-precedence host variable for the current run and a lower-precedence fact copy eligible for the configured fact cache. meta: clear_facts removes the fact copy, not the current-run host variable.

- name: Create both representations
  ansible.builtin.set_fact:
    chosen_color: blue
    cacheable: true

- name: Clear stored facts for this host
  ansible.builtin.meta: clear_facts

- name: Confirm the host variable remains
  ansible.builtin.assert:
    that:
      - chosen_color == 'blue'
      - "'chosen_color' not in ansible_facts"
- name: Create both representations
  ansible.builtin.set_fact:
    chosen_color: blue
    cacheable: true

- name: Clear stored facts for this host
  ansible.builtin.meta: clear_facts

- name: Confirm the host variable remains
  ansible.builtin.assert:
    that:
      - chosen_color == 'blue'
      - "'chosen_color' not in ansible_facts"
- name: Create both representations
  ansible.builtin.set_fact:
    chosen_color: blue
    cacheable: true

- name: Clear stored facts for this host
  ansible.builtin.meta: clear_facts

- name: Confirm the host variable remains
  ansible.builtin.assert:
    that:
      - chosen_color == 'blue'
      - "'chosen_color' not in ansible_facts"

Marking a fact cacheable does not itself configure persistent caching. On a later invocation that loads the cached copy, precedence differs from the original set_fact assignment. Avoid using cache clearing as a general variable-reset mechanism; it may leave the very value a later task still reads.

64. How do you expand parent records and their child lists without losing context?

Use a parent-child expansion such as subelements when each task needs both the parent record and one child value. Flattening all child lists alone loses the association required to name resources or validate ownership.

- name: Inspect each team and repository pair
  ansible.builtin.debug:
    msg: "{{ pair.0.name }} owns {{ pair.1 }}"
  loop: "{{ teams | subelements('repositories', skip_missing=true) }}"
  loop_control:
    loop_var: pair
  vars:
    teams:
      - name: platform
        repositories: [api, worker]
      - name: finance
        repositories: [billing]
      - name

- name: Inspect each team and repository pair
  ansible.builtin.debug:
    msg: "{{ pair.0.name }} owns {{ pair.1 }}"
  loop: "{{ teams | subelements('repositories', skip_missing=true) }}"
  loop_control:
    loop_var: pair
  vars:
    teams:
      - name: platform
        repositories: [api, worker]
      - name: finance
        repositories: [billing]
      - name

- name: Inspect each team and repository pair
  ansible.builtin.debug:
    msg: "{{ pair.0.name }} owns {{ pair.1 }}"
  loop: "{{ teams | subelements('repositories', skip_missing=true) }}"
  loop_control:
    loop_var: pair
  vars:
    teams:
      - name: platform
        repositories: [api, worker]
      - name: finance
        repositories: [billing]
      - name

The three pairs are platform/api, platform/worker and finance/billing. The pending record produces no pair because missing lists are explicitly allowed. If every team must have a repository declaration, validate it and remove that permissive policy. Also distinguish an empty declared list from a missing key when those states have different business meanings.

65. How does until behave when a task also has a loop?

The retry condition is evaluated for each loop item, using that item’s latest registered result. One item can succeed immediately while another consumes retries. This is different from retrying the entire loop as a single operation.

- name: Check each synthetic item
  ansible.builtin.debug:
    msg: "{{ candidate }}"
  loop: [ready, ready]
  loop_control:
    loop_var: candidate
  register: probe
  until: probe.msg == 'ready'
  retries: 2
  delay: 0
- name: Check each synthetic item
  ansible.builtin.debug:
    msg: "{{ candidate }}"
  loop: [ready, ready]
  loop_control:
    loop_var: candidate
  register: probe
  until: probe.msg == 'ready'
  retries: 2
  delay: 0
- name: Check each synthetic item
  ansible.builtin.debug:
    msg: "{{ candidate }}"
  loop: [ready, ready]
  loop_control:
    loop_var: candidate
  register: probe
  until: probe.msg == 'ready'
  retries: 2
  delay: 0

Both items succeed on their initial attempt in this harmless fixture. For a real probe, use a read-only check that can observe changing state and a bounded delay appropriate to the service. Retrying a non-idempotent mutation can repeat its side effects. Once the loop finishes, inspect the per-item results rather than treating the aggregate register object as one successful probe response.

66. How do you prevent nested loops from overwriting each other’s item value?

Assign an explicit loop_var to each loop, especially when a looped include contains another loop. The default name item is shared unless changed, so inner work can collide with the outer task group’s expected input.

- name: Process each service with its index
  ansible.builtin.debug:
    msg: "{{ service_index }}: {{ service_name }}"
  loop: [api, worker]
  loop_control:
    loop_var: service_name
    index_var

- name: Process each service with its index
  ansible.builtin.debug:
    msg: "{{ service_index }}: {{ service_name }}"
  loop: [api, worker]
  loop_control:
    loop_var: service_name
    index_var

- name: Process each service with its index
  ansible.builtin.debug:
    msg: "{{ service_index }}: {{ service_name }}"
  loop: [api, worker]
  loop_control:
    loop_var: service_name
    index_var

This prints indices 0 and 1 next to the service names. In an included task file, reserve a different variable such as endpoint for the inner loop. Do not treat an index as a stable resource identity: reordering the source list changes the index. Use a stable name or identifier when persisting configuration or relating results across runs.

67. Does loop_control label protect sensitive fields in loop items?

No. A label makes loop output easier to read by replacing a bulky item description with a concise identifier. It is a presentation feature, not a redaction boundary. Other task output, errors or registered values may still contain the original data.

- name: Show an intentionally public record name
  ansible.builtin.debug:
    msg: "Processing {{ account.name }}"
  loop:
    - {name: analyst, team: reporting}
  loop_control:
    loop_var: account
    label: "{{ account.name }}"
- name: Show an intentionally public record name
  ansible.builtin.debug:
    msg: "Processing {{ account.name }}"
  loop:
    - {name: analyst, team: reporting}
  loop_control:
    loop_var: account
    label: "{{ account.name }}"
- name: Show an intentionally public record name
  ansible.builtin.debug:
    msg: "Processing {{ account.name }}"
  loop:
    - {name: analyst, team: reporting}
  loop_control:
    loop_var: account
    label: "{{ account.name }}"

This example contains no secrets. For credential-bearing tasks, use no_log at the appropriate tasks and avoid subsequently printing the registered object or loop source. Keep labels nonsecret as well. A short log is useful for operations, but output minimization and secret protection require separate design decisions.

68. How would you make a command task report changes accurately?

Base changed_when on a documented signal from the command, rather than suppressing every change or assuming every successful execution modified state. Prefer a purpose-built idempotent module when one exists.

- name: Classify a synthetic command result
  ansible.builtin.debug:
    msg: reconciled
  register: reconciliation
  changed_when: reconciliation.msg == 'updated'
- name: Classify a synthetic command result
  ansible.builtin.debug:
    msg: reconciled
  register: reconciliation
  changed_when: reconciliation.msg == 'updated'
- name: Classify a synthetic command result
  ansible.builtin.debug:
    msg: reconciled
  register: reconciliation
  changed_when: reconciliation.msg == 'updated'

This harmless fixture reports no change because its message is reconciled, not updated. In a real command task, the equivalent condition might examine a stable exit-code contract or structured output. Match an exact machine-readable signal rather than a substring that could appear in an error message.

Change reporting drives handler notification as well as summary counts. Setting changed_when: false on a task that really modifies configuration can prevent a needed reload. Conversely, false positives can repeatedly restart a service. Validate both the no-op and modification cases against the command’s actual contract.

69. Why can a list of failed_when conditions fail to catch an error?

A YAML list of failed_when expressions combines them with logical AND. If failure should occur when either of two conditions holds, write one expression containing OR. Otherwise a nonzero exit code could be ignored merely because a second error marker is absent.

- name: Classify a synthetic response
  ansible.builtin.debug:
    msg: accepted
  register: response
  failed_when: response.msg == 'rejected' or response.msg == 'invalid'
  changed_when: false
- name: Classify a synthetic response
  ansible.builtin.debug:
    msg: accepted
  register: response
  failed_when: response.msg == 'rejected' or response.msg == 'invalid'
  changed_when: false
- name: Classify a synthetic response
  ansible.builtin.debug:
    msg: accepted
  register: response
  failed_when: response.msg == 'rejected' or response.msg == 'invalid'
  changed_when: false

This passes for accepted. For a command, an OR condition could combine an unexpected return code with a documented error flag. Be careful that customizing failure criteria does not accidentally bless an unreachable target or a malformed task; connection and parsing problems are different from a normal module result. Test each failure branch individually, not only the case where every error signal appears together.

70. How does listen let several handlers respond to one notification?

Give several handlers the same listen topic, then notify that topic from a changed task. This separates the producer’s event name from the individual handler names and allows one event to trigger a coherent group of reactions.

# Task fragment
- name: Signal a synthetic configuration change
  ansible.builtin.debug:
    msg: changed configuration
  changed_when: true
  notify: configuration updated

# Handlers belong under the play-level handlers key.
# - name: Record reload work
#   ansible.builtin.debug:
#     msg: reload requested
#   listen: configuration updated
# - name: Record verification work
#   ansible.builtin.debug:
#     msg: verification requested
#   listen: configuration updated
# Task fragment
- name: Signal a synthetic configuration change
  ansible.builtin.debug:
    msg: changed configuration
  changed_when: true
  notify: configuration updated

# Handlers belong under the play-level handlers key.
# - name: Record reload work
#   ansible.builtin.debug:
#     msg: reload requested
#   listen: configuration updated
# - name: Record verification work
#   ansible.builtin.debug:
#     msg: verification requested
#   listen: configuration updated
# Task fragment
- name: Signal a synthetic configuration change
  ansible.builtin.debug:
    msg: changed configuration
  changed_when: true
  notify: configuration updated

# Handlers belong under the play-level handlers key.
# - name: Record reload work
#   ansible.builtin.debug:
#     msg: reload requested
#   listen: configuration updated
# - name: Record verification work
#   ansible.builtin.debug:
#     msg: verification requested
#   listen: configuration updated

Handler execution order follows the handler definitions, not the order of names in a notification list. Repeated notifications before an execution point are deduplicated. Give handlers unique names because their namespace is shared within the play; accidental name collisions or broad topic names can make a role trigger unrelated work.

71. What happens if a handler is notified before and after flush_handlers?

meta: flush_handlers runs the handlers currently pending at that point. It does not disable future notifications. A later changed task can notify the same handler again, causing another execution at a subsequent handler execution point.

Consider two template changes that both notify a reload handler. If both occur before the flush, the handler runs once at the flush. If the first occurs before the flush and the second afterward, the handler can run twice. Place a flush only where later tasks truly require the pending reaction to have completed.

This matters for expensive or disruptive handlers: an early flush can defeat the useful coalescing of several changes. Validate configuration before requesting its activation, and remember that a flush operates on the pending handler set, not solely on the handler you had in mind when inserting it.

72. What does force_handlers change after a task failure?

Normally, a failure on a host can prevent its notified handlers from running later in the play. force_handlers requests that pending handlers still run on hosts with task failures. It does not make an unreachable host reachable or guarantee that a handler itself succeeds.

For example, a configuration file changes and notifies a reload, then an unrelated verification task fails. Forcing the handler may bring the running service into line with the file, but that is only desirable if the new configuration is known to be safe. Reloading a partially written or unvalidated configuration can make the situation worse.

Choose this behavior from the workflow’s state requirements, not as a general error-suppression switch. It does not change a failed task into a successful one. Keep configuration validation and activation responsibilities clear so the handler does not become an uncontrolled recovery step.

73. How do you use rescue without hiding a failed operation?

Use rescue to handle a task that returns failure inside a block, and make the resulting state explicit. A successful rescue can allow the play to continue; that is appropriate only if recovery or a valid alternative actually succeeded.

- name: Demonstrate an explicitly handled failure
  block:
    - name: Reject a synthetic input
      ansible.builtin.fail:
        msg: synthetic invalid input
  rescue:
    - name: Record the handled outcome
      ansible.builtin.set_fact:
        input_rejected: true
  always:
    - name: Record completion of this attempt
      ansible.builtin.set_fact:
        attempt_finished: true
- name: Demonstrate an explicitly handled failure
  block:
    - name: Reject a synthetic input
      ansible.builtin.fail:
        msg: synthetic invalid input
  rescue:
    - name: Record the handled outcome
      ansible.builtin.set_fact:
        input_rejected: true
  always:
    - name: Record completion of this attempt
      ansible.builtin.set_fact:
        attempt_finished: true
- name: Demonstrate an explicitly handled failure
  block:
    - name: Reject a synthetic input
      ansible.builtin.fail:
        msg: synthetic invalid input
  rescue:
    - name: Record the handled outcome
      ansible.builtin.set_fact:
        input_rejected: true
  always:
    - name: Record completion of this attempt
      ansible.builtin.set_fact:
        attempt_finished: true

The fixture records the rejection rather than pretending that the original operation succeeded. In a real workflow, inspect ansible_failed_task and ansible_failed_result only as needed and avoid exposing secrets. If recovery cannot establish an acceptable state, fail explicitly after collecting the relevant evidence.

74. Why is an always section not a guarantee that cleanup will run?

always runs for ordinary block execution paths, including handled task failures, but it is not an unconditional external cleanup service. Unreachable hosts and invalid task definitions do not follow the normal block failure path that triggers rescue and always, and an interrupted controller cannot execute remaining tasks.

If a block creates a temporary artifact and then validates it, an always task is useful for cleanup after validation succeeds or fails. However, the design still needs a safe way to identify and remove stale artifacts after a disconnected or interrupted run. Give temporary objects explicit ownership and bounded lifetimes when the system supports them.

Do not use ignore_errors as a substitute for cleanup planning: ignoring a task failure changes control flow without repairing state. Test the failure paths relevant to the resource rather than assuming the word “always” covers failures outside Ansible’s ability to continue.

75. Which host does inventory_hostname refer to in a delegated task?

inventory_hostname continues to identify the host whose play iteration is being processed, even when the task executes through delegate_to elsewhere. Connection-related settings and other delegated execution context can come from the delegated host, so do not assume every unqualified variable still describes the original host.

For a task delegated from app01 to a controller or utility host, use inventory_hostname to identify app01 and explicit hostvars[inventory_hostname] lookups for its required inventory attributes. Supply the delegated host’s connection settings separately. This makes the intended source of each value reviewable.

Delegation does not automatically run a task only once: a play targeting five application hosts may execute the delegated task five times. Also, controller-only actions such as includes are not ordinary remote operations merely because a delegate keyword is attached. Check the action’s documented delegation support.

76. How does delegate_facts change where gathered facts are stored?

By default, facts returned by a delegated task are associated with the original inventory host. With delegate_facts: true, they are assigned to the delegated host instead. This is useful when intentionally gathering another host’s facts for later hostvars access.

# Conceptual fragment: database_host must be a defined inventory host.
- name: Gather the database host facts under its own identity
  ansible.builtin.setup:
    gather_subset: min
  delegate_to: "{{ database_host }}"
  delegate_facts: true
# Conceptual fragment: database_host must be a defined inventory host.
- name: Gather the database host facts under its own identity
  ansible.builtin.setup:
    gather_subset: min
  delegate_to: "{{ database_host }}"
  delegate_facts: true
# Conceptual fragment: database_host must be a defined inventory host.
- name: Gather the database host facts under its own identity
  ansible.builtin.setup:
    gather_subset: min
  delegate_to: "{{ database_host }}"
  delegate_facts: true

Afterward, read the data through hostvars[database_host]["ansible_facts"]. Without deliberate ownership, a task can make an application host appear to have the database server’s discovered properties. The option controls fact assignment; it does not make every registered task result belong to the delegate or ensure that multiple hosts cannot write the same shared fact.

77. How do serial and forks limit different parts of execution?

serial divides the play’s selected hosts into batches, completing the play for a batch before proceeding to the next. Forks limits the controller’s parallel worker capacity. A small fork count does not create the same whole-play batch boundary as serial.

Selected hosts

serial

Forks

Implication under linear execution

12

3

10

Three hosts belong to the current batch; spare workers do not enlarge it.

12

12

2

The batch contains all hosts, but a task has at most two worker slots at once.

Use serial when intermediate group state matters, such as keeping most members untouched while a subset is processed. Use forks to manage controller capacity and throughput. Neither value guarantees application availability by itself: task duration, failures and service dependencies still matter. Make the chosen strategy explicit when reasoning about task ordering.

78. When is throttle useful even if serial and forks are already configured?

throttle imposes a narrower worker limit on a task or block. It is useful when most work can run concurrently but one operation, such as a rate-limited API call, should have fewer simultaneous executions.

- name: Illustrate a one-worker task limit
  ansible.builtin.debug:
    msg: bounded work
  throttle: 1
- name: Illustrate a one-worker task limit
  ansible.builtin.debug:
    msg: bounded work
  throttle: 1
- name: Illustrate a one-worker task limit
  ansible.builtin.debug:
    msg: bounded work
  throttle: 1

With a serial batch of four and ten forks, a throttle of one limits this task to one worker; it does not shrink the whole play’s batch to one host. A throttle larger than the available forks or batch cannot create additional concurrency.

The limit applies within this Ansible execution, not across independent jobs or other clients calling the same service. If a shared resource requires global mutual exclusion or a global request rate, use a mechanism that coordinates all writers. A concurrency cap also does not guarantee a fixed requests-per-second rate.

79. What remains exposed after a variable is protected with Ansible Vault?

Vault encrypts stored content, but Ansible must decrypt it when the run consumes it. The decrypted value can still reach module arguments, templates, destination files or task output. Encryption at rest does not automatically protect those runtime paths.

For example, an encrypted database password used to render a configuration file results in a usable password on the managed system. The file still needs appropriate ownership, permissions and application handling, while the task may need no_log and diff suppression. Do not place the vault password next to the encrypted file in the same broadly accessible repository.

Use a controlled password source or secret-management integration, scope access to the environment that needs it and plan credential rotation. Vault IDs help identify encryption contexts; they are not an independent authorization system that prevents an operator with the relevant password from decrypting the content.

80. How do you retain useful diagnostics when using no_log?

Mark tasks that may expose secrets with no_log: true, and emit a separate diagnostic containing only explicitly selected nonsecret fields. Do not print the entire registered result later: redaction on the original task is not a permanent classification attached to every future use of its data.

- name: Handle a synthetic confidential value without printing it
  ansible.builtin.set_fact:
    confidential_marker: example_only
  no_log: true

- name: Report only the nonsecret workflow outcome
  ansible.builtin.debug:
    msg

- name: Handle a synthetic confidential value without printing it
  ansible.builtin.set_fact:
    confidential_marker: example_only
  no_log: true

- name: Report only the nonsecret workflow outcome
  ansible.builtin.debug:
    msg

- name: Handle a synthetic confidential value without printing it
  ansible.builtin.set_fact:
    confidential_marker: example_only
  no_log: true

- name: Report only the nonsecret workflow outcome
  ansible.builtin.debug:
    msg

The fixture uses a harmless marker, not a real credential. In production, keep diagnostic allowlists narrow: status, a safe request identifier and a sanitized error category may be enough. Avoid secret-derived task names and labels, and do not enable broad debug output around secret handling.

no_log reduces Ansible output exposure; it does not encrypt destination files, erase process arguments in unrelated tools or sanitize logs written by a remote application. Review each path through which the secret actually passes.

Ansible Interview Questions and Answers for Experienced

Experienced answers examine operational correctness under retries, partial failures and evolving environments. They explain trade-offs and verification strategies without presenting a successful play recap as proof of a safe deployment.

81. How does run_once behave when a play uses serial batches?

With the normal linear strategy, run_once runs once for each current serial batch, not necessarily once for the entire play. This matters for database migrations, shared notifications and other operations intended to occur only once across all hosts.

- name: Show batch-scoped execution
  hosts: demo
  gather_facts: false
  serial: 1
  tasks:
    - name: Report the current batch
      ansible.builtin.debug:
        msg: "batch={{ ansible_play_batch }}"
      run_once: true
- name: Show batch-scoped execution
  hosts: demo
  gather_facts: false
  serial: 1
  tasks:
    - name: Report the current batch
      ansible.builtin.debug:
        msg: "batch={{ ansible_play_batch }}"
      run_once: true
- name: Show batch-scoped execution
  hosts: demo
  gather_facts: false
  serial: 1
  tasks:
    - name: Report the current batch
      ansible.builtin.debug:
        msg: "batch={{ ansible_play_batch }}"
      run_once: true

With two demo hosts and serial: 1, the debug task executes twice. A separate play on an explicitly chosen coordinator can make a global operation clearer. A condition selecting a particular inventory host has different failure and limit behavior, so verify that the selected host is actually targeted. Never rely on the phrase “once” without specifying its execution boundary.

82. Why can delegated tasks race when they all write the same file?

Delegation changes where a task runs; it does not serialize the originating hosts. Several hosts can concurrently delegate a template or line update to one controller or management host, overwriting each other’s changes. Each task can report success while the final file loses updates.

Prefer building the complete shared content and writing it once through a designated owner. If separate writes are unavoidable, use an appropriate serialization mechanism and account for concurrent playbook runs too. throttle: 1 constrains workers for a task but is not a distributed lock across independent executions. A local test with two inventory aliases can reveal the scheduling assumption without touching real servers.

83. When can the free strategy violate a playbook’s coordination assumptions?

The free strategy lets hosts advance independently, so a fast host can reach a later task while another is still working on an earlier one. A playbook that assumes every host has completed preparation before any host activates a change may therefore be incorrect under that strategy.

For a coordinated schema and application transition, define explicit phases or separate plays with the required barriers rather than relying on task order across hosts. run_once is not a reliable global synchronization mechanism under free execution. Use free only when the host workflows are sufficiently independent and verify the strategy’s supported behavior. Faster execution is not useful if it removes a required ordering guarantee.

84. How would you distinguish connection, task and asynchronous runtime timeouts?

A connection timeout concerns establishing or using the transport according to the connection plugin. The task-level timeout limits the task action; the keyword documentation excludes templating and looping from that limit. async supplies a maximum runtime for a supported asynchronous action. These settings govern different stages and should not be treated as interchangeable end-to-end deadlines.

If a job takes twelve minutes but SSH connects immediately, increasing the connection timeout does not express the job’s permitted duration. Choose an appropriate asynchronous runtime and completion polling, then distinguish a connection failure from an expired job. Check the selected plugin’s options and the module’s asynchronous support. A timeout also leaves a state-reconciliation question: determine whether an external operation completed before retrying it.

85. What does poll: 0 leave unfinished from an orchestration perspective?

It starts asynchronous work and continues without waiting for its final result. A successful launch is not proof that the job completed or that dependent tasks may proceed. Preserve the job identifier and add a synchronization point when later work requires completion.

For a long-running export, poll the job with ansible.builtin.async_status and a bounded retry policy before consuming its file. A run can otherwise finish while the export is still running or has failed. Do not start another operation on the same exclusively locked resource merely because the first task returned a job ID. The workflow needs explicit completion, failure and cleanup ownership.

86. How should asynchronous job cleanup be handled?

Clean up the async status artifact after the job’s outcome has been observed and retained as needed. With poll: 0, Ansible does not automatically remove the job cache file; async_status with mode: cleanup removes that artifact. Cleanup is not a command to cancel a running job.

- name: Remove the completed job status artifact
  ansible.builtin.async_status:
    jid: "{{ finished_job_id }}"
    mode

- name: Remove the completed job status artifact
  ansible.builtin.async_status:
    jid: "{{ finished_job_id }}"
    mode

- name: Remove the completed job status artifact
  ansible.builtin.async_status:
    jid: "{{ finished_job_id }}"
    mode

This task fragment assumes the job has already been checked and finished_job_id is known. Removing evidence too early can make later diagnosis impossible without stopping the underlying process. Keep the async timeout, polling budget and recovery procedure consistent, and avoid treating a missing status file as definite proof that the business operation never happened.

87. How does max_fail_percentage affect a rolling deployment?

With serial execution, the failure percentage applies to the current batch, and the threshold must be exceeded rather than merely reached. This can make small-batch behavior surprising. The threshold is a control for stopping further work, not a rollback of changes already made.

In a batch of four hosts, a threshold of 50 is not exceeded by two failures; three failures exceed it. If the intent is to stop after two failures, choose a threshold consistent with that boundary and validate it in a harmless fixture. Also consider whether one failure is already unacceptable for the service. Availability depends on healthy capacity and topology, not only a percentage of task failures.

88. When is any_errors_fatal useful, and what does it not guarantee?

It can stop the play across hosts when a task failure means continuing would be unsafe. It does not instantly cancel every in-flight action or reverse completed changes. The failing task can finish on hosts in the current batch before the broader abort takes effect.

Use it for a shared prerequisite such as a failed compatibility gate where no host should proceed to activation. Pair it with a recovery design for hosts that already changed. Treat unreachable hosts and task failures according to the documented behavior rather than assuming one switch handles every condition. A fatal stop is a containment mechanism; service restoration remains a separate responsibility.

89. How can handler name collisions change which operation runs?

Handlers share a global namespace within a play. If two handlers have the same name, the last loaded definition shadows earlier ones for notification by that name. Loading order therefore matters; execution order of notified handlers follows their definition order, not the order of names in a task’s notification list.

For example, two roles that both define Restart service can make a notification resolve to the wrong role’s handler. Give handlers descriptive unique names or notify a role-qualified name such as web_role : Restart web. When several distinct operations should respond to one event, use unique handler names listening to a deliberately shared topic. Review static role/import loading and runtime includes rather than assuming the visual position of a notify statement determines its target.

90. Why is block/rescue not equivalent to a database transaction?

A rescue section performs explicitly authored recovery tasks after eligible failures; it does not automatically undo earlier external effects. A package install, API call or file replacement may already have changed state. Invalid task definitions and unreachable-host conditions also do not behave like ordinary rescuable module failures.

If activation fails after a release artifact was copied, rescue must know the previous artifact, whether configuration changed and how to verify restoration. A successful rescue can allow execution to continue, so deliberately fail afterward when the overall deployment should still be marked unsuccessful. Document which effects are reversible and which require manual intervention rather than implying that the block supplies atomicity.

91. What makes a playbook rollback plan credible?

It identifies the prior state, preserves the information needed to restore it and verifies the business service after restoration. Reinstalling an old package is insufficient if the new version changed persistent data or an external API. Rollback should be tested under the same compatibility assumptions as rollout.

For a release, retain the previous artifact digest and configuration version, define a safe activation switch and include a health check after reversal. Explain how partially completed hosts are handled and whether writes during the rollout can be represented by the old version. If reversal is impossible after a migration boundary, call the plan a forward repair and define the decision point clearly.

92. How would you structure a rolling deployment around service health?

Use explicit phases: verify capacity, remove or drain a bounded set of instances, apply the change, validate local readiness and external behavior, then return them to service. A task reporting “service started” is not evidence that the application can serve correct requests.

Choose batch sizes from redundancy and failure domains rather than a convenient host count. Include a stable observation period where the risk requires it and stop expansion on defined health signals. A load-balancer update and host change may occur on different systems, so record their outcomes separately. The playbook should leave a failed instance in a known state instead of blindly returning it to the pool in an always section.

93. How can a template be validated before replacing a live configuration file?

The template module’s validate option runs a validation command against a temporary candidate file before copying it into place. The command must include %s for that candidate path. It is passed securely without shell expansion, so pipes and shell operators do not behave as a shell script. Use the application’s actual configuration checker where available.

A candidate with an invalid directive should fail validation while leaving the current destination intact. This protects a different boundary from predicting whether a template would change. Normal atomic file replacement also reduces the chance of readers seeing a partially written file; enabling unsafe writes can weaken that protection on filesystems requiring a fallback.

Validation must cover the relevant includes and environment, and a valid configuration can still fail at startup because a dependency or port is unavailable. Combine candidate validation with controlled activation and service checks. Do not treat one file’s atomic replacement as an atomic transaction across several files.

94. Why can a derived set_fact value stop tracking changes to its input?

set_fact evaluates its expression when the assignment task runs. The stored result is a snapshot, not a live formula that recomputes whenever another variable changes. This differs from ordinary lazily evaluated variable expressions and can leave a derived endpoint or resource list stale later in the play.

- name: Establish the initial input
  ansible.builtin.set_fact:
    active_port: 8080

- name: Capture a derived value
  ansible.builtin.set_fact:
    captured_endpoint: "http://example.invalid:{{ active_port }}"

- name: Change the input
  ansible.builtin.set_fact:
    active_port: 9090

- name: Verify snapshot semantics
  ansible.builtin.assert:
    that:
      - active_port == 9090
      - captured_endpoint == 'http://example.invalid:8080'
- name: Establish the initial input
  ansible.builtin.set_fact:
    active_port: 8080

- name: Capture a derived value
  ansible.builtin.set_fact:
    captured_endpoint: "http://example.invalid:{{ active_port }}"

- name: Change the input
  ansible.builtin.set_fact:
    active_port: 9090

- name: Verify snapshot semantics
  ansible.builtin.assert:
    that:
      - active_port == 9090
      - captured_endpoint == 'http://example.invalid:8080'
- name: Establish the initial input
  ansible.builtin.set_fact:
    active_port: 8080

- name: Capture a derived value
  ansible.builtin.set_fact:
    captured_endpoint: "http://example.invalid:{{ active_port }}"

- name: Change the input
  ansible.builtin.set_fact:
    active_port: 9090

- name: Verify snapshot semantics
  ansible.builtin.assert:
    that:
      - active_port == 9090
      - captured_endpoint == 'http://example.invalid:8080'

The assertion passes because the second assignment does not reevaluate captured_endpoint. Choose deliberately between preserving the value used for an earlier action and computing the current value at its point of use. If a new snapshot is required, recompute it explicitly after the input changes. Split dependent assignments into separate tasks rather than relying on dictionary-key order inside one set_fact task. No connection to the example domain is made.

95. How would you distinguish configuration drift from an intentionally unmanaged setting?

Define ownership and the desired-state boundary before comparing current state. A role may own one configuration block while another system owns the rest. Replacing the entire file can erase valid changes, while ignoring everything outside a narrow check can leave important drift undetected.

For a shared service configuration, choose a supported include file or a clearly managed section where feasible. Document which properties the role enforces and which it only observes. Test a change inside the owned scope and one outside it. The desired response should differ intentionally; “Ansible changed it back” is not automatically evidence that the original change was wrong.

96. When should you fetch a file instead of loading it with slurp?

Use fetch when the desired result is a controller-side file; use slurp when a small file’s content must become a registered value for further logic. Slurp’s default base64 representation is encoding, not encryption, and the in-memory transfer can require substantially more memory than the original file.

Requirement

Choice

Boundary to review

Archive a large diagnostic file

fetch

Controller destination, retention and per-host naming

Inspect a small configuration marker

slurp

Encoding, content validation and log exposure

Fetch normally creates a host-organized destination tree. With flat: true, several hosts fetching the same basename into one directory can overwrite each other, so make the destination identity explicit. Fetch used with become may itself use slurp for checksum work, increasing memory and transfer costs; choosing fetch does not remove every resource concern.

In ansible-core 2.21, slurp adds an armor option; the default armored content remains base64 encoded. Only decode according to the returned encoding and the file’s actual text/binary contract. Avoid dumping a registered blob into debug output, and collect the smallest artifact needed for the diagnostic. A successful transfer verifies delivery, not that the source file represents a consistent application snapshot.

97. Why does a lookup’s execution location matter?

Lookups run on the controller, so file paths, credentials, network access and side effects belong to that environment rather than the managed host. A lookup of an environment variable reads the controller process’s environment. Delegating a surrounding task does not relocate that templating operation.

If a play retrieves a token from a controller-side secret service, ensure the execution environment has the intended access and that the result is not logged or cached unnecessarily. Do not assume a target-host file exists at the same path on the controller. Review custom lookup plugins as executable controller code, especially when their inputs come from inventory or other external sources.

98. What changed in the template trust model in ansible-core 2.19?

The 2.19 templating changes make trust explicit: only appropriately trusted strings are eligible to be evaluated as templates. Data arriving from untrusted sources should remain data rather than becoming executable template content. Legacy plugins that construct or return template strings may need changes to preserve the intended trust metadata.

When an upgrade leaves a template-looking string unevaluated or reports an untrusted-template issue, trace where it originated and whether evaluating it is actually intended. Do not indiscriminately mark external data as trusted to recover old behavior. Review the porting guide and test custom plugins separately. A compatibility fix should restore a justified trust boundary, not disable the protection that exposed the unsafe assumption.

99. How should later tasks handle a registered result from a skipped task?

A task skipped by its when condition generally still creates a registered result recording the skip. That object is not a successful module response with all normal fields. Test its state before accessing fields such as stdout or rc, and define what skipping means for the dependent workflow.

- name: Skip an optional probe deliberately
  ansible.builtin.command:
    argv: [/usr/bin/printf, '%s', ready]
    expand_argument_vars: false
  when: false
  register: optional_probe
  changed_when: false

- name: Verify the skip result contract
  ansible.builtin.assert:
    that:
      - optional_probe is skipped
      - "'rc' not in optional_probe"

- name: Consume only an executed probe
  ansible.builtin.debug:
    var: optional_probe.stdout
  when

- name: Skip an optional probe deliberately
  ansible.builtin.command:
    argv: [/usr/bin/printf, '%s', ready]
    expand_argument_vars: false
  when: false
  register: optional_probe
  changed_when: false

- name: Verify the skip result contract
  ansible.builtin.assert:
    that:
      - optional_probe is skipped
      - "'rc' not in optional_probe"

- name: Consume only an executed probe
  ansible.builtin.debug:
    var: optional_probe.stdout
  when

- name: Skip an optional probe deliberately
  ansible.builtin.command:
    argv: [/usr/bin/printf, '%s', ready]
    expand_argument_vars: false
  when: false
  register: optional_probe
  changed_when: false

- name: Verify the skip result contract
  ansible.builtin.assert:
    that:
      - optional_probe is skipped
      - "'rc' not in optional_probe"

- name: Consume only an executed probe
  ansible.builtin.debug:
    var: optional_probe.stdout
  when

The assertion runs, and the final debug task is skipped. This is different from a task excluded by tag selection, which may never create the register variable at all; such a consumer also needs an undefined-value policy. Do not convert a missing result to success with default(0) on its return code. If readiness is mandatory, explicitly reject the skipped or absent probe instead of continuing as though readiness was established.

100. Why is constructing a conditional expression as a string fragile?

It blurs the boundary between data and executable template logic and can depend on multiple passes of evaluation. The 2.19 templating changes expose many such patterns. Prefer a fixed expression that reads data values rather than assembling expression text from variables.

Instead of building a string equivalent to “the selected environment equals production,” compare a validated environment variable directly in when. If several behaviors are supported, use a data mapping or explicit task selection with a bounded set of choices. This is easier to review and avoids evaluating text supplied by inventory, API responses or users as control logic.

101. Do different Vault IDs create separate access-control boundaries?

Vault IDs label encrypted content and help select passwords; they are not user authorization rules. By default, a matching label’s password is tried first and other supplied passwords may then be attempted. The dev and prod labels alone therefore do not establish environment isolation.

Use distinct secret material and control which password sources each execution identity can obtain. Where required, review the vault-ID matching configuration as well, while recognizing that matching policy does not replace access control to the keys. A development job supplied with the production decryption credential has already crossed the intended boundary, regardless of the friendly label attached to the content. Test selection with disposable values and keep production credentials out of lower-trust jobs.

102. How does rekeying a vault differ from rotating the secret stored inside it?

Rekeying changes the encryption password protecting the vaulted content. It does not change the database password, API token or other credential contained in that content. If the underlying credential may be compromised, changing only the vault key leaves that credential usable.

Plan the two operations separately: rotate the actual service credential through its supported process, update authorized consumers, verify them and retire the old credential; then rekey stored ciphertext when required. Account for old repository history and cached copies. A successful rekey command proves that encryption changed, not that every dependent system now uses a new service secret.

103. How would you manage secret-bearing destination files and their backups?

Inventory every plaintext artifact created by delivery: the active file, old backups, staging files and copies collected for troubleshooting. Set explicit owner, group and restrictive mode appropriate to the consuming process. A secure active file does not compensate for a readable backup that contains a previous credential still accepted by the service.

For example, enabling backup: true on a secret-bearing template introduces a retained historical copy that needs its own access and retention policy. Decide whether that backup is needed, how authorized rollback will retrieve it, and when it should be removed after rotation. Restrict the destination directory too, and verify permissions in the target environment rather than relying on controller-side file modes.

Use synthetic marker values when checking the lifecycle. Removing a file is not a guarantee of physical secure erasure from snapshots or storage media; account for those systems separately. Rotation should revoke obsolete credentials as well as replace the current file.

104. What changes when copy uses remote_src: true?

The source path is then resolved on the managed host, not uploaded from the controller. This can reuse a staged artifact, but it does not transfer a file from an arbitrary third host. Delegation changes the managed execution context, so both the source and destination must be interpreted in that context.

- name: Copy an already staged local-to-target artifact
  ansible.builtin.copy:
    src: "{{ scratch_dir }}/staged.txt"
    dest: "{{ scratch_dir }}/activated.txt"
    remote_src: true
    mode

- name: Copy an already staged local-to-target artifact
  ansible.builtin.copy:
    src: "{{ scratch_dir }}/staged.txt"
    dest: "{{ scratch_dir }}/activated.txt"
    remote_src: true
    mode

- name: Copy an already staged local-to-target artifact
  ansible.builtin.copy:
    src: "{{ scratch_dir }}/staged.txt"
    dest: "{{ scratch_dir }}/activated.txt"
    remote_src: true
    mode

This fragment assumes a disposable scratch directory and an existing staged file on the target. It preserves that source mode; verify that the source permissions meet the destination’s requirements. Establish artifact identity or checksum before activation rather than trusting a familiar filename left by an earlier run. In a real deployment, copying bytes alone does not activate or validate a service.

Automatic Vault decryption is not supported for a remote source. An encrypted file staged on the target is not silently converted to plaintext by this option. Plan decryption and access controls explicitly, and do not broaden permissions merely because the destination exists but is unreadable.

105. Why can a task work over one connection type and fail over another?

Connection plugins define how commands and modules reach the target and what execution model is available. POSIX SSH, Windows transports, network CLI and HTTP API connections are not interchangeable. Modules and privilege-escalation methods must support the selected platform and connection.

For a network device, installing Python on the controller does not make a generic POSIX module executable on the device. Select the appropriate collection and connection settings, and verify where each module actually runs. Diagnose transport authentication, execution privilege and module compatibility separately. Copying working SSH inventory variables into a different platform can produce misleading failures rather than a portable configuration.

106. Why can the same playbook use a different ansible.cfg in another working directory?

Ansible selects the first configuration file found in its search order: the ANSIBLE_CONFIG environment setting, the current directory’s ansible.cfg, the home-directory file, then the system file. It does not merge every discovered file. Changing the launch directory can therefore change inventory defaults, plugin paths or other behavior without editing the playbook.

ansible --version
ansible-config dump --only-changed
ansible --version
ansible-config dump --only-changed
ansible --version
ansible-config dump --only-changed

The first command identifies the selected configuration file; the second helps inspect nondefault configuration and its origin. Treat raw output as potentially sensitive. A runner should select and record the intended configuration explicitly and still account for environment or other higher-precedence inputs.

Ansible does not automatically load ansible.cfg from a world-writable current directory because another user could alter its behavior. Fix directory ownership and permissions rather than disabling that protection casually. An explicit ANSIBLE_CONFIG path is an intentional trust choice, not proof that the file is safe. Compare the actual launch context when a laptop and CI runner disagree.

107. How would you review a third-party collection before trusting it in a privileged workflow?

Review provenance, maintenance, version pinning, dependencies and the code paths that run on the controller or target. Modules, action plugins, lookups and filters can execute code with the automation process’s access. A familiar module name or a successful installation is not a security review.

Use the organization’s approved source and verification process, test the required functionality in a bounded environment and record the selected version. Inspect secret handling and unexpected network or subprocess behavior for sensitive workflows. Fully qualified names clarify which implementation is invoked, but they do not establish that the implementation is trustworthy. Updates need the same dependency and behavior review as other executable software.

108. How can stale dynamic inventory cause a correct playbook to target the wrong machine?

Cached addresses, reused hostnames or delayed discovery can make an inventory entry refer to a different resource than intended. A playbook’s host pattern can be syntactically correct while its identity assumptions are stale. Inventory should preserve stable resource identity and expose freshness where relevant.

Before a consequential rollout, compare the intended resource identifiers and environment classification with the discovered targets. Define how terminated, replaced and newly created instances are handled. A cache refresh is useful only if the source itself is authoritative and current. Avoid using an IP address alone as proof that a machine is the same instance previously approved for the change.

109. How do end_host, end_batch and end_play change a recovery workflow?

These meta actions end different execution scopes without marking the affected hosts failed. Use the smallest scope that matches an intentional control-flow decision; stopping tasks is not rollback, and a success recap must not conceal an incomplete required operation.

Action

Scope

Example consequence

end_host

Current host in this play

Other hosts can continue

end_batch

Current serial batch

Later batches can still run

end_play

Entire play

All hosts stop this play; later plays can still run

With four hosts and serial: 2, ending the first batch leaves the second batch eligible to proceed. With serial unset or zero, end_batch behaves like end_play. Therefore, end_batch is wrong for a failed global compatibility gate that must stop expansion. Use explicit failure semantics when an unsuccessful deployment must be reported as such.

The actions have distinct version boundaries: end_host arrived in 2.8 and end_batch in 2.12. Test the chosen strategy and condition scope: global meta actions do not behave like an ordinary per-host module loop. Define how earlier changes and pending follow-up work are reconciled before ending the scope.

110. What changes when add_host creates inventory entries during a playbook run?

ansible.builtin.add_host updates the in-memory inventory for later plays in the same playbook. It does not rewrite a persistent inventory source or automatically add the new machine to the current play’s already selected hosts. Supply the necessary connection variables explicitly when creating an entry.

For example, a discovery play can add an approved machine to a new_workers group, followed by a play targeting that group. On the next separate invocation, discovery or a persistent inventory source must supply it again. Newly added hosts also do not bypass a command-line --limit; the later play still has to satisfy that restriction. Treat a hostname discovered from external data as an identity to validate, not permission to connect to an arbitrary address.

111. Why does serial: 1 not protect against two simultaneous playbook runs?

It limits hosts within one execution, not independent automation processes. Two controllers can each process one host and still modify the same shared resource concurrently. A deployment lock or external ownership protocol is needed when the workflow requires exclusivity across runs.

For a shared schema migration, use a lock with a clear owner, timeout and recovery policy, or a migration mechanism that provides its own concurrency control. Ensure stale locks do not require unsafe manual guessing and that the operation is retry-aware. Inventory batching and a cross-run lock solve different problems; neither should be presented as a substitute for the other.

112. How would you respect an API rate limit from Ansible?

Control request rate and retry behavior according to the API’s contract, not only task concurrency. throttle can reduce simultaneous workers, but fast calls can still exceed a requests-per-second limit. Multiple playbook runs and plugin-internal calls also contribute to the total.

Use bounded retries, respect server retry guidance where available and avoid synchronized retry bursts. Cache or batch reads when the API supports it, while preserving freshness requirements. Record which failures are retryable and which require correction. A blanket retry on every non-success response can prolong invalid requests or duplicate operations instead of improving reliability.

113. How should a playbook retry an API call after an uncertain timeout?

First determine whether the remote operation may already have completed. A transport timeout is not proof of no side effect. Prefer an idempotency key or a lookup by stable request identity before repeating a create or payment-like action.

If a resource creation request times out, query the intended resource or operation ID and reconcile its state. Retry only under the API’s documented semantics and stop when the outcome remains ambiguous. Preserve enough evidence for recovery without logging secrets. Ansible’s until repeats a task; it does not automatically make the underlying business action idempotent.

114. What should a custom module’s changed result mean?

It should report whether the module actually changed managed state, or would change it under supported check mode, according to a clear state comparison. Returning changed: true on every successful call causes unnecessary handlers and obscures convergence. Returning false after mutation hides real work.

Define normalized desired and current states, including defaults and unordered collections, and test create, update, no-op and drift cases. Return structured nonsecret evidence useful to callers. A custom module should also use failure reporting consistently and avoid printing arbitrary text to stdout that corrupts its result protocol. The contract is operational behavior, not merely valid JSON.

115. How should a custom module implement check mode honestly?

It should inspect enough current state to predict whether a change is needed and then avoid the mutation. Declare support only when that behavior is meaningful for the module. If an action cannot be predicted safely, document the limitation rather than performing it and calling the run a simulation.

Test the same fixture in check mode and real mode, verifying that the former leaves state unchanged and that its prediction agrees where the contract permits. Include absent resources, invalid input and external lookup failures. A read-only prediction can still require credentials and network access, so check mode is not a substitute for access control or safe input handling.

116. Why can explicitly defining localhost change the Python used for delegated work?

Ansible’s implicit localhost uses a local connection and the interpreter running ansible-playbook. Defining localhost explicitly in inventory replaces those implicit defaults. If the explicit entry omits its interpreter, local module execution can select a different Python from the controller environment containing the required libraries.

all:
  hosts:
    localhost:
      ansible_connection: local
      ansible_python_interpreter: "{{ ansible_playbook_python }}"
all:
  hosts:
    localhost:
      ansible_connection: local
      ansible_python_interpreter: "{{ ansible_playbook_python }}"
all:
  hosts:
    localhost:
      ansible_connection: local
      ansible_python_interpreter: "{{ ansible_playbook_python }}"

This inventory deliberately uses the playbook interpreter for local module execution. It is useful when a delegated module needs a Python dependency installed in the controller’s virtual environment. If a separate local interpreter is intended, provide its reviewed path and dependencies instead. Verify the interpreter actually used by a Python-based module, not only the shell’s python command.

This fixes an execution-environment boundary, not task ownership or concurrency: five original hosts can still delegate the same work five times. A task-level local connection also does not automatically create all implicit-localhost behavior. Keep local host variables explicit and avoid applying controller paths to remote hosts.

117. How would you plan an ansible-core or collection upgrade?

Read the relevant porting guides and collection compatibility requirements, then test representative content under the proposed versions before changing the execution environment. Separate parser and templating changes from module behavior and platform support. Pin the old and new environments so differences can be reproduced.

Include custom plugins, variable coercion, secret handling, check mode, error paths and realistic inventory shapes. For the 2.19 transition, templating trust and Boolean conditionals deserve explicit coverage. A successful syntax check is only the first gate. Stage the upgrade with a rollback plan for the automation environment and verify that rerunning older content against changed targets remains appropriate.

118. Why can rerunning only failed hosts be unsafe after a partial deployment?

The workflow may contain shared prerequisites, batch-level actions or state that changed for successful hosts. Retrying a subset can skip required coordination or repeat a supposedly once-only operation under a different host set. The retry scope must be derived from current state, not only the previous failure list.

If a migration succeeded but several application hosts failed, the recovery run should recognize the existing schema version and the compatibility window. Reassess inventory and health before resuming. Keep durable checkpoints for cross-host phases where needed. A retry is another execution with its own context; it is not automatically a continuation from the exact instruction that failed.

119. How would you validate that an Ansible run changed only its intended scope?

Compare the approved target identities, task selection and desired-state boundaries with the actual run evidence. A successful recap does not reveal whether an overly broad host pattern or inherited variable caused unintended changes. Record the inventory snapshot or identifiers and the resolved configuration used for the run.

For a small rollout, inspect representative before-and-after state and any shared resources touched through delegation or controller-side plugins. Include handlers and cleanup tasks in the scope review. If the task targets ten hosts but writes one global configuration, the global effect still needs explicit authorization and verification. Scope is defined by all side effects, not merely the hosts listed in the play header.

120. How would you make a lineinfile edit converge without leaving duplicate configuration keys?

Choose a regular expression that matches both the old and desired form of the owned setting, and define how duplicate keys are handled. A replacement that only recognizes one obsolete value can miss later drift. For state: present, lineinfile replaces the last matching line; it does not automatically clean up every duplicate directive.

- name: Converge one uniquely owned port setting
  ansible.builtin.lineinfile:
    path: "{{ scratch_dir }}/app.conf"
    regexp: '^port\s*='
    line: 'port=8443'
    create: false
- name: Converge one uniquely owned port setting
  ansible.builtin.lineinfile:
    path: "{{ scratch_dir }}/app.conf"
    regexp: '^port\s*='
    line: 'port=8443'
    create: false
- name: Converge one uniquely owned port setting
  ansible.builtin.lineinfile:
    path: "{{ scratch_dir }}/app.conf"
    regexp: '^port\s*='
    line: 'port=8443'
    create: false

For a file containing exactly one port=8080 line, the first run replaces it with port=8443 and the second reports no change. The same expression can correct a later port=9090 edit. If the file contains two port directives, changing only the last may leave an ambiguous or invalid application configuration; reject that input or use an ownership model that safely rebuilds the intended section.

With backrefs enabled, a nonmatching expression leaves the file unchanged instead of inserting a new line, which is another reason to test absent and already-correct states. Validate the resulting configuration where the application supports it. A single-line edit is appropriate only when the setting’s grammar and ownership can really be expressed by that rule.

Ansible Documentation and Further Reading

These official Ansible references explain the language, execution model and operational behavior discussed above. The links follow the current documentation; match the core version, collection version and platform support matrix to your environment. The 2.19 porting guide is included because its templating and conditional changes explain behavior that remains relevant in newer releases.

Team Sherlock.sh

Building fraud intelligence for live high-stake video interactions (financial discussions, hiring interviews, board meeting etc).

Catch candidate fraud before it costs you.

Sherlock AI helps you detect AI-assisted, proxy, and deepfake candidates, so every hiring decision is backed by evidence.

Ask AI about Sherlock.sh

Similar Posts