Skip to content

Ansible Playbooks

← Back to all decks

103 cards β€” 🟒 7 easy | 🟑 81 medium

🟒 Easy (7)

1. 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).

Under the hood: Galaxy hosts both roles and collections (bundles of modules, roles, and plugins). Collections are the modern packaging format since Ansible 2.10+.

Example: ansible-galaxy install geerlingguy.docker installs a community role. Use requirements.yml to pin versions for reproducible builds.

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

Gotcha: YAML indentation matters in playbooks. Use 2-space indent consistently. A single wrong indent can change a task's behavior or cause a syntax error.

3. What language are Ansible playbooks written in?

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

Fun fact: YAML stands for 'YAML Ain't Markup Language' (recursive acronym). It was chosen for readability over JSON or XML.

Gotcha: YAML is whitespace-sensitive. Mixing tabs and spaces causes parse errors. Convention is 2-space indentation.

Gotcha: YAML indentation matters in playbooks. Use 2-space indent consistently. A single wrong indent can change a task's behavior or cause a syntax error.

4. 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".

Remember: variable precedence (low to high): defaults, inventory, playbook, role vars, extra vars (-e). Extra vars always win.

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

Remember: a role is a self-contained bundle: tasks/, handlers/, templates/, files/, defaults/, vars/, meta/. Think 'reusable Ansible package.'

Example: ansible-galaxy init myrole scaffolds the directory structure. Share roles via Galaxy or private Git repos.

6. What are Ansible "templates"?

Show answer Files using Jinja2 syntax to generate dynamic configurations.

Example: {{ ansible_hostname }}-{{ ansible_date_time.date }}.log renders to 'web01-2026-03-21.log'. Jinja2 supports filters: {{ name | upper }}.

Gotcha: always quote Jinja2 expressions in YAML: name: '{{ var }}' β€” unquoted {{ can break YAML parsing.

7. What are Ansible "roles"?

Show answer Organizational units that group related tasks and variables.

Remember: a role is a self-contained bundle: tasks/, handlers/, templates/, files/, defaults/, vars/, meta/. Think 'reusable Ansible package.'

Example: ansible-galaxy init myrole scaffolds the directory structure. Share roles via Galaxy or private Git repos.

🟑 Medium (81)

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

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

Remember: import_* = static (parsed at playbook load). include_* = dynamic (parsed at runtime). Use import for roles, include for conditional logic.

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

Gotcha: YAML indentation matters in playbooks. Use 2-space indent consistently. A single wrong indent can change a task's behavior or cause a syntax error.

3. 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 }}`

Under the hood: Jinja2's bool filter converts strings like 'True', 'yes', '1' to Python True, and 'False', 'no', '0' to False. Essential when variables come from external sources as strings.

Remember: variable precedence (low to high): defaults, inventory, playbook, role vars, extra vars (-e). Extra vars always win.

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

Gotcha: YAML indentation matters in playbooks. Use 2-space indent consistently. A single wrong indent can change a task's behavior or cause a syntax error.

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

Gotcha: YAML indentation matters in playbooks. Use 2-space indent consistently. A single wrong indent can change a task's behavior or cause a syntax error.

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

Gotcha: YAML indentation matters in playbooks. Use 2-space indent consistently. A single wrong indent can change a task's behavior or cause a syntax error.

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

Example: assert: that: ansible_memtotal_mb >= 1024 fail_msg: 'Insufficient memory' β€” validates preconditions before proceeding with the playbook.

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

Example: setting ansible_ssh_common_args: '-o ProxyJump=bastion.example.com' routes all SSH through a bastion/jump host β€” useful for reaching private subnets.

Remember: a role is a self-contained bundle: tasks/, handlers/, templates/, files/, defaults/, vars/, meta/. Think 'reusable Ansible package.'

Example: ansible-galaxy init myrole scaffolds the directory structure. Share roles via Galaxy or private Git repos.

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

Gotcha: YAML indentation matters in playbooks. Use 2-space indent consistently. A single wrong indent can change a task's behavior or cause a syntax error.

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

Remember: a role is a self-contained bundle: tasks/, handlers/, templates/, files/, defaults/, vars/, meta/. Think 'reusable Ansible package.'

Example: ansible-galaxy init myrole scaffolds the directory structure. Share roles via Galaxy or private Git repos.

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

Remember: handlers run once at end of play, even if notified multiple times. Use meta: flush_handlers to force immediate execution.

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

Example: ansible all -m shell -a 'uptime' -b runs uptime as root on all hosts. Ad-hoc is for quick one-off tasks; use playbooks for repeatable workflows.

Gotcha: YAML indentation matters in playbooks. Use 2-space indent consistently. A single wrong indent can change a task's behavior or cause a syntax error.

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

Gotcha: YAML indentation matters in playbooks. Use 2-space indent consistently. A single wrong indent can change a task's behavior or cause a syntax error.

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

Gotcha: YAML indentation matters in playbooks. Use 2-space indent consistently. A single wrong indent can change a task's behavior or cause a syntax error.

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

16. 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\nansible-galaxy install author_name.role_name\n```

Example: ansible-galaxy install geerlingguy.docker installs a community role. Use requirements.yml to pin versions for reproducible builds.

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

Gotcha: YAML indentation matters in playbooks. Use 2-space indent consistently. A single wrong indent can change a task's behavior or cause a syntax error.

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

Remember: a role is a self-contained bundle: tasks/, handlers/, templates/, files/, defaults/, vars/, meta/. Think 'reusable Ansible package.'

Example: ansible-galaxy init myrole scaffolds the directory structure. Share roles via Galaxy or private Git repos.

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

Remember: handlers run once at end of play, even if notified multiple times. Use meta: flush_handlers to force immediate execution.

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

Example: lookup('file', '/path/to/file') reads a file. lookup('env', 'HOME') reads an environment variable. lookup('pipe', 'date') runs a command. Lookups execute on the control node.

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

Gotcha: YAML indentation matters in playbooks. Use 2-space indent consistently. A single wrong indent can change a task's behavior or cause a syntax error.

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

Gotcha: YAML indentation matters in playbooks. Use 2-space indent consistently. A single wrong indent can change a task's behavior or cause a syntax error.

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

Gotcha: YAML indentation matters in playbooks. Use 2-space indent consistently. A single wrong indent can change a task's behavior or cause a syntax error.

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

Gotcha: YAML indentation matters in playbooks. Use 2-space indent consistently. A single wrong indent can change a task's behavior or cause a syntax error.

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

Example: ansible-playbook site.yml --check --diff shows what WOULD change without actually changing anything. Perfect for pre-deployment review.

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

Remember: variable precedence (low to high): defaults, inventory, playbook, role vars, extra vars (-e). Extra vars always win.

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

Remember: a role is a self-contained bundle: tasks/, handlers/, templates/, files/, defaults/, vars/, meta/. Think 'reusable Ansible package.'

Example: ansible-galaxy init myrole scaffolds the directory structure. Share roles via Galaxy or private Git repos.

28. 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"

Gotcha: YAML indentation matters in playbooks. Use 2-space indent consistently. A single wrong indent can change a task's behavior or cause a syntax error.

29. 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\n- name: Pause for debugging\n pause:\n minutes: 30\n```

Remember: Ansible playbooks should be idempotent β€” running them twice produces the same result. Use modules (not shell/command) to ensure this.

Gotcha: always test playbooks with --check --diff before applying. This shows what WOULD change without actually changing anything.

30. 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)

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

Gotcha: YAML indentation matters in playbooks. Use 2-space indent consistently. A single wrong indent can change a task's behavior or cause a syntax error.

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

Gotcha: YAML indentation matters in playbooks. Use 2-space indent consistently. A single wrong indent can change a task's behavior or cause a syntax error.

33. 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\nansible-playbook playbook.yml --list-tasks\n```

Gotcha: combine --list-tasks with --tags to see which tasks would run with your tag filter, without executing anything. Great for verifying tag coverage before running on production.

Gotcha: YAML indentation matters in playbooks. Use 2-space indent consistently. A single wrong indent can change a task's behavior or cause a syntax error.

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

Example: {{ ansible_hostname }}-{{ ansible_date_time.date }}.log renders to 'web01-2026-03-21.log'. Jinja2 supports filters: {{ name | upper }}.

Gotcha: always quote Jinja2 expressions in YAML: name: '{{ var }}' β€” unquoted {{ can break YAML parsing.

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

Gotcha: YAML indentation matters in playbooks. Use 2-space indent consistently. A single wrong indent can change a task's behavior or cause a syntax error.

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

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

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.

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

Remember: a role is a self-contained bundle: tasks/, handlers/, templates/, files/, defaults/, vars/, meta/. Think 'reusable Ansible package.'

Example: ansible-galaxy init myrole scaffolds the directory structure. Share roles via Galaxy or private Git repos.

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

Remember: a role is a self-contained bundle: tasks/, handlers/, templates/, files/, defaults/, vars/, meta/. Think 'reusable Ansible package.'

Example: ansible-galaxy init myrole scaffolds the directory structure. Share roles via Galaxy or private Git repos.

39. 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\nansible-playbook playbook.yml --limit=hostname\n```

Gotcha: --limit accepts patterns: --limit 'web*' targets hosts matching the glob. Combine with --list-hosts to verify which hosts match before running.

Gotcha: YAML indentation matters in playbooks. Use 2-space indent consistently. A single wrong indent can change a task's behavior or cause a syntax error.

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

Show answer {{ some_var | type_debug }}

Under the hood: type_debug outputs the Python type name (str, int, list, dict, etc.). Invaluable for debugging when a variable is unexpectedly a string instead of a list or integer.

Remember: variable precedence (low to high): defaults, inventory, playbook, role vars, extra vars (-e). Extra vars always win.

41. 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") }}`

Under the hood: ternary is a Jinja2 filter that acts like a C-style ternary operator: condition | ternary(true_val, false_val). Useful for concise conditional assignments in templates.

Remember: variable precedence (low to high): defaults, inventory, playbook, role vars, extra vars (-e). Extra vars always win.

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

Show answer False. It uses a procedural style.

Under the hood: tasks execute top-to-bottom (procedural), unlike Terraform which builds a dependency graph (declarative). Individual modules like apt with state=present behave declaratively.

Gotcha: YAML indentation matters in playbooks. Use 2-space indent consistently. A single wrong indent can change a task's behavior or cause a syntax error.

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

Gotcha: YAML indentation matters in playbooks. Use 2-space indent consistently. A single wrong indent can change a task's behavior or cause a syntax error.

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

Remember: a role is a self-contained bundle: tasks/, handlers/, templates/, files/, defaults/, vars/, meta/. Think 'reusable Ansible package.'

Example: ansible-galaxy init myrole scaffolds the directory structure. Share roles via Galaxy or private Git repos.

45. 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\nansible-playbook playbook.yml --check\n```

Gotcha: --check (dry run) does not guarantee accuracy β€” modules that depend on previous task results may report incorrect changes. Use it as a sanity check, not a guarantee.

Example: ansible-playbook site.yml --check --diff shows what WOULD change without actually changing anything. Perfect for pre-deployment review.

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

Gotcha: YAML indentation matters in playbooks. Use 2-space indent consistently. A single wrong indent can change a task's behavior or cause a syntax error.

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

Gotcha: YAML indentation matters in playbooks. Use 2-space indent consistently. A single wrong indent can change a task's behavior or cause a syntax error.

48. What is the syntax for an Ansible Playbook?

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

Gotcha: YAML indentation matters in playbooks. Use 2-space indent consistently. A single wrong indent can change a task's behavior or cause a syntax error.

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

Remember: a role is a self-contained bundle: tasks/, handlers/, templates/, files/, defaults/, vars/, meta/. Think 'reusable Ansible package.'

Example: ansible-galaxy init myrole scaffolds the directory structure. Share roles via Galaxy or private Git repos.

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

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

Gotcha: YAML indentation matters in playbooks. Use 2-space indent consistently. A single wrong indent can change a task's behavior or cause a syntax error.

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

Remember: import_* = static (parsed at playbook load). include_* = dynamic (parsed at runtime). Use import for roles, include for conditional logic.

52. 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\n- name: Print variable value\n debug:\n var: variable_name\n```

Remember: variable precedence (low to high): defaults, inventory, playbook, role vars, extra vars (-e). Extra vars always win.

53. 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\nansible-playbook playbook.yml --tags=tag_name\n```

Gotcha: if a task's tag is not explicitly listed in --tags, it is skipped entirely. Use the special 'always' tag for tasks that must execute regardless of filtering.

Gotcha: YAML indentation matters in playbooks. Use 2-space indent consistently. A single wrong indent can change a task's behavior or cause a syntax error.

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

Example: assert: that: ansible_memtotal_mb >= 1024 fail_msg: 'Insufficient memory' β€” validates preconditions before proceeding with the playbook.

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

Gotcha: YAML indentation matters in playbooks. Use 2-space indent consistently. A single wrong indent can change a task's behavior or cause a syntax error.

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

Gotcha: YAML indentation matters in playbooks. Use 2-space indent consistently. A single wrong indent can change a task's behavior or cause a syntax error.

57. 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).

Remember: a role is a self-contained bundle: tasks/, handlers/, templates/, files/, defaults/, vars/, meta/. Think 'reusable Ansible package.'

Example: ansible-galaxy init myrole scaffolds the directory structure. Share roles via Galaxy or private Git repos.

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

Gotcha: YAML indentation matters in playbooks. Use 2-space indent consistently. A single wrong indent can change a task's behavior or cause a syntax error.

59. Write a playbook to deploy the file β€˜/tmp/system_info’ on all hosts except for controllers group, with the following content

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

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

The playbook to deploy the system_info file

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

The content of the system_info.j2 template

```\n# {{ ansible_managed }}\nI'm {{ ansible_hostname }} and my operating system is {{ ansible_distribution }\n```

Gotcha: YAML indentation matters in playbooks. Use 2-space indent consistently. A single wrong indent can change a task's behavior or cause a syntax error.

60. 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 ```\n- name: Install a package\n package:\n name: "{{ package_name|default('zlib') }}"\n state: present\n```

Remember: variable precedence (low to high): defaults, inventory, playbook, role vars, extra vars (-e). Extra vars always win.

61. Write a filter to capitalize a string

Show answer ```\ndef cap(self, string):\n return string.capitalize()\n```

Under the hood: custom Jinja2 filters are Python functions placed in a filter_plugins/ directory alongside your playbook. Ansible auto-discovers them at runtime.

Remember: useful Jinja2 filters: default('fallback'), join(','), replace('old','new'), regex_replace, to_yaml, to_json, combine (merge dicts). Filters chain: {{ var | lower | trim }}.

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

Example: assert: that: ansible_memtotal_mb >= 1024 fail_msg: 'Insufficient memory' β€” validates preconditions before proceeding with the playbook.

63. 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\nansible-playbook playbook.yml --list-tasks\n```

Gotcha: combine --list-tasks with --tags to see which tasks would run with your tag filter, without executing anything. Great for verifying tag coverage before running on production.

Gotcha: YAML indentation matters in playbooks. Use 2-space indent consistently. A single wrong indent can change a task's behavior or cause a syntax error.

64. Write a playbook to install β€˜zlib’ and β€˜vim’ on all hosts if the file β€˜/tmp/mario’ exists on the system.

Show answer ```\n---\n- hosts: all\n vars:\n mario_file: /tmp/mario\n package_list:\n - 'zlib'\n - 'vim'\n tasks:\n - name: Check for mario file\n stat:\n path: "{{ mario_file }}"\n register: mario_f\n\n - name: Install zlib and vim if mario file exists\n become: "yes"\n package:\n name: "{{ item }}"\n state: present\n with_items: "{{ package_list }}"\n when: mario_f.stat.exists\n```

Gotcha: YAML indentation matters in playbooks. Use 2-space indent consistently. A single wrong indent can change a task's behavior or cause a syntax error.

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

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

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

Remember: variable precedence (low to high): defaults, inventory, playbook, role vars, extra vars (-e). Extra vars always win.

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

Gotcha: YAML indentation matters in playbooks. Use 2-space indent consistently. A single wrong indent can change a task's behavior or cause a syntax error.

68. How do you test Ansible safely?

Show answer Multiple layers of safety:

**Syntax and lint**:
```bash\nansible-playbook --syntax-check playbook.yml\nansible-lint playbook.yml\n```

**Dry-run (check mode)**:
```bash\nansible-playbook --check --diff playbook.yml\n```
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\nmolecule test\n```
Spins up containers, applies role, runs verification.

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

Gotcha: YAML indentation matters in playbooks. Use 2-space indent consistently. A single wrong indent can change a task's behavior or cause a syntax error.

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

```\n[defaults]\nforks = 30\n```

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

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

```\ntasks:\n- command: /path/to/cpu_intensive_command\n throttle: 1\n```

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

Remember: variable precedence (low to high): defaults, inventory, playbook, role vars, extra vars (-e). Extra vars always win.

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

Gotcha: YAML indentation matters in playbooks. Use 2-space indent consistently. A single wrong indent can change a task's behavior or cause a syntax error.

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

Gotcha: YAML indentation matters in playbooks. Use 2-space indent consistently. A single wrong indent can change a task's behavior or cause a syntax error.

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

Gotcha: YAML indentation matters in playbooks. Use 2-space indent consistently. A single wrong indent can change a task's behavior or cause a syntax error.

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

Gotcha: YAML indentation matters in playbooks. Use 2-space indent consistently. A single wrong indent can change a task's behavior or cause a syntax error.

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

Gotcha: YAML indentation matters in playbooks. Use 2-space indent consistently. A single wrong indent can change a task's behavior or cause a syntax error.

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

Gotcha: YAML indentation matters in playbooks. Use 2-space indent consistently. A single wrong indent can change a task's behavior or cause a syntax error.

77. 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\n- name: Include external tasks\n include_tasks: tasks/external_tasks.yml\n```

Remember: import_* = static (parsed at playbook load). include_* = dynamic (parsed at runtime). Use import for roles, include for conditional logic.

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

Gotcha: YAML indentation matters in playbooks. Use 2-space indent consistently. A single wrong indent can change a task's behavior or cause a syntax error.

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

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

Gotcha: you can mix encrypted and unencrypted variable files in the same playbook. Use --vault-id to manage multiple vault passwords for different environments (dev, prod).

Gotcha: YAML indentation matters in playbooks. Use 2-space indent consistently. A single wrong indent can change a task's behavior or cause a syntax error.

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

Gotcha: YAML indentation matters in playbooks. Use 2-space indent consistently. A single wrong indent can change a task's behavior or cause a syntax error.

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

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

Remember: variable precedence (low to high): defaults, inventory, playbook, role vars, extra vars (-e). Extra vars always win.