Linux – Ansible conditional statement based on other roles

ansibleconditionallinux

I've got the following scenario with an Ansible deployment:

  • hostX has the role common-mta and a few other roles
  • hostY has the role common-mta as well as the role package-postfix

The common-mta role copies a file (if you could have guessed, it's /etc/postfix/main.cf), but I want to restrict this based on whether a host has the role of package-postfix, rather than just restricting by hostname like I have now, e.g.:

when: not group_names == "mail"

What I'd like is something like:

when: not role_names == "package-postfix"

I think this would be much cleaner and allows me to arbitrarily add the package-postfix role to other hosts without having to modify the common-mta role at all.

Is this possible?

Edit: Navern's suggestion does not work for this particular use case; the list of roles is independent from the list of groups, and while I can do this via group, it's dirtier. Consider this, which is my actual task line:

- name: install postfix generic config if we aren't an mx, mail, or luna host
  template: src=main.cf.j2 dest=/etc/postfix/main.cf
  when: "'luna' not in group_names and 'mx' not in group_names and 'mail' not in group_names"

I'd like to replace this with:

- name: install postfix generic config if we don't have the postfix role
  template: src=main.cf.j2 dest=/etc/postfix/main.cf
  when: "'package-postfix' not in role_names"

However, role_names is not a valid variable, and so far in the documentation I can't find a variable which contains the list of roles the host is in, and not its groups. These may seem like the same thing, but in my case they're not, since the three groups I mention all share the package-postfix role. Hopefully that makes sense and I'm using Ansible correctly.

Best Answer

Actually we have role_names variable in Ansible since late 2013. Confirmed with Ansible 1.9.2. So you can simply write a conditional like this:

when: "'package-postfix' not in role_names"