Skip to content

Ansible

← Back to all decks

171 cards — 🟢 27 easy | 🟡 128 medium | 🔴 16 hard

🟢 Easy (27)

1. What is an Ansible "inventory"?

Show answer A file that defines the managed nodes and their groups.

2. What is Ansible Galaxy?

Show answer Ansible Galaxy is a community repository for Ansible roles. It allows you to share and download roles written by others (via ansible-galaxy command).

3. What is Molecule? How does it works?

Show answer It's used to rapidly develop and test Ansible roles. Molecule can be used to test Ansible roles against a variety of Linux distros at the same time. This testing ability helps instill confidence in the automation today and as time goes on while a role is maintained.

4. What is an Ansible playbook?

Show answer A playbook is a YAML file containing one or more "plays", which map a set of tasks to a group of hosts. It defines what tasks to run on which hosts (and in what order) to automate configuration or deployment.

5. What is Ansible and how does it work?

Show answer Ansible is an open-source IT automation tool for configuration management, provisioning, and deployment. It's agentless – the control node connects over SSH/WinRM to managed nodes and executes "modules" (tasks) to bring systems to a desired state.

6. What are Ansible "playbooks"?

Show answer YAML scripts that declare the desired state of a system.

7. How do you run an Ansible playbook on a specific group of hosts?

Show answer By using the -l (limit) flag or by specifying hosts in the playbook. For example: ansible-playbook site.yml -l webservers would run the playbook only on hosts in the "webservers" group.

8. What language are Ansible playbooks written in?

Show answer YAML (Yet Another Markup Language), a human-readable data serialization format.

9. How does Ansible connect to managed nodes?

Show answer It typically uses SSH for Linux and WinRM for Windows.

10. How do you pass variables to Ansible at runtime?

Show answer You can use the -e flag (extra vars) on the command line, e.g., ansible-playbook play.yml -e "var1=value1 var2=value2".

11. What is a task in Ansible?

Show answer A task is the smallest unit of action in a playbook, typically calling an Ansible module with specific arguments (e.g., a task to install a package or copy a file).

12. How do you execute a single ad-hoc Ansible command?

Show answer Using the ansible command. For example: ansible all -m ping will run the "ping" module on all hosts in the inventory (useful for quick tasks or to test connectivity).

13. What is the difference between an Ansible playbook and a role?

Show answer A playbook is a YAML file that defines automation tasks to run on hosts.
A role is a structured way to organize and reuse playbook content.

Playbook:
- Entry point for Ansible execution
- Defines which hosts to target
- Contains plays with tasks, handlers, variables
- Can be a single file or include others

Role:
- Standardized directory structure
- Reusable, self-contained automation unit
- Automatically loads files from specific directories
- Can be shared via Ansible Galaxy

14. What is "Ansible Vault"?

Show answer A tool for encrypting sensitive data like passwords within playbooks.

15. What is a "Managed Node"?

Show answer A target device or server managed by Ansible.

16. What is a "strategy" in Ansible? What is the default strategy?

Show answer A strategy in Ansible describes how Ansible will execute the different tasks on the hosts. By default Ansible is using the "Linear strategy" which defines that each task will run on all hosts before proceeding to the next task.

17. What is the Ansible inventory?

Show answer The inventory is a list of managed hosts (and groups of hosts) that Ansible operates on. It can be a static INI/JSON/YAML inventory file or dynamic inventory script, defining hostnames, groups, and connection info.

18. What is an inventory file and how do you define one?

Show answer An inventory file defines hosts and/or groups of hosts on which Ansible tasks executed upon.

An example of inventory file:

```
192.168.1.2
192.168.1.3
192.168.1.4

[web_servers]
190.40.2.20
190.40.2.21
190.40.2.22
```

19. What is a dynamic inventory file? When you would use one?

Show answer A dynamic inventory file tracks hosts from one or more sources like cloud providers and CMDB systems.

You should use one when using external sources and especially when the hosts in your environment are being automatically
spun up and shut down, without you tracking every change in these sources. projects/knowledge/interview/ansible/008-what-is-a-dynamic-inventory-file-when-you-would-us.txt

20. What are Ansible "tags"?

Show answer Labels used to selectively run or skip specific tasks.

21. What are Ansible "modules"?

Show answer Reusable units of code that perform specific tasks on nodes.

22. What is "Ansible Tower" or "AWX"?

Show answer A web-based interface for managing Ansible at scale.

23. What's your experience with Ansible?

Show answer I've used Ansible heavily for server provisioning, patching, switch configuration, and enforcing consistency across large server fleets. I write clean, modular roles, use inventories effectively, and rely on Jinja2 templating for dynamic configs. I've automated PXE/bootstrap workflows and built idempotent playbooks for both servers and network gear.

24. What are Ansible "templates"?

Show answer Files using Jinja2 syntax to generate dynamic configurations.

25. What are Ansible "facts"?

Show answer Dynamic system information gathered during execution.

26. What is the "Control Node"?

Show answer The machine where Ansible is installed and commands are run.

27. What are Ansible "roles"?

Show answer Organizational units that group related tasks and variables.

🟡 Medium (128)

1. File '/tmp/exercise' includes the following content

Show answer ```
- name: Change saiyans levels
lineinfile:
dest: /tmp/exercise
regexp: "{{ item.regexp }}"
line: "{{ item.line }}"
with_items:
- { regexp: '^Vegeta', line: 'Vegeta = 250' }
- { regexp: '^Trunks', line: 'Trunks = 40' }
...
```

2. Explain the use of the -vvv option when running Ansible commands.

Show answer The -vvv option is used to enable maximum verbosity when running Ansible commands. It produces highly detailed output, including information about each task and the status of module execution, aiding in debugging.

3. What steps would you take to debug an issue with Ansible Container?

Show answer Debug by:
* Reviewing Ansible Container logs.
* Checking container runtime logs.
* Inspecting container build outputs.
* Using the --debug option for detailed debugging information.

4. Explain the concept of Ansible Facts in a Windows environment.

Show answer Ansible Facts in a Windows environment provide information about the target system, such as hardware details, IP addresses, and installed software. Ansible gathers these facts during playbook execution, and they can be used in tasks or templates.

5. What are Ansible Modules?

Show answer Ansible Modules are standalone scripts or programs that Ansible executes to perform specific tasks on managed nodes. Modules handle tasks such as package installation, file manipulation, and service management.

6. The value of a certain variable you use is the string "True". You would like the value to be a boolean. How would you cast it?

Show answer `{{ some_string_var | bool }}`

7. How do you handle sensitive information like passwords in Ansible?

Show answer Sensitive information is managed using Ansible Vault to encrypt and secure data. Vault-encrypted files or strings can be included in playbooks, and passwords can be provided at runtime using various methods, such as prompting or external tools.

8. What is the purpose of an Ansible Playbook?

Show answer An Ansible Playbook is a YAML file containing organized instructions (plays) for configuring and managing systems. Playbooks define tasks, roles, and dependencies, providing a structured way to automate complex tasks.

9. What is the purpose of the "gather_facts" task in Ansible?

Show answer The gather_facts task collects system information (facts) from managed nodes. Facts are then available as variables in the playbook. It is often used at the beginning of playbooks to gather information about the target environment.

10. How do you troubleshoot failed jobs in Ansible Tower?

Show answer Troubleshoot by:
* Examining job details and logs in the Ansible Tower UI.
* Reviewing playbook output for error messages.
* Checking inventory, credentials, and playbooks for misconfigurations.
* Analyzing job status and error codes.

11. Explain the role of the ansible_ssh_common_args variable in connection settings.

Show answer ansible_ssh_common_args is used to pass additional SSH connection parameters globally. It's helpful for setting common options like custom SSH keys or connection timeouts across multiple hosts.

12. What are some best practices for writing clean and maintainable Ansible code?

Show answer Best practices include:
* Organizing playbooks with clear structure and naming conventions.
* Using roles to modularize and reuse code.
* Documenting tasks and variables.
* Employing version control.
* Avoiding hardcoded values and using variables.
* Ensuring idempotence in tasks.

13. How does Ansible use scripts for dynamic inventory?

Show answer Ansible executes external scripts, typically written in Python or any executable language, to fetch dynamic inventory information. These scripts should output JSON-formatted data describing hosts and groups.

14. Explain how you can use the "ansible-doc" command to get help on a module.

Show answer The ansible-doc command provides documentation for Ansible modules. To get help for a specific module, use:
```bash
ansible-doc
```
It displays module documentation, including parameters, examples, and usage.

15. Explain the use of Ansible roles in network automation.

Show answer Ansible roles in network automation help organize and modularize tasks. Roles can encapsulate configurations, templates, and tasks specific to network devices, making it easier to reuse and share automation code.

16. What are Ansible handlers and when should you use them?

Show answer Handlers are special tasks that only run when notified by other tasks.
They're typically used for actions that should happen once after multiple
changes, like restarting a service after config updates.

How they work:
1. Tasks notify handlers when they make changes
2. Handlers run at the end of the play (by default)
3. Each handler runs only once, even if notified multiple times

17. How can you troubleshoot issues related to network modules in Ansible?

Show answer Troubleshoot by:
* Checking module documentation for device compatibility.
* Verifying device connectivity.
* Examining module-specific logs and output.
* Using debug modules to inspect variables and data.

18. Explain the concept of Ansible Ad-Hoc commands.

Show answer Ad-Hoc commands are one-line commands used for quick tasks without creating playbooks. For example, ansible all -m ping checks connectivity to all nodes.

19. What are some best practices for effective debugging and troubleshooting with Ansible?

Show answer Best practices include:
* Using the debug module for variable inspection.
* Enabling verbose mode with -vvv for detailed output.
* Breaking down playbooks into smaller tasks for targeted debugging.
* Leveraging Ansible facts for dynamic information.

20. What strategies are you familiar with in Ansible?

Show answer - Linear: the default strategy in Ansible. Run each task on all hosts before proceeding.
- Free: For each host, run all the tasks until the end of the play as soon as possible
- Debug: Run tasks in an interactive way

21. How does Ansible ensure idempotence?

Show answer Ansible ensures idempotence by executing tasks only if the desired state is different from the current state. Tasks are designed to be repeatable without causing unintended changes, ensuring consistency in configurations.

22. How do you install and configure Ansible Tower?

Show answer Ansible Tower is installed by following the installation guide provided by Red Hat. It involves downloading the installer, running the installation playbook, and configuring settings. Tower settings are configured using the web interface after installation.

23. What kind of automation you wouldn't do with Ansible and why?

Show answer While it's possible to provision resources with Ansible, some prefer to use tools that follow immutable infrastructure paradigm.
Ansible doesn't save state by default. So a task that creates 5 instances for example, when executed again will create additional 5 instances (unless
additional check is implemented or explicit names are provided) while other tools might check if 5 instances exist. If only 4 exist (by checking the state file for example), one additional instance will be created to reach the end goal of 5 instances.

24. How do you use Ansible Galaxy to download and install roles?

Show answer Ansible Galaxy is used to share and download roles. To install a role from Galaxy, use the ansible-galaxy command:
```bash
ansible-galaxy install author_name.role_name
```

25. Explain the purpose of the --diff option in Ansible playbooks.

Show answer The --diff option shows the differences between the current and desired state of files being managed by Ansible. It's useful for understanding changes made during playbook execution.

26. How do you install Ansible on a Linux system?

Show answer On a Linux system, Ansible can be installed using package managers:
* For Red Hat-based systems: sudo yum install ansible
* For Debian-based systems: sudo apt-get install ansible

27. Explain the difference between Ansible Playbook and Ansible Role.

Show answer An Ansible Playbook is a collection of plays, each specifying tasks to execute. A role, on the other hand, is a reusable and shareable collection of variables, tasks, handlers, and other Ansible artifacts, organized in a predefined directory structure.

28. Explain Ansible Handlers and their use.

Show answer Handlers are tasks that only run when notified by other tasks. They are often used to restart services or perform specific actions triggered by changes. Handlers are defined in the handlers section and notified using the notify directive.

