In this lesson, you will learn how to separate variables from your Ansible inventory file to simplify maintenance and improve organization. When dealing with numerous inventory items, embedding variables within the inventory file itself can quickly become cumbersome. A more efficient approach is to define host-specific variables in dedicated YAML files. For each server (for example, web1, web2, and web3), create a YAML file with the same name as the host inside the host_vars directory. Then, move the corresponding variables from the inventory file into these new files. When transferring the variables, make sure to replace the equal sign (Documentation Index
Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
Use this file to discover all available pages before exploring further.
=) with a colon followed by a space (: ) to adhere to proper YAML syntax. Ansible automatically processes these files during playbook execution, matching them with the corresponding host based on the file name.
Below is an example of an inventory file entry before variables are separated:
- For host variables, use a folder named host_vars.
- For group variables, use a folder named group_vars.
If your variable file is not located in one of Ansible’s default directories, you can still load external variables by using the
include_vars module within your playbook./opt/apps/common-data/email) that is shared across multiple playbooks. Below is a simplified file structure:
include_vars module. For example, to load email-related variables before executing a mail task, your playbook might include the following:
/opt/apps/common-data/email/info.yml) should be structured as follows:
ansible-inventory command with the -y parameter. This outputs the final inventory in YAML format. For example:
In some cases, you may wish to reuse task definitions for installing and configuring services across different playbooks, such as a single playbook that can handle both database and web server configurations. To achieve this modularity, divide your tasks into separate files (for example, tasks/db.yml and tasks/web.yml) and incorporate them into your playbook using the
include_tasks directive. The following example demonstrates how to structure such a playbook:
Reinforce your understanding of
include_tasks and variable management by experimenting with different inventory structures and playbook configurations. This modular approach enhances maintainability and scalability.