Conditionnal include and group_by in roles

85 views
Skip to first unread message

Julien Pepy

unread,
Dec 29, 2014, 8:01:43 AM12/29/14
to ansible...@googlegroups.com
Hi,

I'm struggling to solve a classical problem : building a multi-OS role without spawning unnecessary skipped statements. I've already read a lot of discussions on the subject (Dynamic 'include:' lines?Conditional Include QuestionRoles with multiple OS versions...), but I find no satisfying solution :
  • task include with "when" statement does not really performs a conditional include, since it instantiates all tasks in the included file with an added "when" statement, so at runtime we get a lot of unnecessary skipped messages.
  • task include file name is evaluated at parsing level, before any host is even contacted, so we can't use the same trick as with include_vars.
  • the officially recommended solution, group_by, seems fine, but since we can't restrict a task to specific hosts, we can't use it in a role. It's designed to be used in a playbook, so it's not a real solution for a multi-OS role.
I think I've listed every alternative, but I may be missing something. If that's not the case, would it be possible to extend the task include statement to handle properly the when clause at runtime, depending on each host ?

Thanks for your help,

Julien

dlun...@syberisle.com

unread,
Jan 7, 2015, 11:09:15 PM1/7/15
to ansible...@googlegroups.com
I ran into the same problem and my playbooks ended up looking like this, not pretty to say the least. Since I primarily manage FreeBSD machines. I had to move quite a few of my roles to handle the singular Ubuntu system that exists. 

my-play.yml
---
- hosts: all
  gather_facts: yes
  tasks:
    - group_by:
        key: "{{ ansible_os_family | lower }}"

- hosts: freebsd
  sudo: yes
  gather_facts: no
  vars:
    os_type: freebsd
  roles:
    - multi-os-role

- hosts: debian
  sudo: yes
  gather_facts: no
  vars:
    os_type: debian
  roles:
    - multi-os-role

roles/multi-os-role/tasks/main.yml
---
- include: "{{ os_type }}.yml"

# other tasks that are common between OS'

if you have steps that need to be run in different places in your task like I did, you can make the os_type a directory and do "{{ os_type }}/step-one.yml" or "{{ os_type }}/step-two.yml".


Reply all
Reply to author
Forward
0 new messages