patternMajor
Execute multiple Ansible tasks with the same list of items
Viewed 0 times
samethewithtasksitemsmultiplelistansibleexecute
Problem
I am using an ansible playbook to configure Apache for a list of sites. The playbook has to copy the virtual host configuration template for each site into place, and then enable each site using
I don't like having to repeat the same list for each task. How to I configure the playbook to execute both tasks with the same list of items?
a2ensite:- name: Install apache site conf
template: src=apache-sites-{{item}}-conf.j2 dest=/etc/apache2/sites-available/{{item}}.conf mode=0644
with_items:
- sitea
- siteb
- sitec
- sited
- name: Enable site apache conf
command: a2ensite {{item}}
args:
creates: /etc/apache2/sites-enabled/{{item}}.conf
with_items:
- sitea
- siteb
- sitec
- sitedI don't like having to repeat the same list for each task. How to I configure the playbook to execute both tasks with the same list of items?
Solution
Make separate tasks file
And in your playbook:
make_site.yml:---
- name: Install apache site conf
template:
src: apache-sites-{{ site }}-conf.j2
dest: /etc/apache2/sites-available/{{ site }}.conf
mode: 0644
- name: Enable site apache conf
command: a2ensite {{ site }}
args:
creates: /etc/apache2/sites-enabled/{{ site }}.confAnd in your playbook:
- include_tasks: make_site.yml
with_items:
- sitea
- siteb
- sitec
- sited
loop_control:
loop_var: siteCode Snippets
---
- name: Install apache site conf
template:
src: apache-sites-{{ site }}-conf.j2
dest: /etc/apache2/sites-available/{{ site }}.conf
mode: 0644
- name: Enable site apache conf
command: a2ensite {{ site }}
args:
creates: /etc/apache2/sites-enabled/{{ site }}.conf- include_tasks: make_site.yml
with_items:
- sitea
- siteb
- sitec
- sited
loop_control:
loop_var: siteContext
StackExchange DevOps Q#2978, answer score: 21
Revisions (0)
No revisions yet.