0% found this document useful (0 votes)
62 views13 pages

Ansible Interview Questions and Answers-1

This document contains a collection of Ansible questions and answers, covering topics such as installation, key components, playbooks, roles, variables, modules, error handling, and best practices. It serves as a guide for users to understand and implement Ansible effectively while emphasizing the importance of testing and managing dependencies. The author disclaims responsibility for any issues arising from the use of this guide and encourages feedback for improvements.

Uploaded by

Saurabh Dube
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
62 views13 pages

Ansible Interview Questions and Answers-1

This document contains a collection of Ansible questions and answers, covering topics such as installation, key components, playbooks, roles, variables, modules, error handling, and best practices. It serves as a guide for users to understand and implement Ansible effectively while emphasizing the importance of testing and managing dependencies. The author disclaims responsibility for any issues arising from the use of this guide and encourages feedback for improvements.

Uploaded by

Saurabh Dube
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Ansible Questions and Answers

10st March 2025

Saleh Miri

Linkedin.com/in/salehmiri Salehmiri90@gmail.com

Youtube.com/salehmiri90 Github.com/salehmiri90
This document is including below titles:

General Ansible Questions


Describe a challenging Ansible project

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

Q1. What is Ansible, and how does it work?


Answer:
• Agentless Architecture: Ansible communicates with managed nodes via SSH or WinRM,
eliminating the need for additional software on target systems.
• YAML-Based Playbooks: These define automation tasks in a declarative format, specifying the
desired state of systems.
• Pre-Built Modules: Used to perform tasks like software installation or network configuration.
• Control Node and Inventory: The control node executes Ansible commands, referencing an
inventory file that lists managed nodes.
• Idempotency: Ensures tasks won’t repeat unnecessary changes.
• Scalability and Versatility: Supports diverse platforms, including cloud providers and network
devices, making it suitable for managing small to large-scale environments efficiently.

Q2. How do you install Ansible on different operating systems?


Answer:
Installing Ansible on different operating systems involves using system-specific package managers,
repositories, or tools like pip for Python environments. The method varies depending on the OS.

• 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.

Q3. What are the key components of Ansible?


Answer:
• Inventory: A list of managed hosts (servers), defined either statically in files or dynamically via
scripts, which groups systems for targeted automation tasks.
• Modules: Small programs executed on remote hosts to perform specific tasks like package
installation, file management, or service configuration. Modules are the building blocks of
Ansible automation.
• Playbooks: YAML files that define a series of tasks to achieve the desired state of systems.
Playbooks are central to Ansible’s declarative approach.
• Roles: Reusable and modular units that organize playbooks, variables, tasks, and other
components for better project management and scalability.
• Tasks: Individual actions within a playbook that invoke modules to perform specific
operations on managed nodes.

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

Q4. How do you define and use an inventory in Ansible?


Answer:
An Ansible inventory is a file or collection of files that lists managed hosts and organizes them into
groups. It's crucial for targeting systems during automation tasks.

Q5. What is a playbook in Ansible? Can you write a simple one?


Answer:
An Ansible playbook is a YAML-based file that defines automation workflows, consisting of plays
and tasks. It specifies the desired state of systems and executes tasks sequentially on managed
nodes.
---
- hosts: all
tasks:
- name: Install Apache
yum:
name: httpd
state: present

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.

• Purpose: Simplifies complex playbooks by breaking them into reusable components.


• Structure: Includes directories for tasks, variables, templates, handlers, files, and metadata.
• Usage: Roles are referenced in playbooks to execute specific tasks or configurations.
• Creation: Use ansible-galaxy init to create a role's skeleton structure.
• Reusability: Roles can be shared via repositories like Ansible Galaxy or reused across multiple
projects.
• Separation of Concerns: Encourages logical grouping of automation tasks for better
collaboration and maintainability.

Page 2 of 11
Ansible Questions and Answers

Q7. How do you use variables in Ansible?


Answer:
Variables in Ansible are used to manage system differences and make playbooks dynamic. They can
be defined in various locations, referenced using Jinja2 syntax, and follow a strict precedence
hierarchy.

• 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.

Q8. What is an Ansible module? Can you give some examples?


Answer:
An Ansible module is a small program that performs specific automation tasks on managed nodes.
Modules are the building blocks of Ansible and can handle tasks like managing files, installing
packages, configuring systems, or interacting with APIs.

• Examples of Ansible Modules:


• File Management: copy, file, fetch
• Package Management: apt, yum, dnf
• Service Management: service, systemd
• User Management: user, group
• Cloud Integration: ec2, azure_rm, gcp_compute
• Networking: ios_config, net_ping, nxos_command

Q9. How do you handle errors in Ansible playbooks?


Answer:
Error handling in Ansible playbooks allows you to manage task failures gracefully. You can use
directives like ignore_errors, failed_when, and blocks (block, rescue, always) to control error
behavior and ensure playbook execution continues or stops as needed.

• 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.

Q10. What is Ansible Galaxy, and how do you use it?


Answer:
Ansible Galaxy is a community platform for sharing, discovering, and downloading pre-built Ansible
roles and collections. It simplifies automation by providing reusable content that can be integrated
into your projects.

• Purpose: Hosts community-contributed roles and collections to accelerate automation


workflows.
• Commands:
o ansible-galaxy install: Installs roles or collections from Galaxy.
o ansible-galaxy init: Creates a new role structure.
o ansible-galaxy list: Lists installed roles or collections.
o ansible-galaxy remove: Removes installed roles or collections.
• Integration: Roles and collections from Galaxy can be used in playbooks to streamline
automation tasks.
• Customization: Allows hosting private Galaxy servers for internal use.

