Michael DeHaan(creator of Ansible) made a post on CoderWall that talks about very similar issue. You can adjust and expand it according to your needs(such as permissions and ownership).
Relevant part of the post is here:
This can be simplified by using "with_items
" and a single notify
statement. If any of the tasks change, the service will be notified in exactly the same way that it needs to restart at the end of the playbook run.
- name: template everything for fooserv
template: src={{item.src}} dest={{item.dest}}
with_items:
- { src: 'templates/foo.j2', dest: '/etc/splat/foo.conf' }
- { src: 'templates/bar.j2', dest: '/etc/splat/bar.conf' }
notify:
- restart fooserv
Note that since we have tasks that take more than one unique argument, we don't just say "item
" in the 'template:
' line, but use with_items
with a hash (dictionary) variable. You can also keep it a little shorter by using lists, if you like. This is a stylistic preference:
- name: template everything for fooserv
template: src={{item.0}} dest={{item.1}}
with_items:
- [ 'templates/foo.j2', '/etc/splat/foo.conf' ]
- [ 'templates/bar.j2', '/etc/splat/bar.conf' ]
notify:
- restart fooserv
Of course we could also define the list you were walking over in another file, like a "groupvars/webservers
" file to define all the variables needed for the webservers
group, or a YAML file loaded from the "varsfiles
" directive inside the playbook. Look how this can clean up if we do.
- name: template everything for fooserv
template: src={{item.src}} dest={{item.dest}}
with_items: {{fooserv_template_files}}
notify:
- restart fooserv