In this lab, you will learn how to use external variables with Ansible's loop directive. By leveraging external variables, playbooks can become more dynamic and reusable across different scenarios.
- Use the
loopdirective to iterate over variables defined in the playbook. - Dynamically execute tasks based on external variable data.
- Enhance playbook flexibility for various environments.
- Basic knowledge of Ansible playbooks.
- Ansible installed on your ansible machine.
- Access to a target host categorized as "webservers."
Estimated Time: 30 minutes
-
Create a new YAML file named
loop_with_variables.yml. -
Define the play's name, target hosts, and disable fact gathering:
--- - name: Loop over external variables hosts: webservers gather_facts: no vars: user_list: - Alice - Bob - Charlie
Explanation:
vars: Defines a list of users to iterate over.user_list: Contains the names to be looped through.
-
Under the
taskssection, add a task to iterate over theuser_listvariable and print a custom message for each:tasks: - name: Greeting each user debug: msg: "Hello, {{ item }}" loop: "{{ user_list }}"
Explanation:
loop: Iterates over the values in theuser_listvariable.{{ item }}: Refers to the current value in the loop iteration.
-
Save the
loop_with_variables.ymlfile. -
Run the playbook using the following command:
ansible-playbook loop_with_variables.yml
-
Observe the output. The playbook will print a greeting for each name in the
user_listvariable.
You can compare your playbook with the loop_with_variables.yml file in the current directory.
Using external variables with Ansible's loop directive enhances playbook flexibility and reusability. By defining variables externally, you can adapt playbooks for different environments or scenarios without modifying task logic. Practice using this technique to build dynamic and versatile Ansible playbooks! 👏