In this lab, you will learn how to use include_vars
to include variable files into your playbook. This example demonstrates how to split variables across multiple files and load them using include_vars
for better organization and reusability.
- Use
include_vars
to load variables from external files.
- Ansible installed on your ansible machine.
- At least one managed host configured for Ansible.
Estimated Time: 15 minutes
-
Create a General Variable File:
-
Create a file named
general_vars.yml
with the following content:app_name: "MyApp" app_port: 8080
-
-
Create an Environment-Specific Variable File:
-
Create a file named
env_vars.yml
with the following content:env: "development" db_host: "localhost" db_user: "dev_user" db_password: "dev_password"
-
-
Create a playbook file named
include_vars_play.yml
with the following content:--- - hosts: all gather_facts: no tasks: - name: Include general variables include_vars: general_vars.yml - name: Include environment-specific variables include_vars: env_vars.yml - name: Print app information debug: msg: "App: {{ app_name }}, Port: {{ app_port }}" - name: Print database information debug: msg: "Environment: {{ env }}, DB Host: {{ db_host }}, User: {{ db_user }}"
-
Save the playbook and variable files.
-
Run the playbook using the following command:
ansible-playbook include_vars_play.yml
-
Observe the output. The playbook will load variables from both
general_vars.yml
andenv_vars.yml
, and the debug messages will display the variable values.
In this lab, you’ve learned how to use include_vars
to load variables from multiple files into an Ansible playbook. This technique allows you to organize variables into separate files and load them as needed, making your playbooks more modular and maintainable. 👏