150 Ansible Interview Questions and Answers (2026)

Blog / 150 Ansible Interview Questions and Answers (2026)
Ansible interview questions and answers

Ansible now runs the automation behind serious infrastructure, and interviewers know it. As fleets grow and the bar rises, they're not asking whether you've heard of playbooks — they want to see real, hands-on fluency. Walk in shaky on inventory, roles, or Vault and it shows fast.

This guide gives you 150 questions with concise, interview-ready answers — code included where it helps. It's structured Junior to Mid to Senior, so you build from fundamentals up to the deep architecture and performance questions. Work through it and you'll answer with confidence, not guesswork.

Q1.
What is a task in Ansible?

Junior

A task is the smallest unit of action in Ansible: a single call to a module with its arguments that describes one desired state on a managed node.

  • Structure:

    • Each task invokes exactly one module (e.g. apt, copy, service) with parameters.

    • Usually given a name for readable output and reference.

  • Execution:

    • Tasks run top-to-bottom, in order, one at a time across the targeted hosts.

    • A task reports ok, changed, failed, or skipped.

  • Where tasks live: Inside a play's tasks section, in roles, or included via import_tasks/include_tasks.

yaml

- name: Ensure nginx is installed ansible.builtin.apt: name: nginx state: present

Q2.
Explain the architecture of Ansible, including the Control Node, Managed Nodes, and Inventory.

Junior

Ansible uses a push-based, agentless architecture: a Control Node connects out to Managed Nodes over SSH (or WinRM) to run tasks, and an Inventory tells it which hosts exist and how to group them.

  • Control Node:

    • The machine where Ansible is installed and playbooks are run from.

    • Holds playbooks, roles, inventory, and configuration; needs Python and network access to targets.

    • Windows is not supported as a control node (WSL aside).

  • Managed Nodes:

    • The remote systems Ansible configures; no agent required.

    • Need SSH access and (usually) Python for module execution; Windows uses WinRM.

  • Inventory:

    • A list of managed hosts, organized into groups, in INI or YAML.

    • Can be static (a file) or dynamic (a script/plugin querying a cloud provider).

    • Defines host/group variables and connection details.

  • Supporting pieces:

    • Modules do the actual work on nodes; plugins extend core behavior (connection, lookup, filter).

    • Ansible ships modules to the node, runs them, then removes them.

Q3.
What is Ansible and what are its key advantages over other configuration management tools?

Junior

Ansible is an open-source automation tool for configuration management, application deployment, and orchestration. Its standout advantage is being agentless and using simple, human-readable YAML, which makes it easy to adopt and maintain compared to tools like Puppet or Chef.

  • Agentless:

    • No software to install or maintain on managed nodes; uses existing SSH/WinRM.

    • Puppet and Chef typically require agents and a master server.

  • Simple, declarative YAML: Playbooks read almost like documentation; low learning curve versus Chef's Ruby DSL.

  • Push-based model: Changes are pushed on demand rather than pulled on a schedule, giving predictable control.

  • Idempotent: Re-running a playbook only changes what's out of state, so runs are safe and repeatable.

  • Batteries included: Thousands of modules and collections plus a large community (Ansible Galaxy).

Q4.
What are the key features of Ansible?

Junior

Ansible's key features center on simplicity and agentless operation: YAML-based playbooks, a huge module library, idempotent execution, and support for configuration management, deployment, and orchestration in one tool.

  • Agentless: Works over SSH/WinRM with nothing installed on nodes.

  • Playbooks in YAML: Human-readable, declarative descriptions of desired state.

  • Idempotency: Safe, repeatable runs that only change what's needed.

  • Modules and collections: Thousands of reusable units for cloud, networking, OS, and apps.

  • Roles: Reusable, shareable structures for organizing automation content.

  • Templating with Jinja2: Dynamic config files driven by variables and facts.

  • Ansible Vault: Encrypts secrets like passwords and keys within your repo.

  • Orchestration: Coordinates multi-tier, multi-host workflows in a defined order.

Q5.
How does Ansible work?

Junior

Ansible reads your inventory and playbook on the control node, connects to the targeted hosts over SSH/WinRM, copies module code to each, executes it to enforce the desired state, collects the JSON results, and removes the temporary code.

  1. Parse inputs: Reads the playbook, inventory, and variables; gathers facts about hosts unless disabled.

  2. Connect: Opens connections to managed nodes (SSH or WinRM), in parallel up to forks.

  3. Transfer and execute:

    • Copies the relevant module (with args) to a temp dir on each node and runs it with Python.

    • The module checks current state and only makes changes if needed (idempotent).

  4. Report and clean up:

    • Returns JSON showing ok/changed/failed, then deletes the temporary files.

    • Tasks proceed sequentially; handlers run at the end if notified.

Q6.
What is the difference between a playbook, a play, and a task in Ansible?

Junior

They form a nesting hierarchy: a playbook contains one or more plays, and each play contains an ordered list of tasks.

  • Task:

    • The smallest unit of action: a single call to a module (e.g. install a package, copy a file).

    • Runs in order, top to bottom, and ideally is idempotent.

  • Play:

    • Maps a set of tasks to a group of hosts via hosts:.

    • Also sets play-level context: become, vars, handlers.

  • Playbook: The YAML file itself: an ordered list of plays that describes the full automation workflow.

yaml

- name: Configure web servers # a play hosts: web become: true tasks: - name: Install nginx # a task ansible.builtin.apt: name: nginx state: present

Q7.
What language is used to write Ansible Playbooks?

Junior

Ansible playbooks are written in YAML, a human-readable data-serialization language, while the automation logic underneath is implemented in Python.

  • YAML for the playbook:

    • You declare desired state as structured data (lists and key-value maps), not imperative code.

    • Chosen for readability: minimal syntax, no braces or semicolons.

  • Jinja2 for dynamic values: Templating with {{ variable }} injects variables, filters, and conditionals into the YAML.

  • Python underneath: Ansible core and its modules are written in Python; you write YAML, Ansible executes the Python logic.

Q8.
What is a YAML file and how do we use it in Ansible?

Junior

YAML (YAML Ain't Markup Language) is a human-readable format for representing structured data; Ansible uses it to declaratively describe playbooks, variables, and inventory.

  • Core structures:

    • Key-value maps (dictionaries) and lists, expressed with indentation instead of brackets.

    • Indentation is significant: use spaces, never tabs.

  • How Ansible uses it:

    • Playbooks, group_vars/host_vars, and inventory can all be YAML.

    • A document starts with --- and lists begin with -.

  • Why it fits Ansible: Declarative and readable, so infrastructure intent is easy to review in version control.

yaml

--- user: name: deploy groups: - sudo - docker

Q9.
What are Ansible's primary use cases such as configuration management, application deployment, orchestration, and provisioning?

Junior

Ansible is a general-purpose automation engine, and its main use cases cluster around four areas: configuration management, application deployment, orchestration, and provisioning.

  • Configuration management: Enforce consistent state across servers (packages, files, services) idempotently.

  • Application deployment: Ship application code and dependencies to many hosts in a repeatable, controlled way.

  • Orchestration: Coordinate multi-tier, ordered workflows (e.g. database before app before load balancer), including rolling updates.

  • Provisioning: Stand up infrastructure: cloud instances, network devices, and cloud resources via modules.

  • Also common: Security compliance, patching, and ad-hoc administrative tasks.

Q10.
What is provisioning in Ansible?

Junior

Provisioning in Ansible is the act of preparing infrastructure and systems into a desired ready-to-use state: installing packages, configuring services, creating users, or even standing up cloud resources.

  • Two common scopes:

    • OS/app provisioning: configuring existing machines (packages, files, services) via modules like apt, yum, service.

    • Infrastructure provisioning: creating the machines/resources themselves (e.g. amazon.aws.ec2_instance, azure_rm_virtualmachine).

  • Declarative and idempotent: You describe the end state in a playbook; re-running only changes what differs from that state.

  • Agentless: Ansible provisions over SSH (or WinRM), so no software needs to be pre-installed on targets.

Q11.
What is orchestration in Ansible?

Junior

Orchestration in Ansible is coordinating multiple tasks across multiple hosts in a defined order so a multi-tier system comes up (or is updated) correctly, not just configuring machines in isolation.

  • Configuration vs orchestration: Configuration puts one host in a desired state; orchestration sequences actions across a fleet (databases first, then app servers, then load balancers).

  • Ordering and coordination controls:

    • Plays run in order and target different host groups; serial enables rolling batches.

    • delegate_to runs a task on another host (e.g. remove a node from a load balancer), and run_once runs a task a single time.

  • Typical use case: Zero-downtime rolling deployments: drain, update, health-check, and re-add nodes in controlled batches.

Q12.
What is an inventory in Ansible, and explain static vs dynamic inventories.

Junior

An inventory is the list of hosts (and groups of hosts) Ansible manages, along with connection details and variables. It can be static (a file you maintain) or dynamic (generated on the fly from an external source).

  • Static inventory:

    • A hand-maintained file (INI or YAML) listing hosts and groups.

    • Simple and predictable, but goes stale when infrastructure changes frequently.

  • Dynamic inventory:

    • A plugin or script queries a live source (cloud API, CMDB) each run to build the host list.

    • Ideal for auto-scaling or ephemeral cloud environments where hosts come and go.

  • Selection at runtime: Point Ansible at an inventory with -i, and target subsets in playbooks via the hosts: key.

Q13.
What is a group in inventory?

Junior

A group is a named collection of hosts in the inventory, letting you target and configure many machines at once and assign shared variables to them.

  • Purpose: Organize hosts by role or environment (e.g. [webservers], [dbservers]) so a play can target hosts: webservers.

  • Group variables: Variables set in [group:vars] or group_vars/ apply to all members.

  • Nested / special groups:

    • Groups can contain other groups via [parent:children].

    • all contains every host; ungrouped holds hosts in no other group.

Q14.
How do you define hosts and groups in an Ansible inventory?

Junior

You define hosts and groups in an inventory file using either INI or YAML format: list hostnames or IPs, place them under bracketed group headers (INI) or nested keys (YAML), and attach variables as needed.

  • Hosts: A hostname or IP, optionally with connection vars like ansible_host, ansible_user, or ansible_port.

  • Groups:

    • INI: a [groupname] header with hosts listed under it.

    • Group vars via [groupname:vars] and nesting via [parent:children].

  • Best practice: Keep variables in group_vars/ and host_vars/ directories rather than inline, for clarity.

ini

[webservers] web1.example.com web2 ansible_host=10.0.0.5 ansible_user=deploy [dbservers] db1.example.com [prod:children] webservers dbservers [webservers:vars] http_port=80

Q15.
What are the implicit 'all' and 'ungrouped' groups in an Ansible inventory?

Junior

Ansible always defines two implicit groups: all, which contains every host in the inventory, and ungrouped, which contains hosts that belong to no other group.

  • all: Matches every host; useful for global variables via group_vars/all.yml or targeting everything at once.

  • ungrouped: Holds only hosts not assigned to any explicit group, so it lets you catch stragglers.

  • Always present:

    • You don't define them; they exist even in an empty inventory and cannot be removed.

    • Every host is a member of all plus either ungrouped or one or more named groups.

Q16.
What is an ad-hoc command in Ansible, and how does it differ from a playbook?

Junior

An ad-hoc command runs a single Ansible module against hosts directly from the command line via the ansible tool, for quick one-off tasks; a playbook is a reusable YAML file describing a full, ordered set of tasks.

  • Ad-hoc command:

    • One module, one action: ansible web -m ping or ansible web -m service -a 'name=nginx state=restarted'.

    • Ideal for quick checks, restarts, or ad-hoc file copies; not saved or version-controlled.

  • Playbook:

    • Declarative YAML run with ansible-playbook; supports multiple plays, variables, handlers, and roles.

    • Repeatable, idempotent, and reviewable: the basis of real configuration management.

  • Key difference: Ad-hoc is for throwaway actions; playbooks are for documented, repeatable orchestration.

Q17.
What is an Ansible playbook and what language is used to write it?

Junior

An Ansible playbook is a declarative automation file that defines the desired state of your systems: it lists one or more plays that map groups of hosts to a series of tasks (module calls) to run against them. Playbooks are written in YAML.

  • Purpose: Orchestrates configuration, deployment, and provisioning by describing what the end state should be, not the step-by-step how.

  • Written in YAML: Human-readable, indentation-sensitive; a playbook is a list of plays, each a dictionary with keys like hosts, tasks, and vars.

  • Structure: Play: targets hosts and sets execution context. Task: invokes a single module. Handler: task triggered by notify.

  • Idempotent: Re-running a playbook only changes what isn't already in the desired state.

yaml

- name: Install and start nginx hosts: webservers become: true tasks: - name: Install nginx ansible.builtin.package: name: nginx state: present

Q18.
What command would you use to check the syntax of an Ansible playbook without running it?

Junior

Use ansible-playbook --syntax-check playbook.yml: it parses the YAML and validates playbook structure without connecting to or changing any hosts.

  • What it catches: YAML formatting errors, malformed play/task structure, and undefined imported files.

  • What it does NOT catch: Runtime logic errors or whether modules will actually succeed on the target.

  • Related dry-run tools: --check simulates changes on hosts; ansible-lint enforces best-practice and style checks.

Q19.
What is a playbook run?

Junior

A playbook run is a single execution of a playbook: Ansible reads the plays, gathers facts, and applies each task in order against the targeted hosts, reporting the outcome for every host and task.

  • Execution flow: Plays run top to bottom; within a play, tasks run one at a time across all targeted hosts before moving to the next task (by default).

  • Per-host results: Each task reports ok, changed, failed, or skipped; the PLAY RECAP summarizes per host.

  • Idempotent by design: A second run against unchanged systems should report ok with no changed tasks.

Q20.
Why is naming your tasks considered a best practice, and how does it affect output and tagging?

Junior

Naming tasks with name makes playbook output self-documenting and lets you target tasks precisely: the name appears in the run output and is what --start-at-task and log parsing rely on.

  • Readable output: Named tasks print your descriptive string instead of a generic module line, so it's clear what each step does and where a run failed.

  • Debugging and resuming: --start-at-task "name" lets you resume mid-playbook, which requires stable, unique names.

  • Tags vs names: Naming aids readability, but selective execution is driven by tags (--tags / --skip-tags), not names; use both for clarity and control.

  • Handler matching: notify references a handler by its exact name, so meaningful names are essential.

Q21.
Can you explain the difference between Ansible modules and Ansible playbooks?

Junior

A module is a single reusable unit of work (a program that performs one specific action), while a playbook is the YAML orchestration file that calls modules in an ordered set of tasks to achieve a larger goal. Modules are the building blocks; playbooks are the blueprint that assembles them.

  • Modules: Discrete, single-purpose (e.g. copy, service, user); can even be run ad-hoc via ansible -m.

  • Playbooks: Combine many module calls, plus variables, conditionals, loops, and handlers, into a repeatable workflow across host groups.

  • Relationship: Each task in a playbook invokes exactly one module; the playbook provides the ordering, targeting, and logic around those calls.

Q22.
What are Ansible modules, and how do they report results such as changed, ok, and failed?

Junior

Modules are the units of work Ansible runs on targets; each returns a JSON result, and Ansible maps that result to a task status so you can see what happened. The key statuses are ok, changed, failed (plus skipped and unreachable).

  • ok: The module ran successfully and the system was already in the desired state, so nothing was modified.

  • changed:

    • The module made an actual change to the target: this is what triggers handlers via notify.

    • Drives idempotency reporting: a second run should show ok instead of changed.

  • failed: The module could not complete (error, bad params); by default the host stops running further tasks.

  • Other statuses: skipped (a when: was false) and unreachable (couldn't connect via SSH).

  • Under the hood: modules emit fields like changed, failed, and msg in JSON; capture them with register and override with changed_when/failed_when.

Q23.
What is the difference between the copy and template modules?

Junior

Both place files onto managed hosts, but copy transfers a file as-is, while template renders a Jinja2 template (substituting variables and logic) before delivering it. Use template when the file's content must vary per host.

  • copy:

    • Ships a static file (or inline content:) unchanged from control node to target.

    • Best for binaries, certs, or config that never needs interpolation.

  • template:

    • Processes a .j2 file with Jinja2, injecting variables, facts, conditionals, and loops, then copies the result.

    • Ideal for config files that differ by host (ports, hostnames, IPs).

  • Shared behavior: Both are idempotent, support owner, group, mode, validation, and backups, and only report changed when the destination content actually differs.

Q24.
What are Ansible variables and how are they defined and used in playbooks?

Junior

Ansible variables are named values that make playbooks flexible and reusable: you define them in many places (inventory, playbooks, roles, facts, extra-vars) and reference them with Jinja2 {{ }} syntax.

  • Where they're defined:

    • In a play under vars, or external vars_files.

    • Inventory via host_vars and group_vars.

    • Role defaults/main.yml (lowest) and vars/main.yml (higher).

    • Registered from task output with register, gathered facts, and set_fact.

    • Command line with --extra-vars (highest precedence).

  • How they're used: Referenced in templates and tasks with {{ var_name }}, and can be filtered (| default('x')).

  • Precedence: When defined in multiple places, Ansible follows a fixed precedence order; extra-vars always wins, role defaults always lose.

yaml

- hosts: web vars: http_port: 8080 tasks: - name: Show the port debug: msg: "Listening on {{ http_port }}"

Q25.
What are host_vars and group_vars, and how are they used?

Junior

host_vars and group_vars are inventory-linked variable definitions: values automatically applied to a specific host or to every host in a group, based on directory/file naming that matches inventory names.

  • group_vars:

    • Files under group_vars/<groupname>.yml apply to all hosts in that group.

    • group_vars/all.yml applies to every host.

  • host_vars: Files under host_vars/<hostname>.yml apply to just that host and override group values.

  • Placement and precedence:

    • Live next to the inventory or the playbook; host_vars outrank group_vars.

    • Keep environment- or host-specific config here to keep playbooks and roles generic.

Q26.
What are registered variables, and how do you use them?

Junior

A registered variable captures the full output of a task using the register keyword, so you can inspect its result (rc, stdout, changed, etc.) and drive later tasks with conditionals or loops.

  • What it holds:

    • A dict with fields like rc, stdout, stderr, changed, failed; module-specific keys vary.

    • It is host-scoped, like a fact for the current play.

  • Common uses:

    • Gate later tasks with when: result.rc != 0 or when: result.changed.

    • When registered on a loop, results are under result.results.

yaml

- name: Check service command: systemctl is-active nginx register: svc ignore_errors: true - name: Start if down service: name: nginx state: started when: svc.rc != 0

Q27.
What is Ansible Galaxy and how does it facilitate role management?

Junior

Ansible Galaxy is the public hub and command-line tool for finding, sharing, and installing community roles and collections. It acts as the package repository for reusable Ansible content.

  • What it provides:

    • A central website of published roles/collections with ratings and metadata.

    • The ansible-galaxy CLI to install, scaffold, and manage content.

  • How it helps role management:

    • Install: ansible-galaxy role install geerlingguy.nginx pulls a tested role instead of reinventing it.

    • Scaffold: ansible-galaxy init myrole creates the standard directory layout.

    • Reproducibility: list dependencies with versions in requirements.yml and install them together.

  • Note: you can also point ansible-galaxy at a private Automation Hub or Git repos for internal, controlled content.

yaml

# requirements.yml roles: - name: geerlingguy.nginx version: "3.1.4" collections: - name: community.general version: ">=8.0.0"

Q28.
What is the ansible.builtin namespace and what does it contain?

Junior

The ansible.builtin namespace is the collection bundled directly inside ansible-core. It contains the essential modules and plugins that ship with Ansible itself and are always available without installing anything extra.

  • What it holds:

    • Core modules: copy, template, file, command, shell, service, apt, yum.

    • Core plugins: connection (ssh), lookups, filters, and callbacks.

  • Why it exists: When content was split into collections, these fundamentals stayed in ansible-core under this reserved namespace.

  • Usage: Reference as ansible.builtin.copy; always guaranteed present regardless of installed collections.

Q29.
What is become in Ansible, and how is it used for privilege escalation?

Junior

become is Ansible's privilege escalation system: it lets you connect as one (unprivileged) user but execute tasks as another (usually root) using tools like sudo.

  • Core directives:

    • become: true turns escalation on.

    • become_user sets the target identity (defaults to root).

    • become_method selects the mechanism (sudo, su, doas, etc.).

  • Scope: Can be set at play, block, or task level, so you escalate only where required.

  • Passwords: If sudo needs a password, supply it with --ask-become-pass or the become_password variable.

yaml

- name: Install a package as root hosts: web become: true become_method: sudo tasks: - name: Restart nginx as a specific user ansible.builtin.service: name: nginx state: restarted become_user: root

Q30.
How does the --ask-become-pass option work and when do you need it?

Junior

--ask-become-pass (short -K) prompts you once at runtime for the privilege escalation password and reuses it for all escalated tasks in that run.

  • How it works:

    • At launch Ansible asks for the BECOME password and passes it to sudo/su when escalating.

    • It never stores the password on disk; it lives only in memory for the run.

  • When you need it:

    • When the target's sudo/su requires a password (no NOPASSWD rule).

    • Any time become: true is used against hosts that prompt for credentials.

  • When you don't: If sudo is passwordless (NOPASSWD), or you supply become_password via a vaulted variable for automation.

bash

ansible-playbook site.yml --become --ask-become-pass

Q31.
What is a conditional in Ansible, and how do you use when statements to control task execution?

Junior

A conditional in Ansible runs a task only when an expression evaluates to true, expressed with the when keyword. The value is a raw Jinja2 expression (no {{ }} needed) evaluated per host, so the same play can behave differently across your inventory.

  • Basic usage:

    • Attach when to a task; if it's false the task is skipped for that host.

    • Reference variables and facts directly, e.g. when: ansible_os_family == "Debian".

  • Combining conditions:

    • A list under when is implicitly ANDed together.

    • Use and, or, not for explicit boolean logic.

  • Testing variable state: Common tests: is defined, is not defined, | bool, | length > 0.

  • With loops and registered results:

    • When used with a loop, when is checked on each item.

    • Often gates a follow-up task on a prior registered result, e.g. when: result.changed.

yaml

- name: Install Apache on Debian only ansible.builtin.apt: name: apache2 state: present when: - ansible_os_family == "Debian" - install_web | default(true) | bool

Q32.
What is a tag in Ansible, and how do you use --tags and --skip-tags?

Junior

A tag is a label you attach to tasks, blocks, roles, or plays so you can selectively run or skip parts of a playbook. At runtime you filter with --tags to run only tagged work and --skip-tags to exclude it, which is invaluable for large playbooks.

  • Defining tags:

    • Add tags: with one or more names to any task, block, or role.

    • A single task can carry multiple tags.

  • Running and skipping:

    • ansible-playbook site.yml --tags "deploy,config" runs only matching tasks.

    • ansible-playbook site.yml --skip-tags "slow" runs everything except those tasks.

  • Special reserved tags:

    • always: runs unless explicitly skipped, even when other tags are selected.

    • never: runs only when its tag is explicitly requested.

    • tagged, untagged, all are usable as selectors.

  • Discovery: --list-tags shows all tags available in a playbook.

yaml

- name: Install packages ansible.builtin.apt: name: nginx state: present tags: - install - packages

Q33.
What is ansible-doc and how do you use it to explore module documentation?

Junior

ansible-doc is a command-line tool that displays documentation for modules, plugins, and collections directly from your terminal, so you can look up parameters and examples without leaving the shell or opening a browser.

  • Look up a module: ansible-doc ansible.builtin.copy shows parameters, return values, and examples.

  • Discover what's available: ansible-doc -l lists all modules; add a collection name to narrow it.

  • Other plugin types: Use -t to target a type: ansible-doc -t filter, -t lookup, -t callback.

  • Quick reference: ansible-doc -s copy prints a snippet-style playbook stub of all options, ideal for scaffolding a task.

Q34.
How would you use Ansible to automate the deployment process?

Junior

You model the deployment as an ordered set of roles/tasks (fetch artifact, configure, restart, verify) and run it as a rolling update so the service stays available while hosts are updated in controlled batches.

  • Structure the deploy as roles:

    • Separate concerns: pull the build artifact, template config, manage the service, run smoke tests.

    • Keep versions in variables so the same playbook deploys any release.

  • Roll out safely:

    • Use serial to update in batches and max_fail_percentage to abort if too many hosts fail.

    • Drain from the load balancer with a pre_tasks step, then re-add in post_tasks.

  • Make it idempotent and verifiable: Use handlers to restart only on real changes, and a health-check task (uri) that fails the play if the new version is unhealthy.

  • Enable rollback: Keep prior releases (symlinked current directory) so a failed deploy can repoint to the last good version.

Q35.
How do you interpret the PLAY RECAP and the ok/changed/failed/skipped/unreachable counts?

Junior

The PLAY RECAP is the summary printed at the end of a run: it tallies, per host, how many tasks ended in each state so you can quickly see what happened and where.

  • ok: Tasks that ran successfully with no change needed (already in desired state) plus successful gather steps.

  • changed: Tasks that actually altered the host: high counts on repeat runs suggest non-idempotent tasks.

  • failed: Tasks that errored and were not rescued; a nonzero count fails the play for that host.

  • skipped: Tasks whose when: condition was false, so they didn't run.

  • unreachable: Ansible couldn't connect to the host at all (SSH/auth/network); distinct from a task failing.

  • How to read it:

    • Ideal repeat run: changed=0 and failed=0 (proves idempotency).

    • Newer versions also show rescued and ignored counts.

Q36.
What does the --diff flag show when running a playbook, and how does it help?

Junior

The --diff flag shows a line-by-line comparison of what changed on the target (before vs after), much like git diff, so you can verify exactly what a task modifies.

  • What it displays:

    • For file-changing modules (template, copy, lineinfile), the added/removed lines of content.

    • Other modules may show before/after state where supported.

  • Best paired with check mode: --check --diff previews the exact changes without applying them: ideal for review and change control.

  • Why it helps:

    • Confirms a template renders as expected and catches unintended edits before they land.

    • Caution: diffs can leak secrets; use no_log: true on sensitive tasks.

Q37.
What is idempotence in Ansible and why does it matter, and how do you ensure idempotency in your tasks?

Mid

Idempotence means running the same task multiple times produces the same end state without repeating side effects: if the system already matches the desired state, nothing changes. It matters because it makes playbooks safe to re-run and predictable.

  • Why it matters:

    • You can run a playbook repeatedly with no unintended drift or duplication.

    • The changed count accurately reflects what actually needed fixing.

  • How most modules achieve it: They check current state first and act only if it differs (declarative state: parameters).

  • Ensuring idempotency in your tasks:

    • Prefer state-based modules over raw commands.

    • For command/shell, add guards with creates, removes, or when conditions.

    • Use changed_when and failed_when to report status accurately.

    • Test with --check mode to verify a second run reports no changes.

yaml

- name: Run migration only once ansible.builtin.command: /opt/app/migrate.sh args: creates: /opt/app/.migrated # skips if file exists

Q38.
Explain Ansible's agentless architecture and its implications.

Mid

Agentless means Ansible needs no daemon or software installed on managed nodes: it connects over standard protocols (SSH for Linux, WinRM for Windows), pushes temporary module code, executes it, and cleans up. This dramatically lowers setup and maintenance overhead.

  • How it works without an agent:

    • Uses existing SSH/WinRM plus Python already on most Linux hosts.

    • Ships module code to a temp location, runs it, returns JSON, then removes it.

  • Benefits:

    • No agents to install, patch, or monitor; smaller attack surface.

    • Faster onboarding of new hosts; nothing consuming resources when idle.

    • Leverages existing SSH auth and hardening.

  • Implications and trade-offs:

    • Requires network reachability and credentials to every node.

    • Push model means no continuous enforcement; drift is corrected only when you run a playbook (unlike a pull agent).

    • Can be slower at very large scale since it opens connections per run (mitigated by forks, pipelining, or pull mode).

Q39.
How can Ansible's configuration management assist an organization in handling system updates and maintaining integrity?

Mid

Ansible turns system updates into codified, repeatable playbooks that apply the same desired state everywhere, so patching and maintenance become consistent, auditable, and safe to re-run rather than manual and error-prone.

  • Consistent updates at scale:

    • One playbook patches many hosts identically, eliminating configuration drift.

    • Package modules (apt, yum) enforce specific versions or state: latest.

  • Integrity and verification:

    • Idempotency ensures re-runs converge to the intended state, correcting any drift.

    • Check mode (--check) and --diff preview changes before applying them.

  • Safe, controlled rollouts: serial

  • Safe rollouts and reliability:

    • serial and rolling updates patch batches to avoid downtime.

    • Handlers restart services only when needed; block/rescue handle failures gracefully.

  • Auditability and compliance:

    • Playbooks live in version control, giving a reviewable history of every change.

    • Run reports show exactly what changed on each host.

Q40.
How does Ansible's approach differ from other configuration management tools like Puppet, Chef, or SaltStack (agentless vs agent-based, push vs pull, YAML vs DSLs)?

Mid

Ansible's defining traits are that it is agentless, push-based, and written in YAML, which sets it apart from agent-based, pull-oriented tools like Puppet and Chef that use their own Ruby DSLs.

  • Agentless vs agent-based:

    • Ansible connects over SSH (or WinRM) and needs no daemon on managed nodes, only Python.

    • Puppet and Chef install a persistent agent on each node; SaltStack typically runs a minion, though it also has an agentless SSH mode.

  • Push vs pull:

    • Ansible pushes changes from a control node on demand.

    • Puppet and Chef agents pull desired state from a central server on a schedule.

  • YAML vs DSLs:

    • Ansible uses declarative YAML, lowering the learning curve.

    • Puppet has its own declarative language and Chef uses a Ruby DSL, requiring more programming knowledge.

  • Trade-off: Agentless is simpler to adopt; agent-based pull can enforce continuous drift correction more naturally.

Q41.
What is Red Hat Ansible Automation Platform (formerly Ansible Tower/AWX), and what capabilities does it add over command-line Ansible?

Mid

Red Hat Ansible Automation Platform (built on the upstream AWX project, formerly Ansible Tower) is an enterprise layer over command-line Ansible that adds a web UI, REST API, and centralized control for running automation at scale.

  • Access and security: Role-based access control (RBAC) and centralized, encrypted credential storage so secrets aren't scattered in files.

  • Operations:

    • Job templates, scheduling, and a visual workflow editor to chain playbooks.

    • Centralized logging, auditing, and job history for compliance.

  • Integration and scale:

    • A REST API and webhooks for CI/CD integration.

    • Automation mesh and execution environments (containerized) for distributed, consistent runs.

  • Vs plain CLI: CLI Ansible is fine for individuals; the Platform adds governance, self-service, and team collaboration.

Q42.
Explain the core differences between Ansible and Terraform, and when you would use each (provisioning vs configuration management).

Mid

Terraform is a declarative provisioning tool that manages infrastructure lifecycle through state, while Ansible is primarily a procedural configuration management tool that configures what already exists; they overlap but excel at different stages.

  • Primary purpose:

    • Terraform: create, update, and destroy infrastructure (VMs, networks, cloud resources).

    • Ansible: install and configure software on that infrastructure.

  • State model:

    • Terraform keeps a state file and reconciles reality to your declared config, knowing what to change or delete.

    • Ansible is largely stateless: it runs idempotent tasks each execution without tracking prior state.

  • Style:

    • Terraform is fully declarative (HCL).

    • Ansible is procedural (ordered tasks in YAML), though it aims for idempotent outcomes.

  • When to use each:

    • Use Terraform to provision and tear down cloud infrastructure.

    • Use Ansible to configure servers, deploy apps, and orchestrate workflows.

Q43.
When would you use Ansible AWX/Automation Platform?

Mid

Use AWX (the upstream open-source project) or Red Hat Ansible Automation Platform (the supported product) when you need to run Ansible as a team service with a UI, RBAC, and auditing rather than ad-hoc from a laptop.

  • Centralized control and access: Role-based access control, teams, and credential storage so secrets aren't scattered across engineers' machines.

  • Operational features:

    • Job templates, scheduling, a REST API, webhooks, and logging/auditing of who ran what and when.

    • Surveys let non-experts launch jobs safely with guided inputs.

  • When not needed: A single operator running playbooks manually or from simple CI often doesn't need the added infrastructure.

  • AWX vs Automation Platform: AWX is community and fast-moving; Automation Platform adds Red Hat support, hardening, and certified content.

Q44.
What are dynamic inventory plugins for cloud providers like AWS, Azure, and GCP?

Mid

Dynamic inventory plugins are collection-provided plugins that query a cloud provider's API and build your inventory automatically, so hosts are discovered in real time instead of being maintained by hand.

  • Per-provider plugins:

    • AWS: amazon.aws.aws_ec2.

    • Azure: azure.azcollection.azure_rm.

    • GCP: google.cloud.gcp_compute.

  • How you use them:

    • Configure a YAML file (conventionally ending *.aws_ec2.yml) and pass it with -i.

    • Authenticate via the provider's normal credentials (env vars, profiles, service accounts).

  • Key features: keyed_groups auto-creates groups from tags/attributes; filters limit which instances are returned; compose builds host variables from metadata.

yaml

# demo.aws_ec2.yml plugin: amazon.aws.aws_ec2 regions: - us-east-1 keyed_groups: - key: tags.Role prefix: role filters: instance-state-name: running

Q45.
How do you manage multiple environments such as development, staging, and production in Ansible?

Mid

The standard approach is to keep one inventory per environment and let group_vars/host_vars hold environment-specific values, so the same playbooks and roles run everywhere with only the data changing.

  • Separate inventory per environment:

    • Keep directories like inventories/dev/, inventories/staging/, inventories/prod/, each with its own hosts file and vars.

    • Select one at run time with -i inventories/prod/, which prevents accidental cross-environment runs.

  • Environment values live in group_vars and host_vars: Same variable names, different values (endpoints, credentials, replica counts) so roles stay generic.

  • Reuse the same playbooks and roles: Only the inventory and vars differ, giving parity between environments and reducing drift.

  • Protect production: Encrypt secrets with ansible-vault and gate prod runs with limits or extra confirmation.

Q46.
What are host patterns in Ansible and how do you use the --limit option to target a subset of hosts?

Mid

Host patterns are expressions that decide which hosts a play or command targets by matching group names, host names, wildcards, or set operations; --limit further narrows the already-selected hosts for a single run.

  • Pattern building blocks:

    • Names and groups: webservers, db01, or all.

    • Wildcards: web*.example.com.

    • Set logic: union web:db, intersection web:&staging, exclusion web:!db01.

  • --limit restricts an existing selection:

    • It intersects with the play's hosts:, so it can only reduce scope, never add hosts outside the play.

    • Handy for a targeted deploy or a rerun on failed hosts (with @retry files).

bash

ansible-playbook site.yml --limit 'webservers:!web01.example.com'

Q47.
How do nested (child) groups work in an Ansible inventory?

Mid

Nested groups let one group contain other groups as children, so variables and host membership cascade downward; a parent's hosts are the union of all its children's hosts.

  • Defined with children: In INI use a [parent:children] section; in YAML use the children: key under a group.

  • Membership rolls up: Targeting the parent runs on every host in every child group.

  • Variables inherit downward: Child group vars override parent group vars, since more specific groups win.

yaml

all: children: production: children: web: hosts: web01: db: hosts: db01:

Q48.
What are connection variables like ansible_host, ansible_user, ansible_port, and ansible_connection, and how are they used?

Mid

These are behavioral inventory variables that tell Ansible how to reach and log into a host; they override the defaults derived from the inventory name.

  • ansible_host: The real address (IP or FQDN) to connect to, letting the inventory alias differ from the actual host.

  • ansible_user: The remote username used for the connection.

  • ansible_port: The connection port (defaults to 22 for SSH).

  • ansible_connection: The connection plugin: ssh (default), local, docker, winrm, etc.

  • Where to set them: Inline in inventory, or in host_vars/group_vars for reuse.

ini

web01 ansible_host=10.0.0.5 ansible_user=deploy ansible_port=2222 ansible_connection=ssh

Q49.
What is host_key_checking and why might you disable it?

Mid

host_key_checking is the SSH behavior where Ansible verifies a host's key against known_hosts and refuses to connect to an unknown or changed key; it defends against man-in-the-middle attacks.

  • What it does: On first contact with an unrecognized host, the connection fails (or prompts) rather than trusting silently.

  • Why disable it: Ephemeral or freshly provisioned hosts (cloud instances, CI) have keys not yet in known_hosts, so checks block automation.

  • How to disable: Set host_key_checking = False in ansible.cfg or export ANSIBLE_HOST_KEY_CHECKING=False.

  • Caveat: Disabling removes MITM protection; prefer pre-seeding keys or ssh-keyscan in production.

Q50.
What is ansible-inventory and how do you use it to inspect or debug your inventory?

Mid

ansible-inventory is a CLI tool that parses your inventory (static or dynamic) and prints the resulting host/group structure and variables, so you can verify what Ansible actually sees before running anything.

  • Common uses:

    • --list: dump all groups, hosts, and variables as JSON.

    • --graph: show a tree of groups and their hosts, great for nested groups.

    • --host web01: show the merged variables for a single host.

  • Why it helps debugging:

    • Reveals variable precedence results and group membership without running a play.

    • Validates dynamic inventory scripts/plugins are returning what you expect.

bash

ansible-inventory -i inventories/prod/ --graph ansible-inventory -i inventories/prod/ --host web01

Q51.
How does import_playbook work and when would you use it to combine multiple playbooks?

Mid

import_playbook statically includes an entire external playbook (all its plays) into the current one at parse time, letting you assemble a master playbook from smaller, reusable ones.

  • Play-level, not task-level: It brings in whole plays (each with their own hosts), so it lives at the top level of a playbook, not inside a tasks list.

  • Static import: Resolved when the playbook is parsed, so it can't use loops or reference runtime variables in the file path.

  • When to use: Orchestrating multi-stage workflows: e.g. a site.yml that chains provisioning, configuration, and deployment playbooks in order.

yaml

# site.yml - import_playbook: provision.yml - import_playbook: configure.yml - import_playbook: deploy.yml

Q52.
Explain the difference between Ansible modules and plugins.

Mid

Modules are the units of work you call in tasks to make changes on targets; plugins extend Ansible's own core engine behavior (how it connects, filters data, caches facts, etc.). Simply put: modules do the work on hosts, plugins augment the controller.

  • Modules:

    • Executed on the target (usually shipped over and run there), each performing a discrete action like installing a package (ansible.builtin.package) or managing a file.

    • Invoked as tasks and return JSON results (changed, failed, etc.).

  • Plugins:

    • Run on the control node and extend the engine: types include connection, filter, lookup, callback, and inventory plugins.

    • You typically use them implicitly (e.g. a Jinja2 filter like | default) rather than calling them as tasks.

  • Key distinction: Modules = actions performed on managed hosts; plugins = extensions of how Ansible itself operates.

Q53.
What are Ansible modules, and can you explain the difference between core and extra modules?

Mid

Modules are the discrete units of work Ansible ships to and executes on managed hosts: each one handles a specific task (managing packages, files, services, cloud resources) and returns JSON. The old core vs extras split is now historical: modules are organized into collections.

  • What a module is:

    • A self-contained program (usually Python) invoked by a task with parameters; it does the work and reports structured results back.

    • Called via the task's key, e.g. ansible.builtin.copy or package.

  • Core (now builtin) modules:

    • Historically maintained by the Ansible core team, guaranteed present, e.g. copy, file, service, command.

    • Today they live in the ansible.builtin collection bundled with Ansible.

  • Extra modules:

    • Community-maintained modules with looser support guarantees.

    • Since Ansible 2.10 they were moved out of the core repo into separate collections on Ansible Galaxy (e.g. community.general, amazon.aws).

  • Practical takeaway: the modern distinction is builtin (shipped) vs collection-based (installed via ansible-galaxy collection install), rather than core vs extras.

Q54.
Explain Ansible modules in detail.

Mid

Modules are the reusable, self-contained units of code Ansible pushes to managed nodes to perform tasks, then removes after execution. They are the building blocks of tasks: you declare desired state, and the module makes it so, reporting back in JSON.

  • How they execute: Ansible copies the module (with its arguments) to the target, runs it (typically under Python), captures its JSON output, then cleans up: agentless, transient execution.

  • Declarative and idempotent: Well-written modules check current state and only act if needed, so re-running a playbook is safe.

  • Categories: System (user, service), files (copy, template), packages (yum, apt), cloud, networking, and more.

  • Invocation:

    • Used inside tasks in playbooks, or ad hoc via ansible -m.

    • Arguments passed as key/value pairs; most return facts you can register.

  • Discovery: browse with ansible-doc -l and read usage with ansible-doc <module>.

Q55.
What is the difference between the command, shell, and raw modules, and when would you use each?

Mid

All three run commands on the target, but they differ in whether a shell is involved and whether Python is required. Prefer command for simple safe execution, shell when you need shell features, and raw only for bootstrapping.

  • command (default, safest):

    • Runs the executable directly without a shell, so no pipes, redirects, &&, or env-var expansion.

    • More secure (no shell injection) and predictable: use it for most command execution.

  • shell:

    • Runs the command through /bin/sh on the target, enabling pipes, redirects, globbing, and variables.

    • Use when you genuinely need shell operators; be careful with untrusted input.

  • raw:

    • Sends the command straight over SSH with no module processing and no Python needed on the target.

    • Mainly for bootstrapping (e.g. installing Python) or managing network/appliance devices.

  • Note: command and shell support creates/removes for idempotency; raw does not.

Q56.
When would you use lineinfile versus blockinfile to manage file content?

Mid

Use lineinfile to manage a single line (ensure one line exists, matches a pattern, or is replaced); use blockinfile to manage a contiguous multi-line block that Ansible marks and owns.

  • lineinfile: single-line edits:

    • Ensure one line is present/absent, or replace a matching line via regexp.

    • Good for toggling a single directive (e.g. PermitRootLogin no in a config).

  • blockinfile: multi-line managed regions:

    • Inserts a block wrapped in BEGIN/END ANSIBLE MANAGED BLOCK markers so it can be updated or removed idempotently.

    • Ideal for several related lines that belong together (a vhost stanza, an SSH match block).

  • Rule of thumb:

    • One line, use lineinfile; a group of lines, use blockinfile.

    • For entire files or complex config, prefer template instead of either.

Q57.
What are connection plugins in Ansible, and what is the difference between ssh, paramiko, local, and winrm?

Mid

Connection plugins define how Ansible transports commands to a target: they abstract the mechanism used to reach a host so modules run the same regardless of transport.

  • ssh: the default for Linux/Unix:

    • Uses the native OpenSSH binary, supporting ControlPersist multiplexing and full SSH config.

    • Fast and feature-rich; the standard choice.

  • paramiko: pure-Python SSH:

    • Fallback when the system SSH binary is unavailable or lacks needed features.

    • Slower, no ControlPersist multiplexing.

  • local: runs on the controller itself: No network transport; executes tasks on localhost, useful for API calls and local orchestration.

  • winrm: for Windows targets: Uses the WinRM protocol (PowerShell remoting) since Windows has no native SSH by default.

  • Selection: Set via ansible_connection per host/group in inventory.

Q58.
Why is it a best practice to prefer dedicated modules over the command or shell modules?

Mid

Dedicated modules are idempotent, state-aware, and portable, while command and shell just run arbitrary commands with no understanding of desired state, so they're harder to make safe and repeatable.

  • Idempotency:

    • Modules like package or copy only change what's needed and report changed accurately.

    • A raw shell command runs every time and always reports changed unless you hand-code guards.

  • Correct change reporting: Accurate changed status keeps handlers, --check mode, and diffs meaningful.

  • Portability and safety: Modules abstract OS differences and avoid shell-injection and quoting pitfalls.

  • When command/shell are OK: No module exists for the action; then add guards like creates, removes, or changed_when to restore idempotency.

Q59.
Why does Ansible require Python on managed nodes, and how do the raw and gather_facts steps relate to this?

Mid

Most Ansible modules are Python programs that Ansible copies to the managed node and executes there, so the node needs a Python interpreter. The raw module and gather_facts step both relate to this requirement, at opposite ends of the process.

  • Why Python is needed: Ansible transfers the module code and runs it with the remote interpreter (ansible_python_interpreter).

  • raw: the exception:

    • Sends commands straight over the connection with no Python required.

    • Used to bootstrap a bare host, e.g. install Python before any real modules can run.

  • gather_facts: needs Python:

    • Runs the setup module (a Python module) at play start to collect facts about the host.

    • Disable it with gather_facts: false on hosts without Python, or until it's installed.

  • Typical pattern: Use raw to install Python, then run setup and normal modules.

Q60.
What are lookups and the lookup plugin in Ansible, and give an example of when you would use one?

Mid

Lookups are controller-side plugins that fetch data from external sources (files, environment, secrets stores, APIs) and return it into your play at templating time, via the lookup() function or the with_ loop syntax.

  • Where they run: On the control node, not the target, so they read the controller's files/env.

  • Common lookups: file (read file contents), env (env var), password (generate/store a password), template, vault.

  • When to use: Pull a secret or config value at runtime rather than hardcoding it, e.g. inject an SSH key read from a file on the controller.

yaml

- name: Authorize a key read from the controller ansible.posix.authorized_key: user: deploy key: "{{ lookup('file', '~/.ssh/id_rsa.pub') }}"

Q61.
How is the set_fact module different from defining variables using vars, vars_files, or include_vars?

Mid

They all create variables, but set_fact sets values dynamically at runtime on a per-host basis during play execution, whereas vars, vars_files, and include_vars load values that are known up front (statically or at load time).

  • set_fact is a runtime task:

    • Runs at a point in the play, so it can capture computed values, results of previous tasks, or conditionals.

    • The fact is scoped to each host and persists for the rest of the play (and into cache if fact caching is on).

    • High precedence: overrides most other variable sources.

  • vars / vars_files: Defined at play or task level, evaluated when the play is parsed; good for static, known-in-advance data.

  • include_vars: Loads a vars file as a task, so you can choose the file dynamically (e.g. based on OS), but the file content itself is still predefined.

  • Rule of thumb: use set_fact when the value must be derived at runtime; use the others for known data.

yaml

- name: Derive a value at runtime set_fact: app_url: "https://{{ inventory_hostname }}:{{ app_port }}"

Q62.
How can you access shell environment variables in Ansible?

Mid

Environment variables are read with the env lookup plugin, but be clear about which machine you mean: lookup('env', ...) reads the controller's environment, while remote-host variables require gathered facts or the shell.

  • Controller environment: Use {{ lookup('env', 'HOME') }}; lookups run on the Ansible control node.

  • Remote host environment:

    • Available via facts as ansible_env (e.g. ansible_env.PATH) when facts are gathered.

    • Or capture it by running a shell command and using register.

  • Setting env for a task: use the environment keyword rather than a lookup.

yaml

- debug: msg: "Controller user: {{ lookup('env', 'USER') }}" - debug: msg: "Remote PATH: {{ ansible_env.PATH }}"

Q63.
How do dot notation and array notation of variables differ in Ansible?

Mid

Both access nested variable data; dot notation (var.key) is shorthand and array/bracket notation (var['key']) is the safer, more explicit form that avoids collisions with Python/Jinja internals.

  • Dot notation: Cleaner to read, but breaks when a key clashes with a dict method (e.g. keys, items, update) or contains dashes/spaces.

  • Array/bracket notation:

    • Handles any key name including reserved words and special characters.

    • Also lets you index dynamically with another variable, e.g. data[mykey].

  • Recommendation: prefer bracket notation for correctness; both resolve to the same value when there's no conflict.

yaml

# Same value, safest form on the right {{ ansible_facts.eth0.ipv4.address }} {{ ansible_facts['eth0']['ipv4']['address'] }}

Q64.
What are extra variables (-e) and where do they sit in the variable precedence order?

Mid

Extra variables are values passed on the command line with -e (or --extra-vars), and they sit at the very top of Ansible's variable precedence: they override everything else.

  • How to pass them:

    • Key-value: -e "version=1.2 env=prod".

    • JSON/YAML: -e '{"version":"1.2"}'.

    • From a file: -e @vars.yml.

  • Highest precedence:

    • They win over role defaults, inventory vars, play vars, host/group vars, and even set_fact and registered vars.

    • This makes them ideal for one-off overrides without editing files.

  • Common uses:

    • Passing a build number, target environment, or feature flag at runtime.

    • Overriding a default temporarily during troubleshooting or CI runs.

  • Caveat: because they cannot be overridden by anything, avoid using them for values that should sometimes be adjusted lower in the stack.

Q65.
What are magic variables such as hostvars, inventory_hostname, and groups, and when would you use them?

Mid

Magic variables are special variables Ansible sets automatically that expose inventory and execution context. You never define them yourself; you read them to make plays aware of the host, its facts, and its group memberships.

  • inventory_hostname:

    • The name of the current host as defined in inventory (not necessarily its DNS name).

    • Use it for per-host logic, naming files, or templating unique config.

  • hostvars:

    • A dict of all hosts and their variables/facts, e.g. hostvars['db01']['ansible_default_ipv4']['address'].

    • Use it to reference another host's data (a common pattern in clustered setups).

  • groups:

    • A dict mapping each group name to its list of member hosts.

    • Use it to loop over peers, e.g. build a list of all web servers for a load balancer config.

  • Related magic vars: group_names (groups the current host belongs to), ansible_play_hosts (hosts active in the play), inventory_dir.

yaml

- name: List all DB server IPs debug: msg: "{{ groups['dbservers'] | map('extract', hostvars, ['ansible_default_ipv4','address']) | list }}"

Q66.
What is vars_prompt and when would you use it to collect input at runtime?

Mid

vars_prompt is a play-level directive that pauses execution to interactively ask the user for input, then stores the answer as a variable. It is used when a value should be supplied at runtime rather than stored in a file, especially secrets.

  • How it works:

    • Defined at the play level; prompts appear before tasks run.

    • Set private: yes (the default) to hide typed input like a password.

    • Supports default, confirm, and even hashing with encrypt.

  • When to use it:

    • Collecting a one-time password or passphrase you do not want on disk.

    • Asking for a confirmation value or environment choice in interactive runs.

  • Caveat: prompts break automation. In CI/CD or unattended runs, prefer -e, Vault, or a default so the play does not hang.

yaml

vars_prompt: - name: db_password prompt: "Enter the DB password" private: yes confirm: yes

Q67.
What is the difference between role defaults and role vars in terms of variable precedence?

Mid

Both live inside a role, but defaults/main.yml holds the lowest-precedence variables (easily overridden), while vars/main.yml holds high-precedence variables meant to be stable internals of the role.

  • Role defaults (defaults/main.yml):

    • The lowest precedence of all variable sources: almost anything overrides them.

    • Use for values you expect users to customize (ports, versions, feature toggles).

  • Role vars (vars/main.yml):

    • High precedence: overridden only by things like block/task vars, include_vars, set_fact, and -e.

    • Use for constants the role relies on that users should not casually change.

  • Rule of thumb: If it is a knob the consumer should tune, put it in defaults; if it is an internal implementation value, put it in vars.

Q68.
What are Ansible Collections and why are they used?

Mid

Ansible Collections are a packaging and distribution format that bundle related content (modules, plugins, roles, and playbooks) into a single versioned, namespaced unit. They decoupled content delivery from the core Ansible release.

  • What they contain: Modules and plugins, roles, playbooks, and documentation under a namespace.collection name (e.g. community.general).

  • Why they exist:

    • Independent release cycles: vendors ship updates without waiting for a new Ansible core release.

    • Modularity: install only what you need instead of one monolithic package.

    • Clear ownership and versioning via galaxy.yml metadata.

  • How you use them:

    • Install with ansible-galaxy collection install or pin them in a requirements.yml.

    • Reference content by fully qualified collection name, e.g. community.mysql.mysql_user.

Q69.
What is an Ansible role and how do you create one, and how do roles promote modularity and collaboration in automation workflows?

Mid

A role is a standardized directory structure that packages related tasks, variables, files, templates, and handlers into a reusable unit. Roles let you organize a playbook's logic into self-contained components that can be shared across projects and teams.

  • Standard structure: tasks/, handlers/, defaults/, vars/, files/, templates/, meta/; each has a main.yml auto-loaded by Ansible.

  • How to create one:

    • Run ansible-galaxy init myrole to scaffold the directories, then fill in tasks/main.yml.

    • Consume it in a play with the roles: keyword or include_role/import_role.

  • Why they promote modularity and collaboration:

    • Reuse: the same role runs across many playbooks and environments.

    • Clear interface: defaults expose tunable inputs so consumers customize without editing internals.

    • Team workflows: roles can be versioned, tested, and shared via Galaxy or Git.

Q70.
What are Ansible roles and how do they differ from playbooks?

Mid

A role is a standardized, reusable unit of automation that bundles tasks, handlers, variables, templates, and files into a fixed directory structure. A playbook is the top-level orchestration file that maps hosts to what should run on them, often by calling roles.

  • Roles are reusable building blocks:

    • They enforce a convention-over-configuration layout (tasks/, handlers/, defaults/, templates/) so content is portable and shareable.

    • A role has no host mapping of its own: it just describes what to do.

  • Playbooks orchestrate:

    • A playbook is a YAML file with one or more plays, each binding hosts to tasks or roles.

    • It defines where (targets) and in what order automation runs.

  • Key difference: Roles maximize reuse and encapsulation; playbooks provide the execution context that ties roles to inventory.

yaml

- hosts: webservers roles: - nginx - app_deploy

Q71.
What is an Ansible collection namespace?

Mid

A collection namespace is the first part of a collection's fully qualified name, identifying the author or organization that owns it. Collections are always referenced as namespace.collection, which prevents naming clashes across the ecosystem.

  • Two-part naming: For example community.general or ansible.posix: the namespace is community / ansible.

  • Prevents collisions: Two authors can both ship a collection called utils because their namespaces differ.

  • Used in fully qualified content names (FQCN): Modules are called as namespace.collection.module, e.g. ansible.builtin.copy.

  • On Galaxy, a namespace is reserved to an account/org: You must own the namespace to publish under it.

Q72.
How do you pin versions of Collections in requirements.yml?

Mid

In requirements.yml you list each collection under a collections: key and specify a version constraint. This makes installs reproducible so ansible-galaxy collection install -r requirements.yml pulls the exact versions you tested.

  • Exact pin: version: "6.6.0" locks to a single release: most reproducible.

  • Range operators: Use >=, <=, !=, or *; combine with commas like >=1.0.0,<2.0.0.

  • Source and type: You can add source: (a Galaxy or Automation Hub URL) or a git repo with type: git and a version: pointing to a tag/branch/commit.

yaml

collections: - name: community.general version: "6.6.0" - name: ansible.posix version: ">=1.4.0,<2.0.0" - name: https://github.com/org/mycoll.git type: git version: v1.2.0

Q73.
Describe the purpose of each key file in a standard Ansible role directory (e.g., tasks/main.yml, handlers/main.yml, defaults/main.yml, vars/main.yml, meta/main.yml).

Mid

A standard role has a fixed set of directories, each with a main.yml auto-loaded by Ansible. Each file has a specific job, which is what makes roles predictable and reusable.

  • tasks/main.yml: The main list of tasks the role executes: its core logic.

  • handlers/main.yml: Handlers triggered via notify, typically service restarts, run once at the end of a play.

  • defaults/main.yml: Default variables with the lowest precedence: meant to be overridden by users.

  • vars/main.yml: Role variables with high precedence: internal constants not meant to be overridden.

  • meta/main.yml: Metadata: author/license info and role dependencies that run before this role.

  • Other common dirs: templates/ (Jinja2 .j2 files), files/ (static files to copy), and meta/argument_specs.yml for validating role inputs.

Q74.
Explain the difference between Ansible playbooks, roles, and collections.

Mid

They are three layers of packaging at increasing scope: a playbook orchestrates automation against hosts, a role bundles reusable automation logic, and a collection distributes roles plus plugins/modules under a namespace.

  • Playbook (orchestration): Maps hosts to tasks/roles and defines execution order: the entry point you run with ansible-playbook.

  • Role (reusable logic): A structured folder of tasks, handlers, vars, templates: reused across playbooks but not runnable on its own.

  • Collection (distribution unit): A packaged bundle of roles, modules, plugins, and playbooks under namespace.name, installable via ansible-galaxy.

  • How they nest: A collection can contain roles and playbooks; a playbook uses roles; roles use modules (which often ship inside collections).

Q75.
What is the best way to make content reusable/redistributable in Ansible?

Mid

Package your automation as a role for reuse, then bundle related roles, modules, and plugins into a collection for redistribution. Collections are the modern, versioned, namespaced standard for sharing content via Ansible Galaxy or Automation Hub.

  • Start with roles:

    • Parameterize behavior through defaults/main.yml so consumers override without editing internals.

    • Keep roles single-purpose and idempotent.

  • Distribute with collections: They add semantic versioning, a namespace, dependency metadata (galaxy.yml), and FQCN addressing.

  • Pin dependencies: Declare required collections in requirements.yml with version constraints for reproducibility.

  • Good hygiene: Document variables, ship examples, and use meta/argument_specs.yml to validate inputs.

Q76.
How do you structure playbooks to include and reuse multiple roles efficiently?

Mid

Compose small single-purpose roles and pull them in either statically with the roles: keyword or dynamically with include_role / import_role inside tasks. Choose static vs dynamic based on whether you need conditional/looped inclusion.

  • Static play-level with roles: Runs roles in listed order before regular tasks; simplest for a fixed pipeline.

  • import_role (static): Parsed at playbook parse time; tags and dependencies are pre-processed.

  • include_role (dynamic): Evaluated at runtime, so it can sit behind when: or inside a loop:.

  • Pass variables explicitly: Use vars: on the role entry to configure it, keeping roles decoupled.

  • Layer dependencies: Declare prerequisite roles in meta/main.yml so common setup runs automatically.

yaml

- hosts: web roles: - common - role: nginx vars: nginx_port: 8080 tasks: - include_role: name: app_deploy when: deploy_enabled | bool

Q77.
What is Ansible Galaxy, and how does it relate to Ansible Collections?

Mid

Ansible Galaxy is the public community hub for finding, sharing, and downloading Ansible content, and ansible-galaxy is the CLI that installs it. Collections are the primary content format Galaxy now hosts and serves.

  • Galaxy is the repository/registry: A website plus API where authors publish collections (and standalone roles) under their namespace.

  • The CLI is how you consume it: ansible-galaxy collection install community.general or install a batch from requirements.yml.

  • Relationship to collections: Collections are the packaging format; Galaxy is the distribution channel that stores and versions them.

  • Enterprise counterpart: Red Hat Automation Hub serves certified/supported collections; you can point installs there too.

Q78.
What is a Fully Qualified Collection Name (FQCN) and why does Ansible recommend using it?

Mid

An FQCN is the fully namespaced identifier for a module, plugin, or role in the form namespace.collection.name (e.g. ansible.builtin.copy or community.general.ufw). Ansible recommends it because it removes ambiguity about which content is actually being run.

  • Structure:

    • Three parts: namespace (vendor/org), collection, then the plugin or module name.

    • Example: amazon.aws.ec2_instance.

  • Why it matters:

    • Since content moved into collections (Ansible 2.10+), the same short name can exist in multiple collections; the FQCN pins exactly one.

    • Avoids surprises when the search path or installed collections change.

  • Best practice: Use FQCNs in playbooks and roles for clarity and forward compatibility; short names still resolve but rely on collections: search order.

Q79.
What is the difference between ansible-core and the community Ansible package?

Mid

ansible-core is the minimal engine (language, executor, and the ansible.builtin modules), while the community Ansible package is a large distribution that bundles ansible-core plus hundreds of curated collections.

  • ansible-core:

    • The runtime engine plus a small set of built-in modules only.

    • Installed via pip install ansible-core; lightweight and fast to update.

  • ansible (community package):

    • A batteries-included release that ships ansible-core together with a big set of collections (community.general, cloud collections, etc.).

    • Installed via pip install ansible; convenient for getting broad functionality at once.

  • Practical choice: Use ansible-core plus explicitly installed collections for lean, controlled environments; use the full package for convenience.

Q80.
How do you pass parameters to a role when calling it?

Mid

You pass parameters by supplying variables alongside the role call; these become role-scoped variables with high precedence. The exact syntax depends on whether you use the roles: keyword or include_role/import_role.

  • With the roles: keyword: Add key/value pairs after role:, or nest them under vars:.

  • With include_role / import_role: Use the vars: section on the task.

  • Precedence note: Parameters passed this way outrank role defaults (defaults/main.yml), which is exactly why defaults exist as overridable fallbacks.

yaml

# via roles: keyword roles: - role: webserver vars: http_port: 8080 # via include_role tasks: - include_role: name: webserver vars: http_port: 8080

Q81.
How do you secure sensitive data in Ansible, and describe the workflow for using Ansible Vault to encrypt passwords and other sensitive data.

Mid

Ansible secures sensitive data with Ansible Vault, which encrypts files or individual variables with AES256 so secrets can be committed to source control safely and only decrypted at runtime with the vault password.

  • What you can encrypt:

    • Whole files (a group_vars/vault.yml) with ansible-vault create/encrypt.

    • Single values inline using ansible-vault encrypt_string.

  • Typical workflow:

    1. Put secrets in a dedicated vars file and encrypt it: ansible-vault encrypt group_vars/prod/vault.yml.

    2. Reference the encrypted variables normally in playbooks/templates.

    3. Run with the password: ansible-playbook site.yml --ask-vault-pass or --vault-password-file.

    4. Edit later with ansible-vault edit; rotate with rekey.

  • Best practices:

    • Keep encrypted and plaintext vars separate (a vars.yml + vault.yml pattern) so you can see variable names without decrypting.

    • Use no_log: true on tasks handling secrets to keep them out of output.

    • Never commit the vault password itself.

yaml

# encrypt one value inline # $ ansible-vault encrypt_string 's3cret' --name 'db_password' db_password: !vault | $ANSIBLE_VAULT;1.1;AES256 66386439653...<snip>

Q82.
How does Ansible ensure security in general, considering SSH, Vault, and least privilege?

Mid

Ansible's security model layers transport encryption (SSH), secret encryption (Vault), and controlled privilege escalation so control-node-to-node communication, data at rest, and executed actions are all constrained.

  • Secure transport by default (SSH):

    • Ansible connects over SSH, so traffic is encrypted and authenticated without any agent installed on targets.

    • Favor key-based auth over passwords and verify host keys to prevent MITM.

  • Secrets at rest (Vault):

    • ansible-vault encrypts variable files and strings with AES-256 so secrets can be committed safely.

    • Combine with no_log: true to avoid leaking decrypted values in output.

  • Least privilege:

    • Connect as an unprivileged user and escalate only when needed via become.

    • Scope escalation per task, and restrict what the automation account can do via sudo rules and target-side ACLs.

  • Operational controls: Centralize credentials in AAP/AWX, audit runs, and rotate keys and vault passwords regularly.

Q83.
How do you manage multiple vault passwords or vault IDs in Ansible?

Mid

Vault IDs let you label encrypted content with an identity so a single playbook can use multiple vault passwords (for example, separate dev and prod secrets) and Ansible picks the matching key automatically.

  • Encrypt with a labeled ID: ansible-vault encrypt --vault-id prod@prompt secrets.yml tags the file with the prod identity.

  • Provide multiple IDs at runtime:

    • Pass several --vault-id flags; each maps a label to a prompt or a password file.

    • Ansible tries the matching ID first, then others, so mixed-ID content decrypts in one run.

  • Password sources per ID: Use @prompt to be asked interactively or @/path/file (including an executable script) for automation.

  • Legacy single password: Without IDs, --vault-password-file or --ask-vault-pass supplies one global password.

bash

ansible-playbook site.yml \ --vault-id dev@~/.vault_dev_pass \ --vault-id prod@prompt

Q84.
How do you encrypt a single variable using ansible-vault encrypt_string versus encrypting an entire file?

Mid

encrypt_string encrypts one value and emits an encrypted YAML snippet you paste inline among plaintext variables, whereas encrypting a file scrambles the entire file's contents.

  • encrypt_string (single variable):

    • Produces an !vault tagged block you drop into an otherwise readable vars file.

    • Keeps most variables human-readable and diffable while hiding just the sensitive ones.

    • Great for one or two secrets sprinkled among normal config.

  • encrypt (whole file):

    • Encrypts the full file, so its contents are opaque in the repo and must be viewed with ansible-vault view or edited with ansible-vault edit.

    • Best when a file is entirely secrets or you want the whole thing protected.

  • Trade-off: Inline strings give better readability and diffs; whole-file encryption is simpler but hides everything.

bash

# Single variable, ready to paste into a vars file ansible-vault encrypt_string 'S3cr3t!' --name 'db_password' # Entire file ansible-vault encrypt group_vars/prod/secrets.yml

Q85.
What does ansible-vault rekey do and how do you supply a vault password with --vault-password-file?

Mid

ansible-vault rekey changes the password protecting already-encrypted content: it decrypts with the old password and re-encrypts with a new one, without exposing the plaintext.

  • What rekey does:

    • Rotates the vault password on one or more files in place.

    • Useful when a password is compromised or on a rotation schedule.

  • Supplying the current password non-interactively:

    • --vault-password-file points to a file (or executable script) containing the password, avoiding prompts in automation/CI.

    • For rekey, the old password comes from that file while the new one is prompted (or given via --new-vault-password-file).

  • Security note: Lock down the password file's permissions since it holds the key in plaintext.

bash

# Rotate password: old key from file, new key from another file ansible-vault rekey secrets.yml \ --vault-password-file ~/.vault_old \ --new-vault-password-file ~/.vault_new

Q86.
What are the different become_method options (sudo, su, doas) and how do you configure become_user?

Mid

become_method chooses which underlying tool performs privilege escalation, and become_user names the identity you switch to; together they control how and to whom you escalate.

  • sudo (default):

    • Runs the task as another user via sudo; most common on Linux.

    • May require a password unless configured NOPASSWD.

  • su: Switches user with su; needs the target user's password rather than the caller's.

  • doas: Lightweight sudo alternative common on OpenBSD; same escalation role.

  • Others: pbrun, pfexec, runas (Windows), machinectl, etc.

  • Configuring become_user:

    • Set become_user at play/block/task level; defaults to root when omitted.

    • Can also be set globally in ansible.cfg or via inventory variables.

yaml

- name: Run a command as the postgres user ansible.builtin.command: pg_dump mydb become: true become_method: sudo become_user: postgres

Q87.
What are handlers in Ansible, how are they triggered, and why do they run only once even if notified multiple times?

Mid

A handler is a special task that runs only when another task notifies it, typically to restart or reload a service after a change. Handlers are triggered by the notify directive and, by default, run once at the very end of the play regardless of how many tasks notified them.

  • How they are triggered:

    • A task with notify: "restart nginx" queues that handler, but only if the task reports changed.

    • The handler name (or listen topic) must match the notify string.

  • Why they run only once:

    • Notifications are deduplicated: multiple notifies of the same handler collapse to a single run, avoiding restarting a service several times.

    • They execute after all tasks in the play complete, in the order handlers are defined (not notification order).

  • Important caveats:

    • If a later task fails, queued handlers may not run; use --force-handlers or force_handlers: true to force them.

    • Force mid-play execution with the meta: flush_handlers task.

yaml

tasks: - name: Deploy config ansible.builtin.template: src: nginx.conf.j2 dest: /etc/nginx/nginx.conf notify: restart nginx handlers: - name: restart nginx ansible.builtin.service: name: nginx state: restarted

Q88.
What is a loop in Ansible, when would you use it, and how can you implement looping over a list of hosts in a group?

Mid

A loop repeats a single task over a collection of items, so you avoid duplicating tasks for each value. Use it whenever you'd otherwise copy a task multiple times: installing several packages, creating multiple users, or iterating over host lists. The modern keyword is loop, with the current item exposed as item.

  • Basic looping:

    • loop takes a list; each iteration binds the value to item.

    • loop replaces the older with_items family for most cases.

  • When to use it: Any time the same action applies to many values; combine with when to filter items.

  • Looping over hosts in a group:

    • Use the groups magic variable, e.g. groups['webservers'], which is a list of host names.

    • Pull per-host facts via hostvars[item] to read another host's IP or variables.

yaml

- name: Build /etc/hosts entries from the webservers group ansible.builtin.lineinfile: path: /etc/hosts line: "{{ hostvars[item]['ansible_host'] }} {{ item }}" loop: "{{ groups['webservers'] }}"

Q89.
How do you handle errors in an Ansible playbook using ignore_errors, failed_when, and rescue blocks?

Mid

Ansible stops a host on the first failed task by default; error handling lets you override that. Use ignore_errors to continue despite a failure, failed_when to redefine what "failed" means, and block/rescue to catch failures and run recovery logic.

  • ignore_errors:

    • ignore_errors: true marks the task failed but continues the play on that host.

    • Best paired with register so you can inspect and react to the result later.

  • failed_when:

    • Defines a custom failure condition, e.g. flag failure only when output contains an error string.

    • Set failed_when: false to treat a task as never failing.

  • rescue blocks:

    • Tasks in rescue run only if a task in the block fails, like a try/except.

    • A successful rescue clears the failure, so the host continues.

yaml

- name: Attempt with recovery block: - name: Risky command ansible.builtin.command: /opt/deploy.sh register: out failed_when: "'ERROR' in out.stdout" rescue: - name: Roll back ansible.builtin.command: /opt/rollback.sh

Q90.
What are blocks in Ansible and how do block/rescue/always work for grouping tasks and error handling?

Mid

A block groups related tasks so they can share directives (like when, become, or tags) and participate in structured error handling. Combined with rescue and always, a block behaves like try/except/finally for tasks.

  • block: Holds the main tasks; directives applied to the block cascade to every task inside.

  • rescue:

    • Runs only if a task in the block fails; use it for cleanup or rollback.

    • Access failure details via ansible_failed_task and ansible_failed_result.

  • always: Runs no matter what, whether the block succeeded or failed: ideal for closing/cleanup steps.

  • Key behavior: If rescue completes successfully, the host's failure is cleared and the play continues.

yaml

- block: - name: Deploy app ansible.builtin.command: /opt/deploy.sh rescue: - name: Notify failure ansible.builtin.debug: msg: "Deploy failed: {{ ansible_failed_result.msg }}" always: - name: Clean temp files ansible.builtin.file: path: /tmp/deploy state: absent

Q91.
How do you retry a task until a condition is met using until, retries, and delay?

Mid

The until keyword retries a task until a condition becomes true, which is the standard way to poll for readiness (a service coming up, an endpoint responding). You pair it with retries (max attempts) and delay (seconds between attempts).

  • How it works:

    • The task runs, then until is evaluated against the registered result.

    • If false, Ansible waits delay seconds and retries, up to retries times.

    • Defaults are retries: 3 and delay: 5.

  • Registering the result: You must register the task and reference that variable in the until expression.

  • Outcome:

    • If the condition is never met after all retries, the task fails.

    • The result includes an attempts field showing how many tries it took.

yaml

- name: Wait for service to be healthy ansible.builtin.uri: url: http://localhost:8080/health status_code: 200 register: result until: result.status == 200 retries: 10 delay: 5

Q92.
What is the difference between the with_items family of loops and the newer loop keyword?

Mid

The with_* family (with_items, with_dict, etc.) is the older looping syntax backed by lookup plugins, while loop is the modern, recommended keyword that takes a plain list and pairs with filters for advanced cases.

  • with_* uses lookup plugins:

    • The suffix maps to a lookup: with_items runs lookup('items', ...), which also flattens one level of nested lists.

    • Rich variants exist (with_nested, with_subelements, with_fileglob) that encode complex behavior implicitly.

  • loop is the current standard:

    • Takes a simple list and does NOT auto-flatten, so behavior is more predictable.

    • For what the old variants did, use filters/lookups explicitly: loop: "{{ a | product(b) | list }}" replaces with_nested.

  • Guidance:

    • Ansible recommends loop for new code; with_* is not deprecated but discouraged.

    • Control naming/labels with loop_control (loop_var, label).

Q93.
What is the difference between changed_when and failed_when, and how do they customize task status?

Mid

Both override how Ansible reports a task's outcome: changed_when controls whether the task is marked changed, and failed_when controls whether it's marked failed, based on conditions you define.

  • changed_when:

    • Decides the changed/ok status, which matters because changed status triggers handlers.

    • Common with command/shell, which always report changed; set changed_when: false for read-only commands.

  • failed_when:

    • Defines what counts as failure, evaluated against the task result (rc, stdout, etc.).

    • Lets you accept a nonzero exit code, or fail on a message even when rc is 0.

  • Note: They are independent: a task can be marked failed while also having been a change; typically you register the result and test its fields.

yaml

- command: /usr/bin/check-status register: result changed_when: "'updated' in result.stdout" failed_when: result.rc != 0 and 'already exists' not in result.stderr

Q94.
What does ignore_unreachable do and how is it different from ignore_errors?

Mid

ignore_unreachable tells Ansible to continue when a host is unreachable (SSH/connection failure), whereas ignore_errors only suppresses task-level failures on hosts that were reachable.

  • Two distinct failure categories:

    • Unreachable: Ansible couldn't connect at all (timeout, auth, host down).

    • Failed: connection succeeded but the module reported failure.

  • ignore_errors: Continues past a failed task result; does NOT rescue an unreachable host.

  • ignore_unreachable:

    • Keeps the host in play despite a connection failure, so subsequent tasks still attempt to run on it.

    • Can be set at task or play level.

  • Practical use: Useful when a reboot temporarily drops connectivity and you don't want the whole play to abandon the host.

Q95.
What do the assert and fail modules do and when would you use them?

Mid

assert validates that conditions are true and stops the play with a clear message if not, while fail unconditionally fails a task (usually gated by a when); both enforce preconditions and give meaningful error output.

  • assert:

    • Takes that: a list of conditions that must all evaluate true.

    • Supports fail_msg and success_msg for readable output.

    • Best for guarding required variables/inputs at the start of a role.

  • fail:

    • Just aborts with a msg; you decide when via when.

    • Best when logic is complex or the failure condition is computed elsewhere.

  • Choosing: Use assert for declarative precondition checks; use fail for imperative, conditional bail-outs.

yaml

- assert: that: - app_port is defined - app_port | int > 0 fail_msg: "app_port must be a positive integer" - fail: msg: "Unsupported OS: {{ ansible_distribution }}" when: ansible_distribution not in supported_distros

Q96.
What are the 'always' and 'never' special tags and how do they behave with --tags and --skip-tags?

Mid

They are reserved tag names that override normal tag filtering: always makes a task run in almost every case, while never makes a task run only when explicitly requested.

  • always:

    • A task tagged always runs even when you pass --tags that don't match it.

    • You can still suppress it with --skip-tags always or by requesting a specific tag combination that excludes it.

  • never:

    • A task tagged never is skipped by default and only runs if you explicitly pass one of its other tags via --tags.

    • Useful for expensive or debug tasks you almost never want to run automatically.

  • Interaction rule: Give a never task a second, meaningful tag (e.g. debug) so --tags debug can opt it in.

yaml

- name: Wipe and rebuild DB command: /opt/rebuild.sh tags: [never, rebuild] # runs only with --tags rebuild - name: Always print environment debug: var=ansible_env tags: [always] # runs unless --skip-tags always

Q97.
Explain the use of the delegate_to directive and provide a scenario where it would be useful.

Mid

delegate_to tells Ansible to run a particular task on a different host than the one currently being processed in the play, while still using the original host's variables and context.

  • How it works:

    • The task executes on the delegated host, but the loop item / inventory_hostname still refers to the original host.

    • Variables are resolved from the original host unless you also delegate facts.

  • Common scenarios:

    • Add/remove a web server from a load balancer by delegating the API call to the LB host.

    • Register a monitoring check on a central monitoring server for each app host.

    • Run a database import on the DB server while iterating over app nodes.

  • delegate_to: localhost is a frequent form for running local commands or API calls from the control node.

yaml

- name: Take host out of the load balancer community.general.haproxy: state: disabled host: "{{ inventory_hostname }}" delegate_to: lb01.example.com

Q98.
What is the local_action directive and how does it relate to delegate_to: localhost?

Mid

local_action is shorthand for running a task on the control node, and it is functionally equivalent to writing the task normally with delegate_to: localhost.

  • local_action: Written as a single line prefixing the module, forcing execution on the Ansible controller.

  • Relationship to delegation:

    • local_action: module args is just syntactic sugar for a task using delegate_to: localhost.

    • delegate_to is more flexible: it can target any host, not only localhost, and reads more clearly in modern playbooks.

  • Guidance: Prefer delegate_to: localhost for consistency; local_action is legacy style still seen in older code.

yaml

# Equivalent tasks - local_action: command echo hello - command: echo hello delegate_to: localhost

Q99.
What is the ansible.cfg file, and what are some common settings configured within it?

Mid

ansible.cfg is Ansible's INI-style configuration file that customizes default behavior, so you don't have to pass the same flags on every command line.

  • Common [defaults] settings:

    • inventory: path to the inventory file/directory.

    • remote_user: default SSH user for connections.

    • roles_path and collections_path: where to find roles and collections.

    • host_key_checking: toggle SSH host key verification.

    • forks: number of parallel host connections.

    • gathering: fact-gathering policy (smart, explicit).

  • Other sections:

    • [privilege_escalation]: become, become_method, become_user.

    • [ssh_connection]: pipelining, control_path, SSH args for performance.

ini

[defaults] inventory = ./inventory remote_user = deploy host_key_checking = False forks = 20 [privilege_escalation] become = True become_method = sudo

Q100.
What are the benefits of using Ansible Navigator?

Mid

ansible-navigator is a modern text-based UI and command runner that executes playbooks inside execution environments (containers), giving you consistent, portable, and inspectable automation.

  • Execution environments: Runs content in a container image bundling Ansible, Python, collections, and dependencies, eliminating "works on my machine" drift.

  • Interactive TUI: Drill into play/task results, inventory, and collection docs interactively instead of scrolling raw output.

  • Consistency with automation platform: Uses the same execution environments as Ansible Automation Platform / AWX, so local runs match production.

  • Convenience: Replaces multiple commands (ansible-playbook, ansible-inventory, ansible-doc) under one tool, with a --mode stdout option for classic output.

Q101.
Where can the ansible.cfg file live and how is its precedence determined?

Mid

Ansible searches several locations for ansible.cfg and uses the first one it finds, so a project-local file can override system defaults; the entire file is chosen, settings are not merged across files.

  • Precedence order (highest first):

    1. ANSIBLE_CONFIG: environment variable pointing to a specific file.

    2. ansible.cfg in the current working directory.

    3. ~/.ansible.cfg in the user's home directory.

    4. /etc/ansible/ansible.cfg: the system-wide default.

  • Key behaviors:

    • Only the first match wins; there is no layering or merging between config files.

    • The current-directory file makes configuration project-scoped and easy to commit to version control.

    • Run ansible --version to see which config file is actually in use.

Q102.
What is ansible-lint and how does it help improve playbook quality?

Mid

ansible-lint is a static analysis tool that checks playbooks, roles, and collections against a set of rules for best practices, deprecations, and stylistic issues, catching problems before you run anything against real hosts.

  • What it checks:

    • Best practices (use FQCN like ansible.builtin.copy, name every task, avoid command where a module exists).

    • Deprecated syntax and modules, risky idioms (bare variables, ignored changed state).

  • How it helps quality:

    • Enforces consistency across a team and surfaces idempotency and security smells early.

    • Runs fast and offline, ideal in CI or pre-commit hooks to gate merges.

  • Configurable: Use .ansible-lint to skip or enforce rules, set profiles (min, basic, production), and add # noqa inline exceptions.

bash

ansible-lint playbook.yml ansible-lint --profile production .

Q103.
What is a template in Ansible, and how does it use Jinja2 syntax to generate dynamic configuration files?

Mid

A template is a text file containing Jinja2 expressions that Ansible renders on the control node (using variables, facts, and logic) and then copies to the target host via the template module, letting you generate host-specific configuration files dynamically.

  • How it works:

    • Template files use the .j2 extension and live in a role's templates/ directory.

    • The template module renders it with all in-scope variables and places the result at dest.

  • Jinja2 syntax:

    • {{ }} substitutes variable values.

    • {% %} runs control logic like if and for.

    • {# #} is a comment that isn't rendered.

  • Why it matters: One template produces per-host config from inventory variables, keeping configuration DRY and idempotent.

jinja

# nginx.conf.j2 server { listen {{ http_port }}; server_name {{ ansible_hostname }}; {% for upstream in backends %} server {{ upstream }}; {% endfor %} }

Q104.
What does the 'default' Jinja2 filter do in Ansible, and how is it different from 'mandatory'?

Mid

The default filter supplies a fallback value when a variable is undefined, so rendering continues gracefully; mandatory does the opposite, forcing an explicit error if the variable is undefined.

  • default(value):

    • Returns value when the variable is undefined: {{ port | default(8080) }}.

    • By default it only triggers on undefined, not on empty strings or false; pass true as second arg (default(8080, true)) to also replace "falsy" values.

  • mandatory:

    • {{ password | mandatory }} raises an error immediately if the variable was never defined.

    • Useful for required inputs where silently continuing would be dangerous.

  • When to use which: default for optional settings with sensible fallbacks; mandatory to fail fast on missing critical values.

Q105.
How does the serial keyword control batch sizes in a rolling update?

Mid

The serial keyword sets how many hosts Ansible runs a play against at once: it divides the inventory into sequential batches, each completing the whole play before the next batch begins.

  • Accepts several forms:

    • An integer (serial: 3): three hosts per batch.

    • A percentage (serial: "25%"): a quarter of the hosts per batch.

    • A list (serial: [1, 5, 10]): ramping batch sizes, ideal for canary rollouts.

  • Batch semantics: All tasks (and handlers) finish for one batch before the next starts, keeping the rest of the fleet untouched.

  • Works with failure control: max_fail_percentage is evaluated per batch, so a failing batch can stop the whole play.

  • Relation to forks: serial caps how many hosts are in play; forks caps how many are contacted in parallel within that limit.

Q106.
What are forks in Ansible and how do they control parallelism across hosts?

Mid

Forks are the number of parallel processes Ansible spawns on the control node to communicate with hosts simultaneously. It's the main dial for how much of your inventory is worked on at the same time.

  • How it works:

    • For each task, Ansible processes hosts in parallel up to the fork count, then moves to the next batch of hosts.

    • Default is 5, which is conservative for large fleets.

  • Where to set it: forks under [defaults] in ansible.cfg, or the -f flag on the command line.

  • Trade-offs:

    • Higher forks speed up large runs but consume more CPU, memory, and file descriptors on the control node.

    • Bounded by control-node resources, not target count.

  • Interaction with serial: forks is global parallelism; serial further restricts how many hosts a play touches at once (effective parallelism is the smaller of the two).

Q107.
How do you implement CI/CD integration with Ansible?

Mid

Ansible becomes the deploy/config stage of a pipeline: the CI tool checks out the repo, provides credentials, and invokes ansible-playbook against the target inventory, with linting and dry runs gating the change.

  • Treat playbooks as versioned code: Store roles/playbooks in Git; pin dependencies with a requirements.yml installed via ansible-galaxy.

  • Validate stages: Run ansible-lint and yamllint, then a --check --diff dry run, and optionally Molecule tests before deploying.

  • Inject secrets at runtime: Pull credentials from the CI secret store or Vault, or pass an --vault-password-file for Ansible Vault.

  • Promote across environments: Use per-environment inventories and group_vars; require manual approval before the production job runs.

  • Non-zero exit fails the pipeline: A failed play returns non-zero, which the CI runner treats as a failed build automatically.

Q108.
What is check mode (--check) in Ansible, and when would you use it?

Mid

Check mode (--check) is a dry run: Ansible reports what it would change without actually making any changes, letting you preview the effect of a playbook safely.

  • What it does:

    • Tasks report changed or ok as if they ran, but no state is modified.

    • Especially useful before applying changes to production.

  • Module support matters:

    • Idempotent modules generally support check mode; some (e.g. command, shell) are skipped by default because Ansible can't predict their effect.

    • Pair with --diff to see exactly what would change.

  • Per-task control: Force a task to always run (or never) with the check_mode keyword on the task.

  • Caveat: chained tasks may misreport: If task B depends on a change task A only simulated, results in check mode can be inaccurate.

Q109.
How do you debug a failing Ansible playbook, and what command-line flags and Ansible modules would you use?

Mid

Debug a failing playbook by increasing verbosity, inspecting variables and task output, and isolating the failing task: Ansible provides both CLI flags and modules for this.

  • Increase verbosity: -v to -vvvv: more v's show module arguments, connection details, and full tracebacks.

  • Control execution flow:

    • --start-at-task to resume at a specific task; --step to confirm each task interactively.

    • --check and --diff to preview changes; --limit to target one host.

  • Inspect data with modules:

    • debug: print a variable or message (var: or msg:).

    • Register a task result then debug it to see full return values.

    • assert: fail early with a clear condition; fail to stop with a custom message.

  • Interactive debugger: Add debugger: on_failed to drop into a prompt where you can inspect and re-run the task.

yaml

- name: Show a registered result ansible.builtin.command: whoami register: result - ansible.builtin.debug: var: result

Q110.
How do Ansible and Terraform complement each other in a modern CI/CD pipeline or infrastructure lifecycle?

Senior

They complement each other by splitting the infrastructure lifecycle: Terraform provisions the infrastructure, then Ansible configures and deploys onto it, a common pattern in CI/CD pipelines.

  • Sequential handoff: Terraform creates VMs, networks, and load balancers, then Ansible installs packages and deploys the application.

  • Passing data between them: Terraform outputs (IPs, hostnames) feed Ansible inventory, often via a dynamic inventory plugin.

  • In a CI/CD pipeline:

    • A pipeline stage runs terraform apply, then a later stage runs ansible-playbook against the new hosts.

    • Keeps immutable infrastructure provisioning separate from mutable configuration.

  • Why not one tool: Each stays in its strength: Terraform's state-driven provisioning and Ansible's rich configuration and orchestration.

Q111.
What are some best practices for securing your inventory files and access control?

Senior

Secure inventories by keeping secrets out of plaintext, restricting file access, and controlling who can target which hosts: the inventory is effectively a map of your infrastructure, so treat it as sensitive.

  • Never store plaintext secrets: Encrypt sensitive variables with ansible-vault, or pull them from a secrets manager (Vault, cloud secret stores) at runtime.

  • Lock down file permissions: Restrict read access on inventory and group_vars/host_vars files; keep them in version control with review, but never commit unencrypted credentials.

  • Prefer keys and least privilege: Use SSH keys over passwords, dedicated automation accounts, and scoped become privileges rather than blanket root.

  • Control access centrally: Use AWX/Automation Platform RBAC so teams only reach their own inventories and credentials, with an audit trail.

Q112.
What is the order of execution within a play (pre_tasks, roles, tasks, post_tasks, handlers)?

Senior

Within a play, Ansible runs sections in a fixed order: pre_tasks, then roles, then tasks, then post_tasks. Handlers notified anywhere in a section run at the end of that section, not at the very end of the play.

  1. pre_tasks: Run first (e.g. validation or prep). Handlers notified here flush before roles begin.

  2. roles: Role tasks execute in the order roles are listed.

  3. tasks: The play's main task list, run after roles.

  4. post_tasks: Run last (e.g. verification or cleanup).

  5. Handlers: Automatically flushed at the end of each of the above sections; you can force them early with the meta: flush_handlers task.

Q113.
Not all Ansible modules are inherently idempotent — how can a playbook author enforce idempotency when using modules like shell or command?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q114.
How do you create and use custom modules in Ansible?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q115.
What is a callback plugin in Ansible?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q116.
What are the different types of plugins in Ansible (callback, lookup, filter, inventory, strategy, vars) and how do they differ from modules?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q117.
What is the difference between an action plugin and a module in Ansible?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q118.
What are Ansible facts and how are they gathered, and how does fact gathering/caching work and when should you disable it?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q119.
Explain the Ansible variable precedence ladder and common pitfalls.

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q120.
When is it unsafe to bulk-set task arguments from a variable?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q121.
What are custom facts (facts.d / local facts) and how do you define them on a managed host?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q122.
What is the difference between include_role, import_role, and the roles: keyword?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q123.
How do role dependencies defined in meta/main.yml work?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q124.
How do you handle external secret lookups (e.g., HashiCorp Vault, AWS Secrets Manager), Vault IDs, and multi-vault workflows?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q125.
How do you securely manage sensitive data like passwords and API keys in Ansible playbooks without using Ansible Vault?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q126.
What is loop_control and what options does it provide (e.g., loop_var, label, pause)?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q127.
What is the difference between include_tasks and import_tasks (dynamic vs static)?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q128.
What does the flush_handlers directive do and when would you use it?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q129.
What is the 'listen' keyword in handlers and how does it enable notifying multiple handlers?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q130.
How does force_handlers change handler behavior when a play fails?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q131.
Explain delegate_to and run_once in Ansible and their purpose.

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q132.
What does delegate_facts do and how does it differ from delegate_to?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q133.
How do ANSIBLE_* environment variables interact with ansible.cfg and command-line overrides?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q134.
What are execution environments in Ansible and what problem do they solve?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q135.
What are some commonly used Jinja2 filters in Ansible such as map, select, combine, and regex_replace?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q136.
How do you write and use a custom filter plugin in Ansible?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q137.
What are the different task execution strategies in Ansible such as linear, free, and serial, and when would you use each?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q138.
What is pipelining in Ansible, and how does it improve performance?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q139.
How do you optimize Ansible playbook performance in large-scale environments using forks, pipelining, fact caching, and limiting scope?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q140.
How do you implement rolling updates in Ansible?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q141.
Explain the concept of asynchronous task execution in Ansible and how it benefits long-running or parallel tasks.

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q142.
How would you use Ansible to orchestrate a zero-downtime deployment?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q143.
What do any_errors_fatal and max_fail_percentage do, and how do they affect a play across multiple hosts?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q144.
What is throttle in Ansible and how does it limit task concurrency?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q145.
How do you integrate Ansible with external tools and platforms like GitLab CI/CD pipelines, HashiCorp Vault, or monitoring systems?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q146.
How does Ansible integrate with Kubernetes for managing clusters, deployments, and services?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q147.
How would you use Ansible to automate configuration drift detection and remediation?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q148.
How can Ansible help when migrating workloads from on-premises infrastructure to the cloud?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q149.
How does Ansible manage Windows hosts, and what is different about using WinRM instead of SSH?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q150.
What is Molecule and how is it used for testing Ansible roles?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.