Q11. How do you ensure idempotence in Ansible playbooks?


Answer:
Idempotence in Ansible ensures that running a playbook multiple times results in the same system
state without making unnecessary changes. This is achieved by using modules and practices
designed to check and enforce the desired state.

• 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.

Q12. What are handlers in Ansible, and how do they work?

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.

• Triggering: Handlers are activated by tasks using the notify directive.


• Execution Timing: Run after all tasks in a play are completed, but only if notified.
• Idempotency: Execute only once per play, even if notified multiple times.
• Use Cases: Commonly used for service management (start, stop, restart, reload) after
configuration changes.
• Structure: Defined under the handlers section in playbooks or roles.
• Order of Execution: Handlers execute in the order they are defined, not in the order they are
notified.

Q13. How do you use Ansible Vault to manage secrets?


Answer:
Ansible Vault is a tool within Ansible used to encrypt and manage sensitive data like passwords, API
keys, or certificates. It ensures secrets remain secure by encrypting files or strings and decrypting
them only at runtime.

• Encryption: Use ansible-vault encrypt to secure files or ansible-vault encrypt_string for


inline variables.
• Decryption: Use ansible-vault decrypt or ansible-vault view to access encrypted content.
• Password Management: Vault passwords can be provided interactively, stored in files, or
managed using --vault-id.
• Integration with Playbooks: Encrypted files or variables can be included in playbooks using
modules like include_vars or directly referenced.
• Check Mode: Use ansible-vault list to verify encrypted files.
• Best Practices: Store encrypted secrets in version control safely and restrict access to vault
passwords.

Q14. How do you test Ansible playbooks?


Answer:
Testing Ansible playbooks involves validating syntax, simulating execution, and verifying
functionality. This ensures playbooks work as intended without causing issues in the target
environment.

• 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.

Q17. How do you use conditionals in Ansible playbooks?


Answer:
Conditionals in Ansible playbooks allow tasks to execute only when specific conditions are met,
enabling dynamic and flexible automation. The when keyword is primarily used to define these
conditions, which can be based on variables, facts, or task results.

• 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.

• Purpose: Provide real-time system information for dynamic decision-making in playbooks.


• Fact Gathering: Automatically performed at the start of playbook execution or manually
using the setup module.
• Data Format: Facts are stored in JSON format and include lists, dictionaries, and key-value
pairs.
• Customization: Custom facts can be added using the facts.d directory on managed nodes.
• Usage: Accessed via Jinja2 syntax {{ ansible_facts['key'] }} and used in tasks, conditionals, or
templates.
• Disabling Fact Gathering: Use gather_facts: no in playbooks to skip automatic fact collection
if not needed.

Q19. How do you manage dependencies in Ansible roles?


Answer:
Managing dependencies in Ansible roles ensures that prerequisite roles are executed before the
dependent role. Dependencies are defined in the meta/main.yml file of a role, and Ansible executes
them in the specified order.

• Define Dependencies: Use the dependencies section in meta/main.yml to list prerequisite


roles.
• Execution Order: Ansible runs dependencies first, recursively if needed, before executing the
dependent role.
• Variable Passing: Variables can be passed to dependencies for customization during
execution.
• Avoid Duplication: Ansible skips duplicate role executions unless explicitly allowed with
allow_duplicates: true.
• Project-Specific Dependencies: Use a requirements.yml file to manage role versions and
install them via ansible-galaxy install -r requirements.yml.
• Tagging Dependencies: Apply tags to roles and tasks for selective execution and better
control over dependencies.

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.

Q21. How do you execute tasks on a specific group of hosts in Ansible?


Answer:
To execute tasks on a specific group of hosts in Ansible, you can target groups defined in the
inventory file using the hosts field in playbooks or the --limit option in the command line.

• 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.

Q23. How do you use loops in Ansible?


Answer:
Loops in Ansible allow you to repeat tasks multiple times with different inputs, reducing redundancy
and simplifying playbooks. The loop keyword is the preferred method, but older methods like
with_items are also available.

• 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.

Q25. How do you perform rolling updates with Ansible?


Answer:
Rolling updates in Ansible involve updating a subset of hosts at a time to minimize downtime. This is
achieved using the serial keyword in playbooks, which controls the number of hosts updated
simultaneously.

• 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.

Q27. What is the use of the delegate_to keyword in Ansible?


Answer:
The delegate_to keyword in Ansible allows you to execute a specific task on a different host than the
one defined in the playbook or inventory. It is commonly used for tasks that require centralized
operations, such as downloading files, managing DNS records, or interacting with control nodes.

• 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.

Q28. How do you integrate Ansible with Jenkins for CI/CD?


Answer:
Integrating Ansible with Jenkins enables automated provisioning, configuration management,
and application deployment in a CI/CD pipeline. Jenkins acts as the orchestrator, triggering
Ansible playbooks or workflows for seamless automation.

Q29. How do you manage large inventories in Ansible?


Answer:
Managing large inventories in Ansible requires a structured approach to organize hosts, handle
dynamic environments, and ensure maintainability. This can be achieved using static and dynamic
inventory techniques, inventory directories, and tools like Ansible Tower/AWX/AAP.

Describe a challenging Ansible project


Q30. Can you describe a challenging Ansible project you've worked on and how you resolved any
issues?
Answer:
The GitHub repository at Salehmiri90-Github provides an example of CI/CD pipeline with Ansible to
automating the deployment of Zabbix Agents and Ceph Cluster Deployments.
Github Project Codes: https://github.com/salehmiri90/AnsibleOps/tree/master

Page 11 of 11

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy