Ansible Interview Questions and Answers-1
Ansible Interview Questions and Answers-1
Saleh Miri
Linkedin.com/in/salehmiri Salehmiri90@gmail.com
Youtube.com/salehmiri90 Github.com/salehmiri90
This document is including below titles:
Disclaimer
Please note that this document is intended as a guide, not a reference, for creating a standby system.
The author is not accountable for any losses or damage resulting from the application of this article.
There's no assurance that the advice provided is error-free. It is recommended to use this guide at
your own risk and conduct thorough testing in your specific environment.
If you identify any inaccuracies in the information presented, please reach out to me for corrections.
Your input is appreciated for continual improvement.
Ansible Questions and Answers
General Ansible Questions
• Linux Distributions: Use dnf, yum, or apt package managers for RHEL, CentOS, Fedora,
Debian, and Ubuntu.
• For Arch Linux, use pacman: Install from official repositories or enable EPEL if required.
• Windows: Use Windows Subsystem for Linux (WSL) to install a Linux distribution like Ubuntu
and then install Ansible within it.
• Alternatively, use tools like Cygwin to emulate a Unix-like environment.
• macOS: Use Homebrew to install Ansible with the brew install ansible command.
• Python Environments: Install Ansible using pip for flexibility and control over the version.
Page 1 of 11
Ansible Questions and Answers
• Variables: Dynamic placeholders used in playbooks to make configurations flexible and
adaptable across different systems.
• Templates: Jinja2-based files with placeholders that are dynamically populated during
playbook execution to generate configuration files or scripts.
• Handlers: Special tasks triggered by events (e.g., restarting a service after a change) at the
end of a playbook run.
• Facts: System information gathered by Ansible (e.g., OS, hardware) to make decisions
dynamically during playbook execution
Q6. What are roles in Ansible, and how do you use them?
Answer:
Ansible roles are modular units used to organize and reuse automation tasks efficiently. They group
variables, tasks, handlers, templates, and other components into a standard directory structure,
promoting code reusability and easier management.
Page 2 of 11
Ansible Questions and Answers
• Definition Locations: Variables can be defined in playbooks, inventory files, roles, reusable
files, or passed as command-line arguments.
• Variable Types: Includes simple variables, lists, dictionaries, and registered variables (captured
task outputs).
• Referencing Variables: Use Jinja2 syntax {{ variable_name }} to reference variables in tasks or
templates.
• Precedence: Variables have a strict precedence order; command-line variables --extra-vars
take the highest priority.
• Naming Rules: Variable names must start with a letter or underscore and can include letters,
numbers, and underscores.
• Dynamic Variables: Registered variables capture task outputs for use in subsequent tasks.
• Default Behavior: Ansible stops execution on task failure unless configured otherwise.
• Ignore Errors: Use ignore_errors: yes to continue execution even if a task fails.
• Conditional Failure: Use failed_when to define custom failure conditions for tasks.
Page 3 of 11
Ansible Questions and Answers
• Error Blocks: Use block, rescue, and always for structured error handling, similar to try-catch-
finally in programming.
• Register and Validate: Register task results and use conditions (when) to handle errors
dynamically.
• Fail Module: Explicitly fail a playbook with a custom message using the fail module.
• Use Idempotent Modules: Most Ansible modules (e.g., file, package, service) are inherently
idempotent and only make changes if required.
• Avoid Non-Idempotent Modules: Be cautious with modules like command or shell, as they
do not inherently check the system state.
• Set Desired States: Specify states like present, absent, or started to ensure the system
matches the defined configuration.
• Conditional Logic: Use when conditions or failed_when to enforce idempotent behavior
dynamically.
• Test with Check Mode: Run playbooks with --check to preview changes without applying
them, ensuring idempotence.
• Validate Inputs: Ensure input parameters are consistent and match the desired state for all
tasks.
Page 4 of 11
Ansible Questions and Answers
Answer:
Handlers in Ansible are special tasks that execute only when triggered by the notify directive. They
are typically used for actions like restarting services and run at the end of a play, ensuring
idempotency and efficiency.
• Syntax Check: Use ansible-playbook --syntax-check to validate YAML syntax and detect
errors.
• Dry Run (Check Mode): Use --check to simulate playbook execution without making
changes.
• Diff Mode: Use --diff to preview file changes during execution.
Page 5 of 11
Ansible Questions and Answers
Q15. What strategies would you use to scale Jenkins?
Answer:
Ansible tags are metadata attached to tasks, blocks, roles, or plays in playbooks, allowing selective
execution or skipping of specific components during runtime. They provide flexibility and control
over playbook execution, enabling targeted debugging and efficient management of complex
automation workflows.
• Purpose: Enable selective execution or skipping of tasks, roles, or plays using the --tags and -
-skip-tags command-line options.
• Assignment: Tags can be assigned to individual tasks, blocks, roles, or entire plays.
• Special Tags: Ansible reserves special tags like always, never, tagged, untagged, and all for
specific behaviors.
• Tag Inheritance: Tags defined at higher levels (e.g., play, block) are inherited by child tasks
unless overridden.
• Use Cases: Useful for debugging, reusing components across different scenarios, and
managing complex playbooks efficiently.
• Flexibility: Supports multiple tags per task, allowing for granular control over execution.
Q16. Can you explain the difference between ansible and ansible-playbook commands?
Answer:
The ansible and ansible-playbook commands serve different purposes in Ansible. The ansible
command is used for ad-hoc tasks, while the ansible-playbook command is used to execute
structured playbooks containing multiple tasks.
• ansible Command:
o Executes single ad-hoc tasks directly on managed hosts.
o Useful for quick actions like checking connectivity or running one-off commands.
o Does not require a playbook.
• ansible-playbook Command:
o Executes YAML-based playbooks that define structured automation workflows.
o Used for complex, multi-step automation tasks across multiple hosts.
o Requires a playbook file as input.
• when Keyword: Specifies conditions for task execution using boolean expressions.
• Variable-Based Conditions: Use variables defined in playbooks or inventory to control task
execution.
Page 6 of 11
Ansible Questions and Answers
• Fact-Based Conditions: Leverage Ansible facts (e.g., OS type, hostname) to tailor tasks to
system-specific attributes.
• Registered Variables: Use the register directive to store task results and reference them in
subsequent conditions.
• Logical Operators: Combine multiple conditions using and, or, and not for complex logic.
• Loops with Conditions: Combine loops and conditionals to handle iterative tasks dynamically.
Q18. What are facts in Ansible, and how do you gather them?
Answer:
Ansible facts are system-specific data collected from managed nodes, such as IP addresses, OS
details, and hardware information. These facts are gathered automatically by the setup module
during playbook execution and stored in the ansible_facts variable for use in tasks, conditionals, or
templates.
Page 7 of 11
Ansible Questions and Answers
Q20. What are the differences between Ansible and other configuration management tools like Puppet
or Chef?
Answer:
Ansible, Puppet, and Chef are popular configuration management tools with distinct architectures,
learning curves, and use cases. While Ansible focuses on simplicity and ease of use, Puppet and Chef
provide more advanced features for managing complex environments.
• Architecture:
o Ansible: Agentless, uses SSH or WinRM for communication.
o Puppet & Chef: Agent-based, requiring agents installed on managed nodes.
• Ease of Use:
o Ansible: Easiest to use with YAML-based playbooks and no strong programming
knowledge required.
o Puppet & Chef: Steeper learning curve due to their domain-specific languages (DSL).
• Configuration Management:
o Ansible: Decentralized approach; focuses on task orchestration and automation.
o Puppet & Chef: Centralized approach; offer advanced features like version control
and dependency management.
• Scalability:
o All three tools are scalable, but Puppet has a proven track record in managing large-
scale infrastructures.
• Community and Ecosystem:
o Ansible: Strong community support with extensive documentation and pre-built
modules.
o Puppet & Chef: Active communities but slightly smaller module libraries compared to
Ansible.
• Use Cases:
o Ansible: Ideal for smaller teams or simpler environments.
o Puppet & Chef: Better suited for enterprises with complex configurations and larger
deployments.
• Inventory Groups: Define groups of hosts in the inventory file and specify the group name in
the hosts field of a playbook.
• Command-Line Targeting: Use the --limit option with ansible-playbook to restrict execution
to a specific group or host.
• Dynamic Delegation: Use delegate_to to execute specific tasks on different hosts or groups
dynamically within a playbook.
Page 8 of 11
Ansible Questions and Answers
Q22. What is the purpose of the become directive in Ansible?
Answer:
The become directive in Ansible is used for privilege escalation, allowing tasks to run with elevated
permissions or as a different user. It is essential for executing commands that require root or specific
user privileges on managed nodes.
• Purpose: Enables privilege escalation to perform tasks requiring higher permissions (e.g.,
root).
• Default Behavior: Tasks run as the connecting user unless become is enabled.
• Directives:
o become: Activates privilege escalation when set to true.
o become_user: Specifies the user to switch to (default is root).
o become_method: Defines the method for escalation (e.g., sudo, su).
o become_flags: Adds specific flags for the escalation method.
• Scope: Can be applied globally at the play level or individually per task.
• Security: Supports password prompts (--ask-become-pass) and secure handling of
credentials.
• loop Keyword: Recommended for most use cases; supports lists, dictionaries, and more.
• Legacy Syntax: Older directives like with_items, with_dict, and with_sequence is still valid
but less commonly used.
• Iterating Over Data:
o Lists: Use loop to iterate over simple lists.
o Dictionaries: Use dict2items or dictsort filters with loop.
o Ranges: Use the range() function for numeric sequences.
• Indexing: Access loop indices using loop.index, loop.index0, or loop.first/last.
• Conditionals in Loops: Combine loops with the when directive for conditional execution.
• Advanced Features:
o Nested Loops: Use nested data structures or combine loops with filters like zip.
o Loop Control: Use pause, break, or custom logic to control loop behavior.
Q24. Can you explain the use of the notify keyword in Ansible?
Answer:
The notify keyword in Ansible is used to trigger handlers when a task results in a change. Handlers
are special tasks that execute only when notified, typically for actions like restarting services or
reloading configurations.
Page 9 of 11
Ansible Questions and Answers
• Purpose: Links tasks to handlers, ensuring handlers execute only when necessary (e.g., after a
configuration change).
• Syntax: Add notify in a task and reference the handler by name.
• Execution Timing: Handlers run at the end of a play unless explicitly forced with meta:
flush_handlers.
• Multiple Notifications: A task can notify multiple handlers, and handlers execute only once
per play, even if notified multiple times.
• Order of Execution: Handlers execute in the order they are defined, not the order they are
notified.
• Dynamic Use: Supports loops and conditional execution but triggers all handlers if any loop
iteration causes a change.
• Best Practices:
o Use descriptive names for handlers.
o Group related handlers with the listen keyword for better modularity.
• Use the serial Keyword: Specify the number of hosts to update at once.
• Batch Updates: Gradually increase batch sizes for more efficient updates.
• Integration with Load Balancers: Remove servers from load balancers during updates to
ensure zero downtime.
• Testing and Monitoring: Test updates in staging environments and monitor for issues.
• Automation Tools: Use tools like Ansible Tower for better orchestration and visibility.
Q26. How do you handle multiple environments (development, staging, production) in Ansible?
Answer:
Managing multiple environments (development, staging, production) in Ansible involves organizing
inventories, variables, and configurations to ensure flexibility and maintainability. This is typically
achieved using separate inventory directories, environment-specific variables, and configuration files.
• Separate Inventories: Create distinct inventory files or directories (dev, stage, prod) for each
environment.
• Environment-Specific Variables: Use group_vars and host_vars directories within each
environment to define variables specific to that stage.
• Dynamic Selection: Use the -i flag with ansible-playbook to specify the inventory for the
desired environment.
• Configuration File Management: Customize ansible.cfg to set a default environment or use
the ANSIBLE_CONFIG environment variable for flexibility.
Page 10 of 11
Ansible Questions and Answers
• Cross-Environment Variables: Store shared variables in a central file and link them across
environments using symbolic links or include statements.
• Testing Tools: Use tools like Molecule for testing playbooks in isolated environments before
applying changes to production.
• Purpose: Redirects task execution to a specific host, such as the control node or a designated
server.
• Syntax: Use delegate_to: <host> to specify the target host for the task.
• Use Cases:
o Centralized operations like downloading packages or updating DNS records.
o Running tasks on a control node (localhost) or a dedicated server.
o Handling tasks requiring specific resources or permissions on another host.
• Limitations: Can only delegate tasks to one host at a time. Use loops for multiple hosts if
needed.
• Best Practices:
o Use run_once to prevent redundant execution across inventory hosts.
o Delegate sensitive tasks (e.g., certificate management) to trusted servers for security.
Page 11 of 11