HiveBrain v1.2.0
Get Started
← Back to all entries
patternMajor

Execute multiple Ansible tasks with the same list of items

Submitted by: @import:stackexchange-devops··
0
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 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
  - sited


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?

Solution

Make separate tasks file 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 }}.conf


And in your playbook:

- include_tasks: make_site.yml
  with_items:
    - sitea
    - siteb
    - sitec
    - sited
  loop_control:
    loop_var: site

Code 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: site

Context

StackExchange DevOps Q#2978, answer score: 21

Revisions (0)

No revisions yet.