Back to Blog
Interview Q&A

Top 200 Ansible Automation Interview Questions & Answers

Fortress Institute2026-04-0545 min read

Basic Questions (1-80)

Q1. What is Ansible?

Ansible is an open-source IT automation tool developed by Red Hat. It automates software provisioning, configuration management, application deployment, and orchestration. Ansible is agentless — it communicates with managed nodes over SSH (Linux) or WinRM (Windows), requiring no agent software installed on remote hosts.

Q2. What are the main features of Ansible?

Key features: agentless architecture, YAML-based Playbooks for human-readable automation, idempotent operations (running multiple times produces the same result), inventory management, extensive module library (3000+ modules), support for parallel task execution, role-based access control, and integration with CI/CD pipelines.

Q3. What is a Playbook in Ansible?

An Ansible Playbook is a YAML file defining automation workflows as a list of plays. Each play maps a set of tasks to a group of hosts. Playbooks are the primary way to describe automation policy, configuration states, and deployment sequences in a human-readable, version-controllable format.

Q4. What is an Ansible Inventory?

An Inventory is a file (INI or YAML format) listing the managed hosts and groups that Ansible targets. Hosts can be defined with IP addresses or hostnames. Dynamic inventories use scripts or plugins (AWS EC2, Azure, GCP) to generate host lists dynamically from cloud provider APIs.

Q5. What is an Ansible Module?

An Ansible Module is a discrete unit of code that performs a specific task on a managed host: installing packages (yum, apt), managing files (copy, template, file), starting services (service, systemd), managing users (user), or executing commands (command, shell). Modules ensure idempotency by checking current state before acting.

Q6. What is an Ansible Task?

A Task is a single action in a Playbook calling one module with specific parameters. Each task has a name (for logging), the module name, module arguments, optional conditionals (when), loops (loop/with_items), handlers notification, and tags for selective execution.

Q7. What is an Ansible Role?

A Role is a structured way of packaging reusable automation content. It organizes tasks, handlers, variables, files, templates, and defaults into a standardized directory structure (tasks/main.yml, handlers/main.yml, vars/main.yml, defaults/main.yml, files/, templates/). Roles promote code reuse across playbooks and projects.

Q8. What is an Ansible Handler?

A Handler is a task that runs only when notified by another task using notify. Handlers run once at the end of a play regardless of how many tasks notify them. Common use case: restarting a service (notify: Restart nginx) only when the configuration file actually changes, avoiding unnecessary restarts.

Q9. What is an Ansible Variable?

Variables in Ansible store dynamic values used across tasks and templates. They are defined in inventory files, playbooks (vars:), variable files (vars_files:), roles (defaults/main.yml, vars/main.yml), group_vars/ directories, host_vars/ directories, or passed at runtime (-e key=value).

Q10. What is the ansible.cfg file?

ansible.cfg is the Ansible configuration file defining default behavior: inventory path, remote user, private key file, SSH settings, roles path, callback plugins, privilege escalation defaults (become), and connection type. Ansible searches for it in the current directory, ~/.ansible.cfg, or /etc/ansible/ansible.cfg.

Q11. What is idempotency in Ansible?

Idempotency means running an Ansible task multiple times produces the same result as running it once, without making redundant changes. If a package is already installed, the yum module skips installation. If a file already matches the template, the template module makes no change. This makes automation safe to re-run.

Q12. What is the difference between command and shell modules?

The command module runs commands directly without invoking the shell — no shell operators (&&, |, >, $VAR) are available. The shell module invokes /bin/sh, enabling shell features (pipes, redirections, environment variables). Use command when possible (safer), shell when shell features are required.

Q13. What is the copy module in Ansible?

The copy module transfers files from the Ansible control node (or local content) to managed hosts. It supports src (source path), dest (destination path), owner, group, mode (permissions), and content (inline content). The copy module checks file content hash and skips unchanged files for idempotency.

Q14. What is the template module in Ansible?

The template module renders Jinja2-templated files and copies them to managed hosts. Templates (.j2 files) embed variable references ({{ variable }}), conditionals ({% if %}), and loops ({% for %}). This enables generating configuration files with host-specific values from a single template source.

Q15. What is Jinja2 in Ansible?

Jinja2 is the Python templating engine used by Ansible for variable interpolation in playbooks, templates, and conditionals. Jinja2 expressions ({{ }}) output values; statements ({% %}) control flow (if/for/set); comments ({# #}) add notes. Filters (| upper, | default, | json_query) transform values.

Q16. What is the yum module in Ansible?

The yum module manages RPM packages on Red Hat/CentOS/Fedora systems. state: present/latest installs packages; state: absent removes them. It also manages yum repositories (enablerepo, disablerepo). On RHEL 8+ systems, the dnf module is the preferred equivalent using DNF package manager.

Q17. What is the apt module in Ansible?

The apt module manages Debian/Ubuntu packages using the APT package manager. state: present installs; state: absent removes; state: latest updates to latest. update_cache: true refreshes the apt cache. The apt_key and apt_repository modules manage GPG keys and repository sources.

Q18. What is the service module in Ansible?

The service module manages system services: state: started/stopped/restarted/reloaded controls service state; enabled: true/false controls boot-time activation. On modern systemd systems, the systemd module is preferred for full systemd unit management including daemon_reload.

Q19. What is the user module in Ansible?

The user module manages Unix user accounts: name, state (present/absent), uid, gid, groups (list), shell, home directory, password (hashed), and comment. The group module manages Unix groups. Together they automate user lifecycle management across managed hosts consistently.

Q20. What is the file module in Ansible?

The file module sets file/directory attributes: state (file, directory, link, absent, touch, hard), owner, group, mode (permissions). state: directory creates directories (including parents with recurse: true). state: absent removes files/directories. state: link creates symbolic links.

Q21. What is the lineinfile module in Ansible?

The lineinfile module ensures a specific line is present, absent, or replaced in a file. It uses regexp to identify the target line and line to specify the desired content. Useful for modifying configuration files where only a specific setting line needs to change, not the entire file.

Q22. What is the blockinfile module in Ansible?

The blockinfile module inserts, updates, or removes a block of text surrounded by marker comments in a file. Markers identify the managed block (# BEGIN ANSIBLE MANAGED BLOCK / # END ANSIBLE MANAGED BLOCK) allowing multiple blocks in one file without conflict. Useful for inserting config sections.

Q23. What is the when condition in Ansible?

when: adds a conditional expression to a task, running it only when the expression evaluates to true. Conditions use Jinja2 expressions, Ansible facts (ansible_os_family == 'RedHat'), registered variables (result.rc == 0), and boolean operators (and, or, not). Tasks with false conditions are skipped.

Q24. What are Ansible Facts?

Facts are system information automatically gathered from managed hosts at the start of each play by the setup module. Facts include: ansible_hostname, ansible_os_family, ansible_distribution, ansible_distribution_version, ansible_architecture, ansible_interfaces, ansible_memory_mb, and IP address variables for network interfaces.

Q25. What is fact gathering in Ansible?

Fact gathering (gather_facts: true, the default) runs the setup module at play start to collect system facts. Disabling it (gather_facts: false) speeds up plays when facts are not needed. Custom facts can be deployed to /etc/ansible/facts.d/ on managed hosts and accessed via ansible_local.

Q26. What is the register directive in Ansible?

register: stores a task's output into a variable. The registered variable contains: stdout, stderr, rc (return code), stdout_lines, stderr_lines, and changed status. Used with when: to conditionally execute subsequent tasks based on the result of a previous task.

Q27. What is the loop (with_items) directive in Ansible?

loop: (or with_items: in older syntax) iterates a task over a list of items. Each iteration uses the current item as {{ item }}. With nested lists, with_nested: or loop with a product filter is used. loop also works with a list of dictionaries: {{ item.key }}, {{ item.value }}.

Q28. What is the debug module in Ansible?

The debug module prints messages and variable values to stdout during playbook execution for troubleshooting. debug: msg="{{ variable }}" prints the variable value. debug: var=variable prints the variable and its value. verbosity: 1 requires -v flag to display the message.

Q29. What is the assert module in Ansible?

The assert module verifies that conditions are true and fails the play with a custom message if they are not. assert: that: - condition1 - condition2 fail_msg: "Assertion failed" success_msg: "Passed". Used for validating pre-conditions, input validation, and post-deployment verification checks.

Q30. What is the pause module in Ansible?

The pause module pauses playbook execution for a specified duration (minutes, seconds) or prompts for manual confirmation. pause: prompt="Press Enter to continue" waits for user input, useful in deployment workflows requiring manual approval or inspection steps between automated phases.

Q31. What are group_vars and host_vars in Ansible?

group_vars/ directory contains YAML files named after inventory groups, defining variables for all hosts in that group. host_vars/ contains files named after specific hosts for host-specific variables. These directories are placed alongside the inventory file or in the playbook directory for automatic loading.

Q32. What is the Ansible Vault?

Ansible Vault encrypts sensitive data (passwords, API keys, certificates) in YAML files using AES-256 encryption. ansible-vault encrypt/decrypt/view/edit manages vault files. Encrypted variables are referenced normally in playbooks; the vault password is provided at runtime (--ask-vault-pass or --vault-password-file).

Q33. What is privilege escalation in Ansible?

Privilege escalation allows Ansible to run tasks as a different user (typically root) on managed hosts. become: true enables escalation; become_user specifies the target user (default: root); become_method specifies the method (sudo, su, pbrun, pfexec). become_password provides the sudo password.

Q34. What is the difference between become and sudo?

sudo is one of Ansible's become_method options. become is Ansible's privilege escalation framework that abstracts the underlying escalation mechanism. Other become methods include su, pfexec, doas, machinectl, and runas (Windows). become: true with the default become_method uses sudo.

Q35. What is the ansible-playbook command?

ansible-playbook runs Ansible playbooks: ansible-playbook site.yml -i inventory.ini --check (dry run) --diff (show changes) -t tags (run specific tags) --limit 'group:host' (limit hosts) -e key=value (extra variables) -v/-vvv (verbosity) --become (privilege escalation).

Q36. What is the ansible command (ad-hoc)?

The ansible command runs single module tasks ad-hoc without a playbook: ansible all -m ping (test connectivity), ansible web -m yum -a "name=httpd state=present" (install package), ansible db -m command -a "df -h" (run command). Useful for quick checks and one-off tasks.

Q37. What is the ping module in Ansible?

The ping module tests Ansible connectivity and authentication to managed hosts — it verifies that Ansible can connect via SSH and that Python is available. It does not send ICMP pings. ansible all -m ping returns pong on success, useful for initial connectivity validation.

Q38. What is the setup module in Ansible?

The setup module gathers and returns system facts (as JSON) from managed hosts: OS type, version, hostname, IP addresses, CPU count, memory, disk partitions, network interfaces, and environment variables. It runs automatically at play start (gather_facts: true) or can be called explicitly.

Q39. What is the fetch module in Ansible?

The fetch module downloads files from managed hosts to the Ansible control node. It creates a directory structure on the control node reflecting the remote host's hostname and path: fetch/hostname/path/to/file. Used for collecting log files, certificates, or configuration files from remote systems.

Q40. What is the git module in Ansible?

The git module manages Git repositories on managed hosts: cloning (repo, dest), pulling updates, checking out specific versions/branches/tags, and force-updating. Used in deployment playbooks to clone application code to servers and update to specific release tags or commit hashes.

Q41. What is the unarchive module in Ansible?

The unarchive module extracts compressed archives (.tar.gz, .zip, .tar.bz2) on managed hosts. src can be a local file (copied and extracted) or a remote URL (remote_src: true, downloaded directly on the host). The module checks if extraction is needed to maintain idempotency.

Q42. What is the get_url module in Ansible?

The get_url module downloads files from URLs to managed hosts using HTTP/HTTPS/FTP. Supports checksum validation (checksum: sha256:...), authentication, timeout, and mode settings. Idempotent — skips download if the file exists and matches the checksum. Used for downloading artifacts and packages.

Q43. What are tags in Ansible?

Tags label tasks, plays, roles, or blocks allowing selective execution. Running ansible-playbook with --tags web only executes tasks tagged web. --skip-tags skips tagged tasks. Special tags always (always runs) and never (requires explicit --tags never) provide additional control. Tags support multiple values per task.

Q44. What is a block in Ansible?

A block groups multiple tasks together for shared attributes (when, tags, become, notify) and error handling. rescue: tasks run if any block task fails (like try/catch). always: tasks run regardless of block success or failure (like finally). Blocks simplify error recovery in complex playbooks.

Q45. What is the ignore_errors directive in Ansible?

ignore_errors: true allows a playbook to continue execution even if the task fails (non-zero return code). The task result is still registered and accessible. Useful for non-critical tasks where failure is acceptable, or when checking for optional components that may not exist on all hosts.

Q46. What is failed_when in Ansible?

failed_when: overrides Ansible's default failure detection by defining a custom failure condition. Example: failed_when: result.rc != 0 and 'already exists' not in result.stderr. This prevents tasks from failing when the command output indicates an acceptable condition despite a non-zero exit code.

Q47. What is changed_when in Ansible?

changed_when: overrides Ansible's automatic changed status detection. changed_when: false marks tasks that never actually make changes (like informational commands). changed_when: result.stdout != '' marks a task as changed only when output exists. Controls handler notification and change reporting accuracy.

Q48. What is an Ansible Galaxy?

Ansible Galaxy is the official community hub for sharing and downloading Ansible Roles and Collections. ansible-galaxy install namespace.rolename downloads roles. ansible-galaxy collection install namespace.collection installs collections. requirements.yml specifies dependencies for automated installation in CI/CD pipelines.

Q49. What is an Ansible Collection?

Ansible Collections are distribution packages containing modules, plugins, roles, playbooks, and documentation under a single namespace.collection_name. Collections (e.g., community.general, ansible.builtin, amazon.aws) provide curated, versioned automation content installed via ansible-galaxy or requirements.yml.

Q50. What is the include_tasks vs import_tasks difference?

include_tasks dynamically includes a task file at runtime — included tasks are processed as the play runs, supporting loop/when for dynamic inclusion. import_tasks statically imports tasks at parse time — all tasks are pre-loaded before execution, supporting tags but not dynamic looping. import is faster; include is more flexible.

Q51. What is the include_role vs import_role difference?

import_role statically imports the role at parse time — role tasks, handlers, and variables are fully pre-processed. include_role dynamically includes the role at runtime — supports loop and when conditions. Dynamic inclusion is more flexible but has limitations with tags and pre-task/post-task awareness.

Q52. What is the delegate_to directive in Ansible?

delegate_to: hostname runs a specific task on a different host than the current play host. delegate_to: localhost is commonly used to run tasks on the Ansible control node (e.g., API calls, local file operations, AWS CLI commands) while the rest of the play targets remote hosts.

Q53. What is run_once in Ansible?

run_once: true ensures a task executes only once for the entire play — on the first host in the batch — even when running against multiple hosts. Combined with delegate_to: localhost it performs single-execution control-node tasks (API registrations, database migrations) within a multi-host play.

Q54. What is the serial directive in Ansible?

serial: controls the number of hosts processed in parallel within a play. serial: 1 applies changes host-by-host (rolling update). serial: [1, 5, 10] uses staged batches. serial: "30%" processes 30% of hosts at a time. Prevents all hosts from being updated simultaneously in production deployments.

Q55. What is the max_fail_percentage directive?

max_fail_percentage: sets the maximum percentage of hosts allowed to fail before Ansible aborts the play. max_fail_percentage: 30 allows up to 30% of hosts to fail before stopping. Used with serial updates to halt deployment if too many hosts fail, preventing cascading failures across a fleet.

Q56. What is the any_errors_fatal directive?

any_errors_fatal: true causes Ansible to immediately stop the play on all hosts if any host fails a task, regardless of serial batches. Unlike max_fail_percentage, it stops on the first failure rather than allowing a percentage. Used for critical infrastructure plays where partial failures are unacceptable.

Q57. What is the uri module in Ansible?

The uri module makes HTTP/HTTPS requests from managed hosts: method (GET, POST, PUT, DELETE), url, body, headers, status_code (expected response codes), return_content (capture response body), and validate_certs. Used for API calls, health checks, webhook triggers, and REST API interactions.

Q58. What is the wait_for module in Ansible?

The wait_for module pauses execution until a condition is met: wait_for: port=80 (port is open), state=started/stopped/present/absent/drained, timeout (max wait seconds), delay (initial pause), host, search_regex (content in file). Used to wait for services to start, ports to open, or files to appear.

Q59. What is the stat module in Ansible?

The stat module retrieves file/directory status information: exists, size, mode, owner, group, checksum, isdir, islink, inode, mtime. Registered results are used in when conditions to check file existence or attributes before performing operations like backups, migrations, or conditional configurations.

Q60. What is the find module in Ansible?

The find module searches for files matching criteria in directories: paths, patterns (glob), file_type (file, directory, link), age (older/newer than), size, recurse, and hidden. Returns a list of matched files in files variable, enabling dynamic task execution on found files.

Q61. What is the replace module in Ansible?

The replace module replaces all instances of a regexp pattern in a file with a replacement string. Unlike lineinfile (which manages single lines), replace handles multi-occurrence patterns. after/before anchors limit the replacement scope within the file. Supports backup creation before modification.

Q62. What is the cron module in Ansible?

The cron module manages crontab entries on managed hosts: name (comment identifier for idempotency), minute, hour, day, month, weekday, job (command), user, state (present/absent), and special_time (reboot, hourly, daily, weekly, monthly). Creates, modifies, or removes cron jobs reliably.

Q63. What is the mysql_db module in Ansible?

The mysql_db module (community.mysql collection) manages MySQL databases: state (present/absent/import/dump), name, login_user, login_password, login_host. The mysql_user module manages MySQL users and privileges. Used for database provisioning and schema management in deployment playbooks.

Q64. What is the docker_container module in Ansible?

The docker_container module (community.docker collection) manages Docker containers: state (started, stopped, absent, present), image, name, ports, volumes, env, network_mode, command, and restart_policy. Enables container lifecycle management within Ansible playbooks without separate Docker Compose files.

Q65. What is the AWS EC2 module in Ansible?

The amazon.aws collection provides modules for AWS: ec2_instance (launch/terminate instances), s3_object (S3 operations), rds_instance (RDS management), ec2_security_group (security group rules), iam_role (IAM roles), and route53 (DNS). Authentication uses AWS credentials via environment variables or boto3 profiles.

Q66. What is the ansible-lint tool?

ansible-lint is a command-line tool that analyzes Ansible playbooks, roles, and collections for best practices, common mistakes, and style issues. It enforces rules like: no deprecated modules, task naming, proper YAML formatting, meta file presence, and idempotency concerns. Integrates with CI/CD pipelines for quality gates.

Q67. What is ansible-doc?

ansible-doc displays documentation for Ansible modules, plugins, and roles from the command line: ansible-doc yum shows the yum module's parameters, return values, and examples. ansible-doc -l lists all available modules. Essential for offline reference without needing to open a browser.

Q68. What is the check mode (--check) in Ansible?

Check mode (--check, also called dry run) simulates playbook execution without making actual changes on managed hosts. Modules report what would change. Not all modules support check mode (modules requiring real system state for decisions may behave differently). Used for change validation before production execution.

Q69. What is the --diff flag in Ansible?

The --diff flag shows a unified diff of file changes when tasks modify files (template, copy, lineinfile). Combined with --check it previews file content changes without applying them. The diff output shows removed lines (–) and added lines (+), enabling review of configuration file modifications before deployment.

Q70. What is the Ansible Tower/AWX?

Ansible Tower (Red Hat's enterprise product) and AWX (open-source upstream) provide a web-based UI, REST API, and RBAC layer on top of Ansible. Features: visual dashboard, job scheduling, workflow templates (multi-playbook orchestration), credential management, audit logging, and notification integration with external systems.

Q71. What is an AWX Job Template?

A Job Template in AWX/Tower defines a reusable playbook execution configuration: inventory, project, playbook file, credentials, extra variables, verbosity, forks, and limits. Job Templates are executed manually, via schedule, or triggered by webhooks and workflow templates for orchestrated automation.

Q72. What is an Ansible Workflow Template?

A Workflow Template in AWX/Tower chains multiple Job Templates and inventory sources in a directed acyclic graph (DAG) with success/failure/always branches. Enables complex multi-step automation: provision infrastructure → configure servers → deploy application → run tests → notify team — conditionally branching on step outcomes.

Q73. What is inventory plugin in Ansible?

Inventory plugins dynamically generate inventory from external sources: amazon.aws.aws_ec2 (AWS), azure.azcollection.azure_rm (Azure), google.cloud.gcp_compute (GCP), vmware.vmware_rest.vcenter_vm (VMware), and kubernetes.core.k8s (Kubernetes). They replace static inventory files for cloud and dynamic environments.

Q74. What is the vars_prompt directive in Ansible?

vars_prompt: prompts the user for variable values interactively before the play runs. Supports encrypted input (private: yes hides typed characters). Used in one-off playbooks requiring user-specific values (passwords, target hostnames) without storing them in variable files.

Q75. What is the set_fact module in Ansible?

set_fact: creates or updates Ansible variables at runtime during playbook execution. Variables set with set_fact persist for the current host for the remainder of the play, making them accessible in subsequent tasks and roles. Useful for computed values, conditional overrides, and fact caching scenarios.

Q76. What is the add_host module in Ansible?

add_host: dynamically adds a host to an in-memory inventory group during playbook execution. Used when infrastructure is provisioned dynamically (ec2 instance created, add to web_servers group) enabling subsequent plays to target the newly created hosts without reloading inventory files.

Q77. What is the group_by module in Ansible?

group_by: dynamically creates new inventory groups based on facts, enabling conditional role application. group_by: key="{{ ansible_os_family }}" creates groups named Debian, RedHat, etc. Subsequent plays can target these fact-based groups with os-family-specific tasks without pre-defining the groups in inventory.

Q78. What is meta: flush_handlers in Ansible?

meta: flush_handlers immediately triggers all notified handlers at that point in the play, rather than waiting until the play end. Used when a handler must run before subsequent tasks depend on its results — e.g., restarting a service before testing its port, rather than waiting for all tasks to complete.

Q79. What is the YAML syntax for Ansible playbooks?

Ansible playbooks use YAML: files start with --- (document separator); lists use - prefix; dictionaries use key: value pairs; multiline strings use | (literal) or > (folded); true/false for booleans; indentation is significant (2-space convention). Incorrect indentation is the most common Ansible YAML error.

Q80. What is the difference between Ansible and Puppet/Chef?

Ansible is agentless (SSH-based), uses push model, YAML syntax, and is designed for simplicity and quick adoption. Puppet and Chef are agent-based (pull model), use DSL languages (Puppet DSL, Ruby/Chef DSL), and are better suited for complex, self-healing configuration management at massive scale with certificate-based authentication.

Intermediate Questions (81-150)

Q81. What is Ansible automation for CI/CD pipelines?

Ansible integrates with CI/CD tools (Jenkins, GitLab CI, GitHub Actions, Azure DevOps) as a deployment stage. Pipelines trigger ansible-playbook via ansible-runner or AWX API after build/test stages. Ansible handles artifact deployment, configuration management, service restarts, smoke tests, and rollback procedures.

Q82. What is Ansible Automation Platform (AAP)?

Red Hat Ansible Automation Platform is the enterprise suite including: Automation Controller (AWX/Tower), Automation Hub (private Galaxy), Event-Driven Ansible (EDA), Automation Analytics, and Automation Mesh. AAP provides a complete, supported automation platform for enterprise-scale Ansible deployments.

Q83. What is Event-Driven Ansible (EDA)?

Event-Driven Ansible (ansible-rulebook) enables reactive automation that responds to external events: monitoring alerts, webhooks, Kafka messages, or file changes trigger playbook execution automatically without manual intervention. Rulebooks define event sources, condition filters, and the actions (run_playbook) to take when conditions match.

Q84. What is Automation Mesh in Ansible?

Automation Mesh is a peer-to-peer communication architecture in AAP that replaces the Hub/Spoke isolation model. It allows Ansible Control Plane nodes to communicate with Execution Nodes distributed across firewalled networks, enabling automation across multi-site, hybrid, and disconnected environments without VPN tunneling.

Q85. What is ansible-runner?

ansible-runner is a Python library and command-line tool providing a stable interface for running Ansible from external systems (CI/CD, AWX/Tower). It manages Ansible process lifecycle, captures stdout/stderr in structured artifacts directories, and provides result parsing for programmatic integration.

Q86. What is the Ansible Content Navigator (ansible-navigator)?

ansible-navigator is a text-based user interface (TUI) for Ansible that replaces ansible-playbook for running automation in Execution Environments. It displays real-time playbook output, supports interactive mode for exploring results, task inspection, and plays well with container-based Execution Environments.

Q87. What is an Execution Environment (EE) in Ansible?

Execution Environments are OCI-compliant container images containing Ansible, collections, Python dependencies, and system packages bundled together. EEs ensure consistent automation execution across different systems, eliminating "works on my machine" problems. ansible-builder builds EEs; ansible-navigator runs them.

Q88. What is ansible-builder?

ansible-builder is a tool for creating Ansible Execution Environment container images. The execution-environment.yml file defines: base image, additional Python packages (requirements.txt), system packages, and Ansible collections (requirements.yml). ansible-builder generates and builds the container image using Podman/Docker.

Q89. What is the purpose of ansible-vault in CI/CD?

In CI/CD, ansible-vault protects sensitive playbook variables (database passwords, API keys). The vault password is stored in the CI/CD secret store (Jenkins credentials, GitLab CI variables, GitHub Actions secrets) and provided to ansible-playbook via --vault-password-file pointing to the secret file at runtime.

Q90. What is the Ansible callback plugin?

Callback plugins intercept Ansible events (task start, task result, play recap) and customize output or integrate with external systems. Built-in callbacks: profile_tasks (timing), timer (total runtime), mail (email on failure), slack (Slack notifications), junit (JUnit XML output for CI). Custom callbacks send results to monitoring systems.

Q91. What is the lookup plugin in Ansible?

Lookup plugins retrieve data from external sources: lookup('file', '/path/to/file') reads file content; lookup('env', 'HOME') reads environment variables; lookup('password', ...) generates passwords; lookup('pipe', 'command') runs commands; lookup('template', 'template.j2') renders templates inline.

Q92. What is the vars plugin in Ansible?

Vars plugins load additional variables from external sources beyond static files. host_group_vars (built-in) loads group_vars/host_vars. Custom vars plugins retrieve variables from Consul, AWS SSM Parameter Store, HashiCorp Vault, or databases — enabling dynamic variable injection without static files.

Q93. What is the connection plugin in Ansible?

Connection plugins define how Ansible connects to managed hosts. Built-in plugins: ssh (default for Linux), paramiko (pure Python SSH), winrm (Windows), docker (Docker exec), kubectl (Kubernetes pods), local (localhost without SSH), and community.libvirt.libvirt_lxc (LXC containers). Custom plugins support proprietary systems.

Q94. What is WinRM in Ansible?

WinRM (Windows Remote Management) is the connection method for managing Windows hosts with Ansible. Windows hosts require WinRM configured (ConfigureRemotingForAnsible.ps1 script), and the pywinrm Python library on the control node. ansible_connection: winrm, ansible_winrm_transport: ntlm/kerberos/certificate are set in inventory.

Q95. What is the win_shell module in Ansible?

The win_shell module runs PowerShell commands on Windows hosts, analogous to the shell module for Linux. win_command runs commands without PowerShell shell features. win_powershell (newer) runs full PowerShell scripts with proper variable handling and error object access.

Q96. What is the win_feature module in Ansible?

The win_feature module manages Windows Server roles and features: state (present/absent), name (WindowsFeature name), include_management_tools, include_sub_features, restart. Equivalent to Install-WindowsFeature PowerShell cmdlet, enabling automated Windows Server configuration in Ansible playbooks.

Q97. What is the purpose of Ansible roles defaults vs vars?

Role defaults/main.yml defines the lowest-priority variable values — easily overridden by inventory, playbook, and extra variables. Role vars/main.yml defines high-priority variables that override most other variable sources. Use defaults for role parameters users may customize; use vars for internal constants roles require.

Q98. What is Ansible variable precedence order?

Ansible variable precedence (lowest to highest): role defaults → inventory group_vars/all → inventory group_vars → inventory host_vars → playbook group_vars → playbook host_vars → host facts → play vars → role vars → block vars → task vars → include_vars → set_fact → extra vars (-e). Extra vars have highest precedence.

Q99. What is fact caching in Ansible?

Fact caching stores gathered facts between playbook runs, avoiding repeated fact gathering overhead. Supported backends: memory (single run), jsonfile (local files), redis, memcached, mongodb. Configured in ansible.cfg (gathering = smart, fact_caching = jsonfile, fact_caching_connection = /tmp/ansible_facts). Smart gathering skips hosts with cached facts.

Q100. What is the Ansible forks setting?

forks determines how many hosts Ansible manages in parallel (default: 5). Increasing forks (forks = 50 in ansible.cfg or -f 50) processes more hosts simultaneously, reducing total playbook execution time. Limited by control node CPU/memory and SSH connection limits. Most production environments use 10-50 forks.

Q101. What is the strategy plugin in Ansible?

Strategy plugins control how Ansible executes tasks across hosts. linear (default) runs each task on all hosts before moving to the next. free allows each host to proceed to the next task as soon as it finishes its current one — faster overall but harder to troubleshoot. host_pinned is a variation of free.

Q102. What is the Mitogen strategy plugin?

Mitogen is a third-party Ansible strategy plugin using Python's remote execution framework instead of SSH command invocation. It caches SSH connections, transfers Python code directly (bypassing SFTP), and executes tasks in a persistent Python interpreter on the remote host — providing 2-7x performance improvement over the default SSH strategy.

Q103. What is SSH pipelining in Ansible?

SSH pipelining (pipelining = True in ansible.cfg) reduces SSH operations per task by sending module code over a single SSH session rather than copying it via SFTP first. Requires requiretty to be disabled in /etc/sudoers on managed hosts. Improves playbook performance by 50%+ in typical scenarios.

Q104. What is the purpose of ControlMaster in Ansible SSH?

SSH ControlMaster multiplexes multiple SSH sessions over a single TCP connection, eliminating TCP/TLS handshake overhead for each task. Configured in ansible.cfg (ssh_args = -o ControlMaster=auto -o ControlPersist=60s). ControlMaster and pipelining together significantly reduce Ansible execution time for large inventories.

Q105. What is Ansible molecule?

Molecule is a testing framework for developing and testing Ansible roles. It creates test instances (Docker, Podman, Vagrant, EC2), runs the role, verifies the outcome with Testinfra or Ansible verifier, and destroys the instances. Molecule provides lint, syntax check, converge, idempotency, verify, and destroy lifecycle phases.

Q106. What is Testinfra in Ansible testing?

Testinfra is a Python testing library used with Molecule for verifying role outcomes. Tests assert that files exist (host.file('/etc/nginx.conf').exists), services are running (host.service('nginx').is_running), packages are installed (host.package('nginx').is_installed), and ports are listening. Tests run after Molecule's converge phase.

Q107. What is the Ansible verifier in Molecule?

Molecule's ansible verifier (verify.yml) uses Ansible tasks (assert, stat, command, uri) to verify the role converged correctly, without requiring additional Python testing libraries. The ansible verifier is simpler for Ansible practitioners than Testinfra, using familiar YAML syntax for post-convergence verification.

Q108. What is the purpose of the ansible-test tool?

ansible-test is a CLI tool for testing Ansible collections: unit tests (unittest-based, mocked), integration tests (run against real targets), sanity tests (PEP8, import checks, YAML syntax, documentation validation), and coverage reporting. Required for submitting collections to Ansible Galaxy and Red Hat Automation Hub certification.

Q109. What is Ansible content for Kubernetes?

The kubernetes.core collection provides modules for Kubernetes: k8s (apply/delete manifests), k8s_info (get resources), helm (manage Helm releases), k8s_exec (exec into pods), k8s_log (retrieve pod logs). Authentication via kubeconfig, service accounts, or bearer tokens. Enables Kubernetes resource management from Ansible playbooks.

Q110. What is the purpose of ansible-playbook --limit?

--limit restricts playbook execution to a subset of inventory: --limit webservers (group), --limit host1 (single host), --limit 'webservers:!db01' (group minus specific host), --limit 'webservers:dbservers' (union). Enables targeted execution without modifying inventory files for partial rollouts or targeted fixes.

Q111. What is the purpose of Ansible retry files?

When a playbook fails, Ansible creates a .retry file listing hostnames that failed. Re-running with --limit @playbook.retry retargets only the failed hosts, enabling partial retries without reprocessing already successful hosts. Useful for recovering from transient failures in large-fleet deployments.

Q112. What is the Ansible pull mode?

ansible-pull inverts Ansible's push model: managed nodes pull playbooks from a Git repository and run them locally (ansible-playbook on the node itself). Used for bootstrapping, self-service automation, and environments where the control node can't reach managed hosts (firewalled, mobile endpoints). Scheduled via cron for continuous compliance.

Q113. What is the purpose of Ansible for configuration drift detection?

Running ansible-playbook --check periodically detects configuration drift — differences between the desired state defined in playbooks and the actual host state. The check report shows which tasks would make changes (changed tasks indicate drift). Integrates with monitoring systems to alert on drift before running remediation plays.

Q114. What is the omit placeholder in Ansible?

The omit placeholder ({{ omit }}) tells Ansible to skip a module parameter entirely when the value is undefined. Example: owner: "{{ file_owner | default(omit) }}" — if file_owner is undefined, the owner parameter is not passed to the module, using the module's own default. Prevents "undefined variable" errors with optional parameters.

Q115. What is the Jinja2 default filter in Ansible?

The default filter provides fallback values for undefined variables: {{ variable | default('fallback') }} returns 'fallback' if variable is undefined. default(omit) omits the parameter if undefined. default('value', true) returns 'value' for both undefined AND falsy (None, False, 0, '') variable values.

Q116. What is the selectattr filter in Ansible?

selectattr('attribute', 'test', value) filters a list of dictionaries keeping only items where the attribute passes the test: users | selectattr('active', 'equalto', true) | list returns only active users. map(attribute='name') extracts a single attribute from the filtered list.

Q117. What is the json_query filter in Ansible?

json_query uses JMESPath expressions to query complex JSON/dict structures: variable | json_query('[].name') extracts all name fields; variable | json_query("[?type=='web'].ip") filters and extracts. Requires the jmespath Python library. Useful for processing complex API responses and nested facts.

Q118. What is the combine filter in Ansible?

combine({}) merges dictionaries: dict1 | combine(dict2) produces a merged dict with dict2 values overriding dict1 for matching keys. combine(recursive=true) deep-merges nested dictionaries. Used for merging default variables with override variables in role default patterns.

Q119. What is the zip filter in Ansible?

zip(*lists) pairs elements from multiple lists: [1,2,3] | zip(['a','b','c']) produces [[1,'a'],[2,'b'],[3,'c']]. zip_longest fills shorter lists with a fill value. Used in loops where parallel list items need to be processed together as pairs.

Q120. What is the product filter in Ansible?

The product filter generates the Cartesian product of iterables, used with with_nested for nested loops. loop: "{{ ['a','b'] | product([1,2]) | list }}" produces [('a',1),('a',2),('b',1),('b',2)]. Useful for configuring all combinations of environments × services × hosts.

Q121. What is the purpose of the meta/main.yml in Ansible roles?

meta/main.yml defines role metadata: author, description, company, license, min_ansible_version, platforms (OS compatibility), and dependencies (list of roles to execute before this role). Galaxy metadata enables searchable role discovery; dependencies automatically include prerequisite roles when this role is used.

Q122. What is the purpose of ansible-galaxy role init?

ansible-galaxy role init rolename creates the standard role directory skeleton: tasks/, handlers/, vars/, defaults/, files/, templates/, tests/, meta/, library/, filter_plugins/. This scaffolding ensures the role follows Ansible's expected structure for Galaxy publication, Molecule testing, and consistent team conventions.

Q123. What is a custom module in Ansible?

Custom Ansible modules are Python scripts (or modules in any language returning JSON) placed in library/ directory adjacent to the playbook or role. They follow the AnsibleModule API (argument_spec, supports_check_mode, exit_json, fail_json) and are called like built-in modules in tasks. Used for system-specific operations without existing modules.

Q124. What is the AnsibleModule class in module development?

AnsibleModule (from ansible.module_utils.basic) is the base class for Ansible module development. It handles argument parsing (argument_spec), type coercion, required/mutually exclusive parameter validation, check mode support, and provides exit_json()/fail_json() methods for structured module output to Ansible's engine.

Q125. What is the module_utils directory in Ansible?

module_utils/ contains shared Python utility libraries imported by multiple custom modules. Placing common code (authentication helpers, API clients, data parsing) in module_utils/ avoids duplication across modules. Ansible automatically makes module_utils/ available to modules via import without PYTHONPATH configuration.

Q126. What is the purpose of custom filter plugins?

Custom filter plugins extend Jinja2's available filters for use in Ansible templates and playbooks. Placed in filter_plugins/ directory, they are Python functions registered via FilterModule class. Custom filters encapsulate complex data transformations (parsing, encoding, formatting) as reusable Jinja2 filter names.

Q127. What is the purpose of action plugins in Ansible?

Action plugins run on the Ansible control node before/after the normal module execution on the remote host. Built-in action plugins: template (renders on control node, copies result), copy (processes src on control node), script (transfers and executes). Custom action plugins enable hybrid control-node + remote-host operations.

Q128. What is the Ansible network automation capability?

Ansible automates network devices (Cisco IOS/NXOS, Juniper Junos, Arista EOS, F5 BIG-IP, Palo Alto) via collections: cisco.ios, juniper.device, arista.eos. Network modules use cli_command, cli_config, or vendor APIs. Connection plugins (network_cli, netconf, httpapi) enable SSH/NETCONF/REST API connectivity to devices.

Q129. What is the cisco.ios collection for Ansible?

cisco.ios collection provides modules for Cisco IOS/IOS-XE devices: ios_config (push CLI configuration), ios_command (run exec commands), ios_facts (gather device facts), ios_interface (manage interfaces), ios_bgp (BGP configuration). Connects via network_cli over SSH with IOS terminal handling.

Q130. What is NETCONF in Ansible network automation?

NETCONF is a network management protocol using XML data models (YANG schemas) over SSH. Ansible's netconf connection plugin enables structured configuration management for devices supporting NETCONF. netconf_config applies XML configuration; netconf_get retrieves operational data from NETCONF-capable devices.

Q131. What is the purpose of Ansible for cloud provisioning?

Ansible provisions cloud infrastructure using provider collections (amazon.aws, azure.azcollection, google.cloud, community.vmware). Playbooks define infrastructure as code: create VPCs, subnets, security groups, EC2 instances, RDS databases, load balancers, and DNS records — providing a consistent IaC approach without learning Terraform DSL.

Q132. What is Ansible vs Terraform for infrastructure?

Terraform excels at infrastructure provisioning with state management (tracking created resources) and dependency resolution. Ansible excels at configuration management, application deployment, and procedural automation. Many teams use Terraform to provision infrastructure and Ansible to configure it — complementary rather than competing tools.

Q133. What is the purpose of Ansible for container orchestration?

Ansible orchestrates containers using the community.docker and kubernetes.core collections: building images (docker_image), managing containers (docker_container), deploying Helm charts (helm), applying Kubernetes manifests (k8s), and managing namespaces. Provides a unified automation interface for mixed container environments.

Q134. What is the Ansible AWX REST API?

AWX provides a REST API (browseable at /api/v2/) for all operations: launching job templates (POST /api/v2/job_templates/{id}/launch/), retrieving job status, creating inventory, managing credentials, and triggering workflows. Enables CI/CD pipelines to integrate with AWX programmatically via curl, requests library, or awxkit.

Q135. What is awxkit?

awxkit is the official Python library and CLI (awx) for interacting with the AWX REST API. It provides Python object models for AWX resources and CLI commands (awx job_templates launch, awx jobs get) for scripting AWX interactions from CI/CD pipelines and automation workflows without raw HTTP calls.

Q136. What is Ansible for security hardening?

Ansible automates OS security hardening via community roles (devsec.hardening collection): OS hardening (CIS benchmark compliance), SSH hardening (key algorithms, ciphers, timeouts), firewall configuration (firewalld/iptables), SELinux/AppArmor policy enforcement, and audit logging setup — ensuring consistent baseline security across fleets.

Q137. What is the purpose of OpenSCAP integration with Ansible?

OpenSCAP scans systems against SCAP security profiles (DISA STIG, CIS). The SSG (SCAP Security Guide) generates Ansible remediation playbooks from scan results. Running the generated playbook automatically remediates failed controls, enabling compliance automation without manual interpretation of SCAP findings.

Q138. What is Ansible Lint rules and custom rules?

ansible-lint enforces rules from built-in rule sets (name[casing], no-changed-when, yaml[truthy], risky-shell-pipe). Custom rules are Python classes (AnsibleLintRule subclass) placed in the rules directory, enabling organization-specific conventions like required task tags, banned module usage, or naming pattern enforcement.

Q139. What is the purpose of no_log in Ansible?

no_log: true suppresses task output from appearing in Ansible logs, preventing sensitive data (passwords, tokens, private keys) from being exposed in verbose output, log files, or CI/CD artifact stores. Applied per-task or globally in playbook. Also use no_log on register variables containing sensitive API responses.

Q140. What is vault-encrypted variables inline?

Vault-encrypted variables can be embedded inline in plain-text variable files using !vault: prefix: password: !vault | $ANSIBLE_VAULT;1.1;AES256 ... allows mixing encrypted and plaintext variables in the same file, encrypting only sensitive values rather than encrypting entire files.

Q141. What is the purpose of multiple vault passwords?

Ansible supports multiple vault IDs (--vault-id label@password-file) enabling different passwords for different secret classifications: --vault-id prod@prod_pass --vault-id dev@dev_pass. Vault-encrypted content can specify which vault ID decrypts it, enabling separation of secrets by environment or classification level.

Q142. What is the purpose of ansible_become_password?

ansible_become_password provides the sudo password for privilege escalation on hosts requiring password-authenticated sudo. Set in host_vars/ or group_vars/ encrypted with ansible-vault. Alternatively, --ask-become-pass prompts interactively. Passwordless sudo is preferred in production for automation; password sudo for shared environments.

Q143. What is the purpose of the raw module in Ansible?

The raw module executes raw SSH commands on remote hosts without requiring Python to be installed — Ansible's only module that bypasses Python. Used for bootstrapping managed hosts to install Python before running other modules: raw: dnf install -y python3. Also useful for systems where Python cannot be installed.

Q144. What is the script module in Ansible?

The script module transfers a local script to the managed host and executes it. The script runs with the remote user's environment. Arguments are passed as parameters. The creates/removes arguments make it idempotent — the script runs only if the creates file doesn't exist or removes file does exist.

Q145. What is the expect module in Ansible?

The expect module handles interactive command-line programs by providing input in response to expected output patterns. It uses Python's pexpect library: command (program to run), responses (dict mapping expect patterns to responses), timeout. Used for legacy scripts requiring interactive input that can't be automated otherwise.

Q146. What is the purpose of Ansible in GitOps workflows?

In GitOps, Ansible playbooks are stored in Git as the source of truth for system configuration. Pipeline automation (GitHub Actions, Argo CD) detects commits and triggers ansible-playbook execution via AWX webhooks. Git history provides change audit trail; PR reviews provide change approval; tags trigger specific deployment playbooks.

Q147. What is the purpose of pipelining vs SFTP in Ansible?

By default, Ansible transfers module code to remote hosts via SFTP (a separate SSH subsystem connection). Pipelining sends the module code over the existing SSH control connection stdin, eliminating the SFTP step. This reduces connection overhead from 2 SSH operations to 1 per task, improving performance significantly.

Q148. What is Ansible for zero-downtime deployments?

Zero-downtime deployments use serial: and load balancer integration: remove host from LB → update host → verify → add back to LB. Ansible playbooks automate HAProxy/NGINX/AWS ALB target group manipulation (disable_backend, deregister_targets) bracketing the deployment tasks for graceful rolling updates.

Q149. What is the purpose of pre_tasks and post_tasks in Ansible?

pre_tasks: runs before roles in a play — for prerequisite validation, load balancer removal, or fact setup. post_tasks: runs after roles — for service verification, load balancer re-registration, or notification. Both sections support handlers. They give play-level lifecycle hooks around the main role execution.

Q150. What is the purpose of the Ansible ecosystem integration with Packer?

HashiCorp Packer uses Ansible as a provisioner to build machine images (AMIs, VMware templates, Docker images). Packer launches a base instance, runs ansible-playbook to configure and harden it, and captures the resulting image. Pre-baked images reduce deployment time compared to configuring instances at launch.

Advanced Questions (151-200)

Q151. What is the Ansible content developer experience with Collections?

Collection development workflow: scaffold with ansible-galaxy collection init namespace.name, implement modules in plugins/modules/, add integration tests in tests/integration/, run sanity/unit/integration tests with ansible-test, publish to Galaxy with ansible-galaxy collection publish. Collections are the modern packaging unit replacing standalone roles.

Q152. What is the FQCN (Fully Qualified Collection Name) in Ansible?

FQCN is the namespace.collection.module format for unambiguous module references: ansible.builtin.copy, community.general.ini_file, amazon.aws.ec2_instance. Using FQCNs prevents module name conflicts between collections and is required when using modules outside ansible.builtin in modern collection-based automation.

Q153. What is the purpose of galaxy.yml in Ansible Collections?

galaxy.yml is the collection manifest defining: namespace, name, version, description, license, authors, dependencies (other collections), repository, documentation, issues, and homepage. ansible-galaxy collection build reads galaxy.yml to create the distributable .tar.gz package for Galaxy/Automation Hub publication.

Q154. What is the purpose of the ansible-test sanity command?

ansible-test sanity validates collection code against Ansible's quality standards: PEP8 (pylint, flake8), import validation, module documentation format (DOCUMENTATION/EXAMPLES/RETURN strings), argument_spec completeness, shebang lines, and GPL license headers. Failing sanity tests block Galaxy certification submission.

Q155. What is the purpose of integration tests in ansible-test?

ansible-test integration runs integration tests against real target environments (containers or cloud) defined in tests/integration/targets/. Each target has tasks/ (setup, test, teardown) and aliases (defines the test environment type). Integration tests validate actual module behavior against live systems, not mocked environments.

Q156. What is the purpose of the always_run directive (force_handlers)?

force_handlers: true (play-level) causes handlers to run even if a task fails during the play, preventing system inconsistency from partially applied configurations. Without force_handlers, a failed task skips all remaining tasks and handlers, potentially leaving services in an inconsistent state.

Q157. What is the purpose of the throttle directive in Ansible?

throttle: limits the number of hosts executing a task concurrently, independent of the global forks setting. throttle: 2 allows at most 2 hosts to run a task simultaneously even if 20 hosts are in the play with 20 forks. Used for tasks that must be rate-limited (license-limited software activations, API rate limits).

Q158. What is the purpose of the timeout directive in tasks?

timeout: (seconds) sets a per-task execution time limit. If the task exceeds the timeout on a host, it fails with a timeout error. Used for long-running commands with unknown completion time to prevent playbook hangs. Different from wait_for (which waits for a condition) — timeout limits a task's maximum duration.

Q159. What is the purpose of async tasks in Ansible?

async: (seconds) + poll: (seconds) runs a task asynchronously — the task starts on the host and Ansible polls for completion. poll: 0 fires and forgets (task runs independently). async_status module checks job completion. Used for long-running tasks (database migrations, large file operations) to avoid SSH timeout issues.

Q160. What is the purpose of the listen directive in handlers?

listen: 'event name' allows handlers to subscribe to named events rather than being notified by handler name. Multiple handlers can listen to the same event; a single notify triggers all listeners. This decouples tasks from specific handler names, enabling more flexible handler composition in shared roles.

Q161. What is the purpose of the include_vars module?

include_vars dynamically loads variable files at task runtime based on conditions: include_vars: "{{ ansible_os_family }}.yml" loads the OS-specific variable file. Supports dir parameter to load all .yml files from a directory. Useful for loading environment-specific or platform-specific variable files conditionally.

Q162. What is the purpose of the Ansible inventory graph?

ansible-inventory --graph visualizes the inventory hierarchy as a tree: group relationships, host assignments, and variable inheritance. ansible-inventory --list outputs the full inventory in JSON format for debugging and integration with external tools. Both commands help understand complex dynamic inventory structures.

Q163. What is the purpose of constructed inventory plugin?

The constructed inventory plugin (ansible.builtin.constructed) builds groups and sets variables based on Jinja2 expressions applied to existing inventory facts or variables. keyed_groups creates groups from variable values; compose sets new host variables. Powerful for creating semantic groups from cloud provider tags or existing host attributes.

Q164. What is the Ansible ad-hoc module for gathering specific facts?

ansible all -m setup -a 'filter=ansible_*ip*' gathers only facts matching the filter pattern, reducing output. ansible all -m setup -a 'gather_subset=network' collects only network facts. ansible all -m ansible.builtin.gather_facts args='gather_subset: ['!all', 'network']' with subset control from playbook context.

Q165. What is the purpose of the shell module with executable parameter?

shell: cmd executable=/bin/bash runs the command using a specific shell interpreter rather than the default /bin/sh. Used when commands require bash-specific features (arrays, process substitution, bashisms) not available in POSIX sh. Also applies to specifying Python, Ruby, or other interpreters for scripts.

Q166. What is the purpose of Ansible playbook idempotency testing?

Idempotency testing (Molecule's idempotency phase) runs the playbook twice and asserts all tasks report "ok" (not "changed") on the second run. A task reporting "changed" on second run indicates non-idempotent behavior: the module doesn't check existing state before making changes.

Q167. What is the purpose of the meta/argument_specs.yml file?

argument_specs.yml (Ansible 2.11+) defines typed parameter specifications for roles, similar to module argument_spec. Parameters have type, description, required, default, and choices. ansible-playbook validates role parameters against argument_specs at runtime, providing early error detection for role API contract violations.

Q168. What is the purpose of Ansible for Continuous Compliance?

Continuous Compliance uses scheduled AWX job templates running playbooks in check mode against the full fleet. Check mode results feed into reporting systems: Splunk, Elasticsearch, custom dashboards. Drift detection reports which hosts and controls are non-compliant, triggering remediation workflows or approval-gated fix runs.

Q169. What is the purpose of Ansible with HashiCorp Vault integration?

HashiCorp Vault stores secrets that Ansible retrieves at runtime using the community.hashi_vault collection: hashi_vault lookup plugin (lookup('community.hashi_vault.hashi_vault', 'secret=secret/data/prod/db:password')) fetches secrets dynamically without storing them in Ansible Vault files, enabling centralized, auditable secret management.

Q170. What is the purpose of Ansible for immutable infrastructure?

Immutable infrastructure replaces servers rather than updating them. Ansible builds new images (with Packer), provisions new instances, validates health, shifts traffic, and terminates old instances. The deploy-and-replace pattern eliminates configuration drift by never mutating long-lived servers — all configuration is baked into fresh images.

Q171. What is the purpose of Ansible callback plugins for monitoring?

Custom callback plugins send real-time playbook execution data to monitoring systems: Datadog events (playbook started/completed), Grafana annotations (deployment markers on dashboards), JIRA ticket updates, Elasticsearch document indexing of task results. Callback plugins provide deployment observability without modifying playbooks.

Q172. What is the purpose of the Ansible interpreter discovery?

Interpreter discovery (ansible_python_interpreter: auto) automatically selects the correct Python interpreter on managed hosts (Python 3 on modern systems, Python 2 on legacy). The interpreter_python_fallback list defines the search order. Prevents playbook failures on hosts with non-standard Python installation paths.

Q173. What is the purpose of the become_exe setting?

become_exe specifies the full path to the privilege escalation executable when it's not in PATH: become_exe: /usr/local/bin/sudo. Used on non-standard systems where sudo is in a non-default location, or for using alternative executables like doas, pfexec, or custom wrapper scripts for privilege escalation.

Q174. What is the purpose of the become_flags setting?

become_flags passes additional flags to the privilege escalation command: become_flags: '-i' (sudo -i for login shell), become_flags: '-H' (reset HOME to target user). Useful when sudo configuration requires specific flags or when the target user's environment must be fully loaded for tasks to function correctly.

Q175. What is the purpose of Ansible for database automation?

Ansible automates database lifecycle: provisioning (RDS instances), schema migrations (mysql_query, postgresql_query), user management (mysql_user, postgresql_user), backup scheduling (cron + mysqldump), performance parameter configuration (my.cnf template), and database dump/restore operations for disaster recovery testing.

Q176. What is the purpose of Ansible for certificate management?

The community.crypto collection automates PKI: openssl_privatekey (generate keys), openssl_csr (certificate signing requests), openssl_certificate (sign certificates), acme_certificate (Let's Encrypt via ACME), and certificate_complete_chain (verify cert chains). Automates certificate lifecycle from generation through renewal and deployment.

Q177. What is the purpose of the Ansible persistent connection?

Persistent connections (persistent_command_timeout, persistent_connect_timeout) maintain a single SSH connection across multiple tasks rather than reconnecting per-task. Critical for network device modules (cisco.ios, arista.eos) where establishing CLI sessions has significant overhead. Configured per connection type in ansible.cfg.

Q178. What is the purpose of Ansible for SAP automation?

The community.sap_libs collection automates SAP HANA and SAP S/4HANA operations: hana_instance (manage HANA instances), sapcontrol (SAP system start/stop), sap_hana_install (HANA installation), sap_system_replication (HSR configuration). Used for SAP landscape provisioning, system refresh, and backup automation.

Q179. What is the purpose of the ansible-playbook profiling?

profile_tasks callback plugin (enabled in ansible.cfg: callback_whitelist = profile_tasks) reports execution time per task at play completion, identifying slow tasks for optimization. profile_roles summarizes time by role. Long-running tasks are candidates for async execution, caching, or optimized module alternatives.

Q180. What is the purpose of Ansible Testing with pytest?

pytest with the pytest-ansible plugin enables Python unit tests for Ansible modules: mock ansible.module_utils.basic.AnsibleModule, call run_module() with args dict, assert exit_json() calls match expected results. Unit tests run quickly on the local JVM without requiring remote hosts.

Q181. What is the purpose of the Ansible internal module documentation format?

Ansible modules document themselves via DOCUMENTATION (YAML string describing parameters), EXAMPLES (YAML showing usage), and RETURN (YAML describing return values) Python string constants. ansible-doc parses these strings; Galaxy auto-generates HTML documentation. Proper documentation is required for Galaxy certification.

Q182. What is the purpose of the check_point collection in Ansible?

The check_point.mgmt collection manages Check Point firewalls via the Check Point Management API: cp_mgmt_host (host objects), cp_mgmt_service_tcp (service objects), cp_mgmt_access_rule (security policy rules), and publish/install_policy modules. Enables security policy automation as code without GUI-based policy management.

Q183. What is the purpose of the ansible.netcommon collection?

ansible.netcommon provides shared network automation modules and plugins: net_get/net_put (file transfer), network_resource (generic resource management), cli_parse (parse CLI output with TextFSM/TTP/XML), and connection plugins (network_cli, netconf, httpapi) used by vendor-specific collections as their foundation.

Q184. What is TextFSM parsing in Ansible network automation?

TextFSM templates define regex patterns for parsing structured data from unstructured CLI command output. The cli_parse module applies TextFSM templates to command output (show version, show interfaces) converting text output to structured dictionaries for use in subsequent tasks and conditional logic.

Q185. What is the purpose of NAPALM with Ansible?

NAPALM (Network Automation and Programmability Abstraction Layer with Multivendor support) provides a unified Python API for multi-vendor network device management. The napalm collection wraps NAPALM for Ansible, enabling configuration management, validation, and compliance checking across diverse network vendors with consistent module interfaces.

Q186. What is the purpose of the ansible.posix collection?

ansible.posix provides POSIX-specific modules not in ansible.builtin: mount (manage /etc/fstab and mounted filesystems), synchronize (rsync wrapper), seboolean (SELinux boolean), selinux (SELinux state), firewalld (firewalld rules), acl (POSIX ACLs), and patch (apply unified diff patches to files).

Q187. What is the purpose of Molecule scenario configuration?

Molecule scenarios (molecule/scenario_name/molecule.yml) define the test environment: driver (Docker, Podman, EC2, Vagrant), platforms (container/instance specifications), provisioner (ansible, with lint and playbook settings), verifier (ansible or testinfra), and lifecycle (cleanup, create, destroy commands). Multiple scenarios test different OS versions or configurations.

Q188. What is the purpose of Ansible for PaaS automation?

Ansible automates PaaS platform management: OpenShift/OKD (redhat.openshift collection), Cloud Foundry (community.general.cf_* modules), Heroku deployments (heroku CLI integration), and AWS Elastic Beanstalk (amazon.aws.beanstalk modules). Enables declarative management of PaaS applications and environments alongside infrastructure automation.

Q189. What is the purpose of Ansible for edge computing automation?

Edge computing with Ansible deploys automation to distributed edge devices (IoT gateways, retail kiosks, industrial controllers) using ansible-pull (devices pull playbooks from Git), minimal Execution Environments for constrained environments, and Event-Driven Ansible for reactive automation triggered by edge sensor events or alerts.

Q190. What is the purpose of Ansible AAP subscription management?

Red Hat Ansible Automation Platform subscriptions (managed_nodes count) are managed through the Red Hat Customer Portal and reflected in AAP's license view. Subscription Watch reports managed node counts. Organizations track unique managed hosts to ensure compliance with subscription entitlements and forecast growth needs.

Q191. What is the purpose of Ansible for Linux patching?

Ansible automates OS patching: yum/dnf update with security: true (security patches only), reboot module (controlled restart with post-reboot wait), reboot_timeout, pre/post patch hooks (load balancer manipulation, backup creation), and patch reporting. Enables coordinated rolling patch windows across hundreds of servers simultaneously.

Q192. What is the purpose of the reboot module in Ansible?

The reboot module reboots a managed host and waits for it to come back online before proceeding. Parameters: msg (shutdown message), pre_reboot_delay, post_reboot_delay, reboot_timeout, test_command (verifies host is operational post-reboot). Replaces manual reboot + wait_for_connection task combinations.

Q193. What is the purpose of wait_for_connection in Ansible?

wait_for_connection pauses playbook execution until the managed host becomes reachable via SSH again after a reboot or network disruption. Parameters: delay (initial wait), sleep (poll interval), timeout (max wait). Combined with reboot module or after intentional network changes to avoid premature task execution failure.

Q194. What is the purpose of Ansible for application configuration templates?

Ansible templates generate application configuration files (nginx.conf, application.properties, haproxy.cfg) from Jinja2 templates with host-specific variables (IPs, ports, resource limits) injected at deployment time. Templates version-control configuration logic separately from values, enabling consistent multi-environment config management.

Q195. What is the purpose of the Ansible playbook --start-at-task flag?

--start-at-task="task name" begins playbook execution from the named task rather than the beginning. Useful for resuming failed playbooks after fixing an issue without re-running already-completed tasks. Note: pre-task variable setup and handlers may not have run, so use cautiously in stateful playbooks.

Q196. What is the purpose of Ansible for log management?

Ansible automates log management: configuring rsyslog/journald forwarding rules (template), installing and configuring Filebeat/Fluentd (role-based), rotating logs (logrotate configuration via template), setting log retention policies, and ensuring log aggregation agents are running and shipping to centralized SIEM/ELK systems.

Q197. What is the purpose of the ansible-inventory --host command?

ansible-inventory --host hostname outputs all variables associated with a specific host from the inventory (host_vars, group_vars, dynamic inventory computed vars). Invaluable for debugging why a host received unexpected variable values, verifying variable precedence, and understanding effective variable state before playbook execution.

Q198. What is the purpose of Ansible for service mesh configuration?

Ansible configures service mesh sidecars (Istio, Linkerd, Consul Connect): injecting sidecar annotations, configuring mTLS policies, managing traffic routing rules (VirtualService, DestinationRule via kubernetes.core.k8s), and deploying service mesh control plane components with Helm. Enables declarative service mesh management as IaC.

Q199. What is the purpose of Ansible for monitoring setup?

Ansible deploys and configures monitoring stacks: Prometheus (configuration templates, alerting rules), Node Exporter (service deployment), Grafana (dashboard provisioning via API), Alertmanager (routing configuration), and SNMP exporters. Enables reproducible monitoring infrastructure deployment across environments with a single playbook run.

Q200. What are career paths after mastering Ansible Automation?

Careers include Automation Engineer, DevOps Engineer, Site Reliability Engineer (SRE), Platform Engineer, Infrastructure Engineer, Cloud Automation Architect, Network Automation Engineer, Security Automation Engineer, Ansible Content Maintainer (Red Hat), and Principal DevOps Architect at enterprises adopting Ansible at scale.

Chat with us
📞 Call
DemoWhatsApp