How can I run a role with different variables in a loop? Or am I looking at things the wrong way

Hi,

I noticed I am repeating myself in my role’s tasks, and I am probably doing this wrong :slight_smile:

I have a role that deploys my application to server(s).

The server will have 2 applications installed on it, app1 and app2.

So my directory structure on my server looks like:

/var/www/app1/…
/var/www/app2/…

The tasks for both app1 and app2 are VERY similiar, and I am basically copying each task 2 times for example:

  • name: app1 directory exists
    file: path={{app1_path}} state=directory

  • name: app2 directory exists
    file: path={{app2_path}} state=directory

I then do the same thing for directory permissions, 2 times.

  • name: push app1 to server
    copy: src={{app1_build}}/app1.zip dest={{app1_path}}

  • name: push app2 to server
    copy: src={{app2_build}}/app2.zip dest={{app2_path}}

etc.
etc.

What I am looking for is creating a role, and then looping through a set of variables, is this possible?

psuedo code of what I want
e.g.

loop
role “role_name” app_path=$app_path, app_name=$app_name, app_filename=$app_filename
end loop

This way I can re-use my role, instead of having to repeat things so many times.

I’m sure this is possible but how can I do this with Ansible?

Thanks!

gitted,

Your approach depends on how you’re organizing your variables. Ansible (as of now) does not let you loop through roles or includes. The best way to do this is to loop in each task.

Here’s a sample:

vars:
apps:
app1:
path: /var/www/app1
build: app1.tar
app2:
path: /var/www/app2
build: app2.tar
tasks:

  • name: Ensure directories exist
    file:
    path={{item.value.path}}
    state=directory
    with_dict: apps

  • name: Push apps to server
    copy:
    src={{item.value.build}}/{{item.key}}.zip
    dest={{item.value.path}}

with_dict: apps

There are other ways to approach this as well, but this should do what you want

Chip

That makes sense, thanks.