29. When the value '2017'' will be used in this case: {{ lookup('env', 'BEST_YEAR') | default('2017', true) }}?

Show answer when the environment variable 'BEST_YEAR' is empty or false.

30. What the serial keyword is used for?

Show answer It's used to specify the number (or percentage) of hosts to run the full play on, before moving to next number of hosts in the group.

For example:
```
- name: Some play
hosts: databases
serial: 4
```

If your group has 8 hosts. It will run the whole play on 4 hosts and then the same play on another 4 hosts.

31. Explain the use of the "ec2.py" script for AWS dynamic inventory.

Show answer The "ec2.py" script is a dynamic inventory script for AWS in Ansible. It queries AWS API to dynamically generate inventory information, including EC2 instances and their attributes. It enables dynamic and automatic inclusion of AWS resources in Ansible playbooks.

32. What is Ansible Tower Surveys, and how do they work?

Show answer Ansible Tower Surveys are forms that prompt users for input when launching job templates. They allow dynamic input, making playbook runs customizable. Users provide values for survey questions, influencing the behavior of the playbook.

33. How do you list all modules and how can you see details on a specific module?

Show answer 1. Ansible online docs
2. `ansible-doc -l` for list of modules and `ansible-doc [module_name]` for detailed information on a specific module

34. How do you approach debugging in a large-scale Ansible environment?

Show answer Approach debugging in a large-scale environment by:
* Utilizing centralized logging for aggregated information.
* Implementing consistent playbook and role structures.
* Employing version control for playbooks.
* Ensuring proper documentation for team collaboration.

35. How do you manage secrets in Ansible?

Show answer Never inline plaintext secrets. Options:

**Ansible Vault**:
```bash
ansible-vault create secrets.yml
ansible-vault edit secrets.yml
ansible-playbook --ask-vault-pass playbook.yml
```
Good for: Smaller teams, simple needs.

**External secret managers**:
* HashiCorp Vault (`hashi_vault` lookup)
* AWS Secrets Manager
* Azure Key Vault
* CyberArk, etc.

Good for: Enterprise, dynamic secrets, audit requirements.

**Best practices**:
* Separate vault files per environment
* Use vault IDs for multiple passwords
* CI/CD: vault password from secure variable, never committed
* Rotate secrets regularly

36. True or False? By default, Ansible will execute all the tasks in play on a single host before proceeding to the next host

Show answer False. Ansible will execute a single task on all hosts before moving to the next task in a play. As for today, it uses 5 forks by default.
This behavior is described as "strategy" in Ansible and it's configurable.

37. How does Ansible differ from other configuration management tools?

Show answer Ansible is agentless, relying on SSH for communication, making it easy to deploy. It uses YAML for human-readable playbooks, emphasizing simplicity. Ansible also supports multi-tier orchestration and provides a large collection of modules.

38. Explain how to use the --check option for running Ansible in check mode.

Show answer The --check option runs Ansible in check mode, simulating playbook execution without making changes. It's used to preview potential changes and identify issues without impacting the target systems.

39. How do you define variables in Ansible Playbooks?

Show answer Variables in Ansible Playbooks can be defined in various ways, including:
* Inline: {{ variable_name }} within tasks.
* In a separate YAML file and included using vars_files.
* In the vars section of a playbook.

40. Explain the difference between tasks, handlers, and defaults in an Ansible Role.

Show answer * Tasks: Contain the main work to be done. Defined in the tasks directory.
* Handlers: Define actions to be taken based on notifications. Defined in the handlers directory.
* Defaults: Contain default variables for the role. Defined in the defaults directory.

41. How does Ansible support network automation?

Show answer Ansible supports network automation by providing modules for configuring network devices. It can automate tasks like updating device configurations, managing VLANs, and deploying changes across a network infrastructure.

42. How do you run only a specific part of a playbook?

Show answer Use the --tags and --skip-tags options with the ansible-playbook command.
For example:
* Run specific tags: ansible-playbook playbook.yml --tags "tag_name"
* Skip specific tags: ansible-playbook playbook.yml --skip-tags "tag_name"

43. How do you set breakpoints or pause execution within an Ansible role for debugging?

Show answer Use the pause module to set breakpoints within roles. Example:
```yaml
- name: Pause for debugging
pause:
minutes: 30
```

44. Describe each of the following components in Ansible, including the relationship between them:

Show answer Task – a call to a specific Ansible module
Module – the actual unit of code executed by Ansible on your own host or a remote host. Modules are indexed by category (database, file, network, …) and also referred to as task plugins.

Inventory – An inventory file defines hosts and/or groups of hosts on which Ansible tasks executed upon. The inventory file can be in one of many formats, depending on the inventory plugins you have. The most common formats are INI and YAML.

Play – One or more tasks executed on a given host(s)

45. What information is available in the output when using the --check option?

Show answer The output includes information about tasks that would be changed, added, or removed if the playbook were run normally. It helps identify what actions Ansible would take without actually applying them.

46. What is Ansible Vault?

Show answer A feature that allows you to keep sensitive data (passwords, keys) encrypted in your playbooks or variable files. You can encrypt/decrypt these files with a password and run playbooks that prompt for the vault password.

47. What are some common pitfalls in Ansible, and how can they be avoided?

Show answer Common pitfalls include unhandled errors, inefficient playbook structures, and lack of idempotence. They can be avoided by:
* Proper error handling.
* Structuring playbooks for clarity.
* Ensuring tasks are idempotent.
* Regularly testing playbooks in non-production environments.

48. How do you use the --list-tasks option to view tasks in an execution plan?

Show answer The --list-tasks option displays a list of tasks without executing them. Example:
```bash
ansible-playbook playbook.yml --list-tasks
```

49. What is the "template" module used for?

Show answer The template module is used to copy template files to remote nodes. It allows the use of variables and conditionals in files, making it useful for generating configuration files dynamically.

50. Explain the purpose of the "copy" module in Ansible.

Show answer The copy module is used to copy files from the Ansible controller to remote nodes. It can also set file permissions and ownership during the copy operation.

51. Give examples of commonly used Ansible Modules.

Show answer * yum Module: Manages packages on Red Hat-based systems.
* apt Module: Manages packages on Debian-based systems.
* copy Module: Copies files to remote nodes.
* service Module: Manages services on the system.
* shell Module: Executes shell commands on the remote node.

52. Why is shell in Ansible dangerous?

Show answer The `shell` and `command` modules should be last resort:

**Breaks idempotence**: Shell commands run every time unless you add complex `creates`/`removes` or `when` conditions.

**Hides failures**: Exit codes aren't always meaningful. Silent failures corrupt state.

**Non-portable**: Shell commands vary across distros, versions, shells.

**Hard to test**: No structured output to validate.

**Example - bad**:
```yaml
- shell: useradd myuser
```

**Example - good**:
```yaml
- user:
name: myuser
state: present
```

The module handles idempotence, cross-platform differences, and returns structured results.

53. How do you set up passwordless SSH for Ansible?

Show answer Generate SSH keys using ssh-keygen on the Ansible controller, and copy the public key (~/.ssh/id_rsa.pub) to the ~/.ssh/authorized_keys file on managed nodes.

54. How can you troubleshoot SSH connection issues with Ansible?

Show answer Troubleshoot SSH issues by checking:
* SSH key permissions.
* User permissions on the target system.
* Connectivity between the Ansible controller and target.
* SSH configuration on the target system.
* Security groups or firewalls blocking SSH traffic.

55. Explain the use of the "hosts" directive in a playbook.

Show answer The hosts directive in a playbook specifies the target hosts or groups where the playbook tasks should be executed. It can be a single host, a group of hosts, or the special group "all" for all hosts.

56. What would be the result of the following play?

Show answer ```
---
- name: Print information about my host
hosts: localhost
gather_facts: 'no'
tasks:
- name: Print hostname
debug:
msg: "It's me, {{ ansible_hostname }}"
```

When given a written code, always inspect it thoroughly. If your answer is “this will fail” then you are right. We are using a fact (ansible_hostname), which is a gathered piece of information from the host we are running on. But in this case, we disabled facts gathering (gather_facts: no) so the variable would be undefined which will result in failure.

57. Explain the role of Ansible Tower in a CI/CD pipeline.

Show answer Ansible Tower plays a crucial role in CI/CD by providing a centralized platform for orchestrating and managing automation tasks. It integrates with version control systems, triggers playbooks based on events, and allows for the creation of workflows that automate deployment and testing processes.

58. What are specific challenges you might face when using Ansible for network automation?

Show answer Challenges include:
* Vendor-specific syntax and module support.
* Managing device state changes.
* Handling varied device responses.
* Ensuring network reliability for automation tasks.

59. What is an Ansible Role, and how is it structured?

Show answer An Ansible Role is a collection of tasks, variables, templates, and other Ansible artifacts organized in a predefined directory structure. The structure typically includes directories like tasks, handlers, templates, and defaults.

60. How can you use the --limit option to limit playbook execution to specific hosts for debugging?

Show answer The --limit option restricts playbook execution to specific hosts. Example:
```bash
ansible-playbook playbook.yml --limit=hostname
```

61. What does it mean for an Ansible module to be "idempotent"?

Show answer Idempotence means running the module multiple times yields the same result – the module only makes changes if the target state isn't already achieved. Most Ansible modules are designed to be idempotent (so you can run playbooks repeatedly without causing unintended changes).

62. How to find out the data type of a certain variable in one of the playbooks?

Show answer {{ some_var | type_debug }}

63. If the value of certain variable is 1, you would like to use the value "one", otherwise, use "two". How would you do it?

Show answer `{{ (certain_variable == 1) | ternary("one", "two") }}`

64. True or False? Ansible uses declarative style to describe the expected end state

Show answer False. It uses a procedural style.

65. How do you enable verbose mode for Ansible playbooks?

Show answer Verbose mode for Ansible playbooks can be enabled using the -v, -vv, or -vvv options with the ansible-playbook command. It increases the verbosity of output, providing more details during playbook execution.

66. What is "idempotency" in Ansible?

Show answer Ensuring that applying a configuration multiple times has the same result.

67. What steps would you take to debug an issue within an Ansible role?

Show answer Steps include:
* Adding debug tasks to print variable values.
* Using the --start-at-task option to isolate problematic tasks.
* Setting breakpoints with pause or fail for interactive debugging.

68. How do you perform a dry run of an Ansible playbook to see what changes would be made?

Show answer Use the --check option for a dry run. Example:
```bash
ansible-playbook playbook.yml --check
```

69. What is Ansible Networking, and how is it different from traditional Ansible?

Show answer Ansible Networking is an extension of Ansible designed for network automation. It includes modules tailored for network devices, supporting tasks like configuration management and device provisioning. While traditional Ansible can be used for network automation, Ansible Networking provides specialized modules and features.

70. How can you test and validate a dynamic inventory script?

Show answer Test the script by running it manually and examining output. Validate by checking if it produces JSON-formatted data with required host information.

71. True or False? Ansible follows the mutable infrastructure paradigm

Show answer True. In immutable infrastructure approach, you'll replace infrastructure instead of modifying it.
Ansible rather follows the mutable infrastructure paradigm where it allows you to change the configuration of different components, but this approach is not perfect and has its own disadvantages like "configuration drift" where different components may reach different state for different reasons.

72. How do you structure a good playbook or role?

Show answer Small, predictable roles. Defaults for variables, handlers for restarts, and clear separation of tasks, files, and templates. Idempotency first. Fail fast with clear messages. Reusability over cleverness.

73. How Ansible is different from other automation tools? (e.g. Chef, Puppet, etc.)

Show answer Ansible is:

* Agentless
* Minimal run requirements (Python & SSH) and simple to use
* Default mode is "push" (it supports also pull)
* Focus on simpleness and ease-of-use

74. What is the syntax for an Ansible Playbook?

Show answer Ansible Playbooks use YAML syntax. Example:
```yaml
---
- name: Install and start Apache
hosts: webserver
tasks:
- name: Install Apache
yum:
name: httpd
state: present
- name: Start Apache
service:
name: httpd
state: started
```

75. Explain the role of Ansible Facts in playbooks and how to debug them.

Show answer Ansible Facts provide information about target systems. Debug them by printing facts with debug tasks or using the -vvv option for increased verbosity.

76. How can you print debug messages within an Ansible playbook?

Show answer Use the debug module within Ansible playbooks to print debug messages. Example:
```
- name: Print debug message
debug:
msg: "This is a debug message."
```

77. What is a dynamic inventory in Ansible?

Show answer A dynamic inventory in Ansible is an external script or program that generates inventory information dynamically. It allows Ansible to discover and manage nodes on-the-fly, adapting to changes in infrastructure.

78. Why Use Ansible Collections?

Show answer - Modular and reusable components
- Simplifies management of custom and third-party modules
- Provides a standardized way to distribute automation content
- Helps in version control and dependency management

79. What is an Ansible "handler"?

Show answer A task triggered by another task that only runs if notified.

80. How do you use the "shell" module in Ansible?

Show answer The shell module is used to execute shell commands on remote nodes. Example:
```yaml
- name: Run a shell command
shell: echo "Hello, World!"
```

81. Explain the importance of version control with Ansible playbooks.

Show answer Version control is crucial for tracking changes, collaborating with teams, and ensuring reproducibility. It allows rollbacks to previous versions, collaboration among team members, and proper management of code changes over time.

82. How do you print the values of variables in Ansible playbooks for debugging purposes?

Show answer Use the debug module to print variable values. Example:
```yaml
- name: Print variable value
debug:
var: variable_name
```

83. How do you create and manage inventories in Ansible Tower?

Show answer Inventories in Ansible Tower can be managed through the web interface. You can create and organize inventories, define variables, and configure sources such as static files, dynamic scripts, or cloud providers. Tower also supports syncing with external inventory systems.

84. How can you run a specific task or play within an Ansible playbook for testing?

Show answer Use tags to run specific tasks or plays. Example:
```bash
ansible-playbook playbook.yml --tags=tag_name
```

85. Explain how to use the --debug option with Ansible Container commands.

Show answer Append --debug to Ansible Container commands for increased verbosity. Example:
```bash
ansible-container build --debug
```

86. Explain how to view job output and logs in Ansible Tower.

Show answer View job output in the Ansible Tower UI under the specific job details. Logs can be accessed through the UI or retrieved using the Tower API. Additionally, logs are stored in the Tower log directory on the Tower server.

87. Ansible Installation and Configuration:

Show answer * Installation: Use package managers like yum or apt on Linux systems, or install Ansible using Python's pip package manager.
* Configuration: Ansible configurations are set in the ansible.cfg file, defining parameters like inventory location and SSH settings.

88. What steps would you take to troubleshoot a playbook that fails during execution?

Show answer Troubleshooting a playbook involves:
* Reviewing error messages.
* Verifying playbook syntax.
* Checking variable values using debug.
* Running the playbook with increased verbosity (-vvv).
* Isolating failing tasks for focused analysis.

89. How do you enable verbose mode in Ansible for debugging?

Show answer Verbose mode can be enabled by using the -v, -vv, or -vvv options with the ansible or ansible-playbook command. It provides additional output for debugging purposes, with increasing levels of verbosity.

90. What are collections in Ansible?

Show answer Ansible Collections are a way to package and distribute modules, roles, plugins, and documentation in a structured format. They help organize and distribute automation code efficiently, especially for complex environments.

91. What is an Ansible Inventory file, and how is it configured?

Show answer The Ansible Inventory file lists managed nodes and defines groups. It is usually located at /etc/ansible/hosts. Nodes can be listed by IP or hostname. Example entry: webserver ansible_host=192.168.1.10.

92. What is an Ansible role?

Show answer A role is a structured collection of tasks, files, templates, and variables, organized in a standard directory structure, designed for reusability. Roles allow you to break playbooks into reusable components (e.g., a "webserver" role).

93. What is Ansible and how does it differ from other config management tools?

Show answer Ansible is an open-source automation tool used for configuration management, application deployment, task automation, and orchestration. It simplifies complex infrastructure tasks, enabling efficient management of IT environments.

94. Write a playbook to deploy the file ‘/tmp/system_info’ on all hosts except for controllers group, with the following content

Show answer ```
I'm and my operating system is
```

Replace and with the actual data for the specific host you are running on

The playbook to deploy the system_info file

```
---
- name: Deploy /tmp/system_info file
hosts: all:!controllers
tasks:
- name: Deploy /tmp/system_info
template:
src: system_info.j2
dest: /tmp/system_info
```

The content of the system_info.j2 template

```
# {{ ansible_managed }}
I'm {{ ansible_hostname }} and my operating system is {{ ansible_distribution }
```

95. Modify the following task to use a variable instead of the value "zlib" and have "zlib" as the default in case the variable is not defined

Show answer ```
- name: Install a package
package:
name: "{{ package_name|default('zlib') }}"
state: present
```

96. Write a filter to capitalize a string

Show answer ```
def cap(self, string):
return string.capitalize()
```

97. What steps would you take to troubleshoot a failed Ansible playbook?

Show answer Steps include:
* Examining playbook output for error messages.
* Reviewing log files on target hosts.
* Enabling verbose mode (-vvv) for detailed information.
* Validating syntax using ansible-playbook --syntax-check.
* Checking variable values and data.

98. What is an Ansible playbook execution plan, and how can you generate it?

Show answer An execution plan provides a summary of tasks that would be executed. Generate it using the --list-tasks option. Example:
```bash
ansible-playbook playbook.yml --list-tasks
```

99. Write a playbook to install ‘zlib’ and ‘vim’ on all hosts if the file ‘/tmp/mario’ exists on the system.

Show answer ```
---
- hosts: all
vars:
mario_file: /tmp/mario
package_list:
- 'zlib'
- 'vim'
tasks:
- name: Check for mario file
stat:
path: "{{ mario_file }}"
register: mario_f

- name: Install zlib and vim if mario file exists
become: "yes"
package:
name: "{{ item }}"
state: present
with_items: "{{ package_list }}"
when: mario_f.stat.exists
```

100. What makes good Ansible?

Show answer Good Ansible code follows these principles:

**Idempotent**: Running twice produces same result as running once. No "changed" on second run if state is correct.

**Readable**: Clear task names, organized variables, logical role structure. Future you (or your team) must understand it.

**Minimal conditionals**: If you have `when:` everywhere, your inventory structure is probably wrong.

**Clear variables**: Good naming, appropriate scope (group_vars vs host_vars), documented defaults.

**No shell unless necessary**: Shell/command modules break idempotence. Use proper modules first.

**Tested**: Syntax checks, dry-runs, molecule tests for roles.

Bad Ansible is just scripting with extra steps.

101. How to make the variable "use_var" optional?

Show answer With "default(omit)"
```
- name: Install a package
package:
name: "zlib"
state: present
use: "{{ use_var|default(omit) }}"
```

102. What is Ansible Container, and how does it integrate with Docker?

Show answer Ansible Container is an extension for managing containerized applications using Ansible. It allows defining container specifications in Ansible playbooks. Integration with Docker involves using Ansible to define Docker container configurations, build images, and deploy containers.

103. How do you test Ansible safely?

Show answer Multiple layers of safety:

**Syntax and lint**:
```bash
ansible-playbook --syntax-check playbook.yml
ansible-lint playbook.yml
```

**Dry-run (check mode)**:
```bash
ansible-playbook --check --diff playbook.yml
```
Shows what WOULD change without doing it.

**Target safely**:
* Non-prod environments first
* Small batches: `--limit 'web[0:2]'`
* Serial execution for risky changes: `serial: 1`

**Role testing with Molecule**:
```bash
molecule test
```
Spins up containers, applies role, runs verification.

**Canary deployments**: Run on one host, verify, then expand.

104. Explain the process of editing an encrypted file with Ansible Vault.

Show answer Use the ansible-vault edit command to edit an encrypted file.
Example:
```bash
ansible-vault edit secret_file.yml
```
Ansible will prompt for the Vault password before allowing access.

105. Explain the Difference between Forks and Serial & Throttle.

Show answer `Serial` is like running the playbook for each host in turn, waiting for completion of the complete playbook before moving on to the next host. `forks`=1 means run the first task in a play on one host before running the same task on the next host, so the first task will be run for each host before the next task is touched. Default fork is 5 in ansible.

```
[defaults]
forks = 30
```

```
- hosts: webservers
serial: 1
tasks:
- name: ...
```

Ansible also supports `throttle` This keyword limits the number of workers up to the maximum set via the forks setting or serial. This can be useful in restricting tasks that may be CPU-intensive or interact with a rate-limiting API

```
tasks:
- command: /path/to/cpu_intensive_command
throttle: 1
```

106. The variable 'whoami' defined in the following places:

Show answer The answer is 'toad'. Ansible variable precedence (lowest to highest, simplified):

1. Role defaults
2. Inventory vars (group_vars, host_vars)
3. Play vars, vars_files, vars_prompt
4. Task vars, block vars
5. Role params
6. set_fact / registered vars
7. Extra vars (-e on CLI) — always win

Rule of thumb: More specific scope beats less specific. CLI extra vars override everything.

107. What are common issues you might encounter with dynamic inventories, and how would you troubleshoot them?

Show answer Common issues include script errors, incomplete data, or connectivity problems. Troubleshoot by running the inventory script manually, checking script permissions, and validating output format.

108. How can you optimize Ansible playbooks for performance?

Show answer Performance optimization involves:
* Minimizing the use of gather_facts when not needed.
* Limiting playbook runs to relevant hosts.
* Using async tasks for long-running operations.
* Employing parallelism with forks.
* Avoiding unnecessary loops and conditionals.

109. What is Ansible Vault, and why is it used?

Show answer Ansible Vault is a feature that encrypts sensitive data, such as passwords or secret keys, within Ansible playbooks and roles. It ensures that sensitive information is kept secure and can be safely shared or stored in version control systems.

110. How can you use Ansible for managing Windows servers?

Show answer Ansible can manage Windows servers using WinRM (Windows Remote Management). Install the pywinrm Python module on the Ansible controller and configure WinRM on Windows servers. Use Ansible playbooks with appropriate Windows-specific modules to perform tasks.

111. Explain the key components of Ansible.

Show answer Ansible consists of:
* Controller Node: The machine running Ansible, orchestrating tasks.
* Managed Nodes: Systems Ansible manages and automates.
* Inventory: A list of managed nodes.
* Modules: Units of work executed by Ansible.
* Playbooks: YAML files defining tasks and configurations.

112. What does idempotency mean in Ansible and why is it important?

Show answer Idempotency means running the same operation multiple times produces the same
result as running it once. In Ansible, a task is idempotent if running it
repeatedly doesn't change the system after the first application.

Why it matters:
- Safe to re-run playbooks (won't break things)
- Enables "desired state" configuration
- Allows for drift detection and correction
- Makes automation predictable and reliable

Good (idempotent):
```yaml
- name: Ensure nginx is installed
apt:
name: nginx
state: present

113. What is YAML, and why is it used in Ansible?

Show answer YAML (YAML Ain't Markup Language) is a human-readable data serialization format. Ansible uses YAML for playbooks and inventories due to its simplicity, readability, and easy mapping to data structures.

114. What is the purpose of the debug module in Ansible?

Show answer The debug module in Ansible is used to print debug messages during playbook execution. It helps troubleshoot by providing information about variable values, task execution details, or any other custom messages.

115. How do you include external tasks in an Ansible Playbook?

Show answer External tasks can be included using the include_tasks or import_tasks directives. For example:
```yaml
- name: Include external tasks
include_tasks: tasks/external_tasks.yml
```

116. How can you use tags in Ansible Roles?

Show answer Tags in Ansible Roles allow selective execution of tasks. Tags are defined in the tasks themselves, and you can run only tasks with specific tags using the --tags option during playbook execution.

117. What are some common issues you might encounter with Ansible modules, and how would you troubleshoot them?

Show answer Issues include module compatibility, incorrect parameters, or module not installed. Troubleshoot by checking documentation, validating parameters, and ensuring the module is available.

118. How do you limit Ansible to run on one host at a time (serial execution)?

Show answer In a playbook, use the serial keyword (e.g., serial: 1 in a play limits Ansible to configure one host at a time from the inventory).

119. How do you use Ansible Vault in a playbook?

Show answer Include the ansible-vault command in the playbook execution command.
Example:
```bash
ansible-playbook --ask-vault-pass playbook.yml
```

120. What is Ansible Tower, and how does it differ from Ansible?

Show answer Ansible Tower is a web-based interface and automation orchestrator for Ansible. It provides a centralized platform for managing and monitoring Ansible automation. While Ansible is the underlying automation engine, Ansible Tower adds features like role-based access control, job scheduling, and a user-friendly interface.

121. Write a single task that verifies all the files in files_list variable exist on the host

Show answer ```
- name: Ensure all files exist
assert:
that:
- item.stat.exists
loop: "{{ files_list }}"
```

122. How do you create an encrypted file using Ansible Vault?

Show answer Use the ansible-vault create command to create an encrypted file.
Example:
```bash
ansible-vault create secret_file.yml
```

123. Explain the use of the ansible-doc command for module documentation.

Show answer ansible-doc provides documentation for Ansible modules. Example:
```bash
ansible-doc module_name
```

124. Can you provide an example of a task you've automated to improve data center efficiency?

Show answer One example of a task automated for data center efficiency is the provisioning of virtual machines (VMs) based on demand. Using tools like Ansible or PowerShell, I created automation scripts that dynamically allocate and configure VMs in response to changing workloads. These scripts assess current resource utilization, determine the required capacity, and automatically spin up or down VMs accordingly. This ensures optimal resource allocation, reduces manual intervention, and improves scalability, contributing to overall data center efficiency.

125. Explain the role of orchestration in automating complex tasks across servers and networking devices.

Show answer • Task Sequencing: Orchestration involves the coordination and sequencing of multiple tasks across servers and networking devices to achieve a specific objective. • Workflow Automation: Orchestration tools automate workflows by defining the order and dependencies of tasks, ensuring that each step is executed in the correct sequence. • Cross-Platform Integration: Orchestration facilitates the integration of tasks across diverse platforms, allowing for the automation of complex processes involving servers, networking devices, and external services.

126. How do you approach automating repetitive tasks in a data center?

Show answer Automating repetitive tasks in a data center involves the following steps: **Task Identification:* • Identify tasks that are repetitive and time-consuming but suitable for automation. **Tool Selection:* • Choose appropriate automation tools based on the task requirements. For server management, tools like Ansible, PowerShell, or configuration management tools may be suitable. **Scripting/Playbook Development:* • Develop scripts or playbooks that automate the identified tasks. Ensure they are well-documented and modular for scalability and maintenance.

127. Have you used automation tools like PowerShell or Ansible for server management tasks?

Show answer Automation tools such as PowerShell and Ansible streamline server management tasks: • **PowerShell:* • • Windows Environment: PowerShell is a scripting language and automation framework designed for Windows environments. • Task Automation: It allows the automation of various tasks, including server configuration, software deployment, and system administration. • Scripting Capabilities: PowerShell scripts can be written to execute commands and tasks, making it efficient for managing Windows servers.

128. Provide an example of a complex task or process you automated using scripting or automation tools.

Show answer In a previous role, I automated the deployment and configuration of a multi-tiered application stack using Ansible. **Steps Taken:* • • Infrastructure Provisioning: Wrote Ansible playbooks to automate the provisioning of virtual machines on different environments (development, testing, and production). • Software Installation: Automated the installation and configuration of various software components, including web servers, application servers, and databases, ensuring consistency across environments.

🔴 Hard (16)

1. Managing Multiple Environments

Show answer To manage multiple environments, I would use separate inventory files and group variables for each environment.

Example directory structure:

```
inventories/
development/
hosts
group_vars/
all.yml
staging/
hosts
group_vars/
all.yml
production/
hosts
group_vars/
all.yml
site.yml
```

In site.yml, specify the inventory file based on the environment:

```
ansible-playbook -i inventories/development/hosts site.yml
ansible-playbook -i inventories/staging/hosts site.yml
ansible-playbook -i inventories/production/hosts site.yml
```

This approach keeps environment-specific configurations separate and manageable.

2. What's the most common non-obvious Ansible scalability killer?

Show answer Fact gathering - enabled by default, runs on every host, before any tasks.

The problem:
- `gather_facts: true` is default
- Collects extensive system info via setup module
- Runs sequentially per fork
- Takes 2-10 seconds PER HOST
- 1000 hosts * 5 seconds = 83 minutes before first task

Other scalability killers:

1. SSH connection setup
- New connection per host per play
- SSH handshake overhead
- Mitigation: pipelining, ControlPersist

3. Ansible in a Multi-Cloud Environment

Show answer To manage multi-cloud environments, I would use dynamic inventories and cloud-specific modules for each provider (AWS, Azure, GCP).

Example using multiple dynamic inventories:

```
plugin: aws_ec2
regions:
- us-east-1

plugin: azure_rm
```

```
ansible-playbook -i aws_ec2.yml -i azure_rm.yml playbook.yml
```

4. What are idempotency issues in infrastructure automation and how are they avoided?

Show answer Idempotency means that running a task multiple times should have the same effect as running it once. To identify and fix idempotency issues:

Identify the Task: Determine which task is causing the issue by reviewing the output of ansible-playbook with the -v (verbose) flag.

Analyze the Task: Check if the task is correctly checking for the desired state before making changes. For example, ensure that file changes, service restarts, or package installations are conditional.

5. Migrating Legacy Scripts to Ansible

Show answer To migrate legacy scripts to Ansible:

Identify Tasks: Break down the shell script into discrete tasks.

Use Ansible Modules: Replace shell commands with equivalent Ansible modules.

Structure Playbooks: Organize tasks into roles and playbooks for better management.

Example migration:

Original shell script:

```
#!/bin/bash
apt-get update
apt-get install -y nginx
echo "Hello, World!" > /var/www/html/index.html
```

Migrated Ansible playbook:


```
- hosts: web
tasks:
- name: Update apt cache
apt:
update_cache: yes

- name: Install Nginx
apt:
name: nginx
state: present

- name: Create index.html
copy:
content: "Hello, World!"
dest: /var/www/html/index.html
```

6. Handling Secret Management

Show answer For managing sensitive information in Ansible, I use Ansible Vault. Ansible Vault allows you to encrypt sensitive data within YAML files.

To encrypt a file:

```
ansible-vault encrypt secrets.yml
```

To use the encrypted secrets in a playbook:

```
- hosts: all
vars_files:
- secrets.yml
tasks:
- name: Use secret API key
uri:
url: "https://api.example.com/data"
headers:
Authorization: "Bearer {{ api_key }}"

```

To run the playbook with the vault password:

```
ansible-playbook playbook.yml --ask-vault-pass
```

7. Configuring Ansible for Network Automation

Show answer For network automation, I would use Ansible network modules and collections like ansible.netcommon and vendor-specific collections.

Example playbook for Cisco devices:

```
- hosts: cisco_routers
gather_facts: no
tasks:
- name: Configure interface
cisco.ios.ios_interface:
name: GigabitEthernet1
description: "Configured by Ansible"
enabled: yes
```

8. Error Handling in Playbooks

Show answer To handle errors:

Ignore Errors: Use ignore_errors: yes for non-critical tasks.

```
- name: Task that might fail
command: /bin/false
ignore_errors: yes
```

Retries: Use retries and delay for tasks that might fail intermittently.

```
- name: Retry task
command: /path/to/command
retries: 5
delay: 10
until: result.rc == 0
register: result
```

Rescue and Always: Use block, rescue, and always for structured error handling.

```
- name: Structured error handling
block:
- name: Task that might fail
command: /bin/false
rescue:
- name: Handle failure
debug:
msg: "Task failed"
always:
- name: Always run
debug:
msg: "This always runs"
```

9. Optimizing Playbook Performance

Show answer To optimize playbook performance:

Parallelism: Increase the number of forks to run tasks in parallel.

```
ansible-playbook -i inventory playbook.yml -f 10
```

Delegate Tasks: Delegate tasks to appropriate hosts to distribute the load.

```
- name: Fetch something
delegate_to: localhost
```

Limit Scope: Use --limit to target specific hosts.

```
ansible-playbook -i inventory playbook.yml --limit web_servers
```

Asynchronous Tasks: Use asynchronous tasks for long-running operations.

10. Handling Dependencies

Show answer To integrate Ansible with a CI/CD pipeline, I would use tools like Jenkins, GitLab CI, or GitHub Actions. The CI/CD pipeline would trigger Ansible playbooks to deploy or update infrastructure.

Example using GitLab CI:

```
stages:
- deploy

deploy:
stage: deploy
script:
- ansible-playbook -i inventory playbook.yml
```

11. Rolling Updates with Zero Downtime

Show answer To implement a rolling update with zero downtime, I would use a combination of Ansible playbooks and a load balancer. The process involves updating a subset of servers at a time while ensuring the load balancer only directs traffic to healthy nodes. Here’s a high-level approach:

Drain Traffic: Use Ansible to interact with the load balancer API to drain traffic from the first subset of servers.

Update Servers: Apply the updates to the drained servers.

Health Check: Ensure the updated servers pass health checks.

12. Multi-Tier Application Deployment

Show answer To handle a multi-tier application deployment efficiently, I would use a modular approach with Ansible roles. Each tier (web server, application server, database server) would have its own role. The directory structure might look like this:

```sh
site.yml
roles/
web/
tasks/
main.yml
templates/
web.conf.j2
app/
tasks/
main.yml
templates/
app.conf.j2
db/
tasks/
main.yml
templates/
db.conf.j2
inventory/
production/
hosts
group_vars/

13. Handling Configuration Drift

Show answer To ensure servers remain in the desired state, I would implement regular configuration enforcement using Ansible Tower/AWX or a cron job that runs playbooks periodically. Additionally, I would use Ansible’s check mode to detect drift without making changes.

Example cron job:

```
0 2 * * * ansible-playbook -i inventory playbook.yml
```

14. Ansible Dynamic Inventory

Show answer To manage a dynamic infrastructure, I would use Ansible’s dynamic inventory feature. This can be achieved by using inventory scripts or plugins that query external data sources such as cloud provider APIs (e.g., AWS, Azure).

Example using AWS EC2 dynamic inventory:

Install the AWS Inventory Plugin:

```
pip install boto boto3
```

Configure the AWS Inventory Plugin:

```
plugin: aws_ec2
regions:
- us-east-1
filters:
tag:Environment: production

```

Use the Dynamic Inventory in Playbooks:

```
ansible-playbook -i aws_ec2.yml playbook.yml

```

15. Troubleshooting Playbook Failures

Show answer To troubleshoot a failing playbook:

Check Recent Changes: Review recent changes in the playbook, roles, or inventory files.

Verbose Output: Run the playbook with increased verbosity (-vvv) to get detailed output and identify where it fails.

Environment Consistency: Ensure the environment where the playbook is run hasn’t changed (e.g., different Ansible version, OS updates, or network configurations).

Isolate the Issue: Isolate the failing task by running it independently or within a minimal playbook.

16. Why is Ansible more dangerous than shell scripts at scale?

Show answer Ansible provides consistent, parallel execution of potentially wrong changes across your entire fleet.

The dangers:

1. Consistent blast radius
- Shell script on one host = one host affected
- Ansible playbook = hundreds of hosts simultaneously
- Mistakes replicated perfectly everywhere

2. Idempotent repetition of wrong state
- "Idempotent" means it enforces state consistently
- Wrong state enforced consistently is still wrong
- Running again won't fix it, will reinforce it