Pass parameter/argument to (generic) template

Hello,

I want to create a generic template which can be reused for several task, but this also need to have a parametrer/variable but how to pass this variable (task specific) to my template, an example (real one) :

My template :

<VirtualHost *:80>
ServerName {{ site.server_name }}
<Directory “/var/www/{{ site.site_name }}/”>
Options FollowSymLinks

DocumentRoot /var/www/{{ site.site_name }}
ErrorLog ${APACHE_LOG_DIR}/error_{{ site.site_name }}.log
LogLevel warn
CustomLog ${APACHE_LOG_DIR}/access_{{ site.site_name }}.log combined env=!Local

My variable is here site, and can be defined like this :

adminer:
site_name: adminer
server_name: dbadmin.domain.fr

Or like this :

phpinfo:
site_name: phpinfo
server_name: phpinfo.domain.fr

I want to pass those 2 variables to the template but in 2 differents tasks, I imagine something like this :

  • name: Paramétrage du virtualhost
    template: src=vhost_adminer.j2
    dest=/etc/apache2/sites-available/{{ adminer.site_name }}
    owner=root
    group=root
    mode=0644
    site=adminer

For the 2 tasks.

But it doesn’t work.

failed: [127.0.0.1] => {“failed”: true, “item”: “”}
msg: this module requires key=value arguments

I know I can use the with_item and pass a list to my template but I need to use the template in 2 differents tasks with 2 differents variable, so no with_items.

Any idea ?

Thanks a lot

You should use parameterized roles in this case.

http://ansibleworks.com/docs/playbooks_roles.html#id5

Thanks for the answer but is there a other way, because I prefer to let the 2 tasks in the same role.

Hi there,

We were faced with what seems like a similar problem recently. I couldn’t find any information online about how to solve it, but was lucky enough to be given a pointer by somebody on the IRC channel. I thought that I would blog our solution so that it’s available for others faced with a similar task.

You can find that post here: http://danrough.net/2013/11/27/iterating-an-ansible-task-using-a-dictionary-object-of-variables/

If there are any elements of the blog that you think could be improved do let me know, I’d be keen to make the blog as clear as possible for all those that are looking for a solution in the future.

Dan.