Ansible Loops
While configuring servers and performing various tasks, you may sometimes need to repeat the execution of the same task using different values. For this purpose we have loops. If when the statement is combined with a loop, Ansible processes the condition separately for each item. Suppose you want to create 50 users at a time. One will have to define a task fifty times for each user. It would be a very inefficient approach.
Using loops
Create a new playbook in your ansible directory as below:
- name: this is our first play.
hosts: webserver1
tasks:
- name: "installing"
apt: name="{{ item }}" state=present
with_items:
- vsftpd
- tree
Here, the item will hold the values from with_items for each iteration.
Run the playbook - And verify the same on webserver1 - The above playbook can be modified as -
- name: this is our first play.
hosts: webserver1
vars:
pkg:
- vsftpd
- tree
tasks:
- name: "installing"
apt: name="{{ item }}" state=present
with_items: "{{ pkg }}"
output: