ansible needs new magic vars instrument

ansible is very nice ,but when I write a common role for different operation ( mac,centos,ubuntu), I found it is difficult to reuse codes. thou i write code like:

  • action: homebrew name=$item state=present
    with_items: …
    when: ansible_os_family == ‘Darwin’
  • action: apt pkg=$item
    with_items: …
    when: ansible_os_family == ‘Debian’
  • action: yum …
    with_items: …
    when: ansible_os_family == ‘RedHat’

the example maybe too simple, but when we want implement complex condition logic ,like (different version, different architecture ,different register var with and/or combining …),then the code will be all filled with when when when
so i think it need a new vars instrument . and (imop) as a data structured tools , group_vars host_vars is too simple.
the vars instrument such as:

[ansible_os_familly==“Darwin”]
package: “homebrew”
state: “present”
base_pkgs:

  • ntp
  • git

    [ansible_os_familly==“Darwin” && ansible_os_familly==“Debian” ]

[ansible_os_familly==“Debian” && “ansible_distribution_version”== “10.2” && “ansible_machine”==“x86_64” ]

[fact_XX == “XX” && register XX == “XX”]

then write code will turn into write define data,the code above can write with action: ${package} pkg=$item state=${state} with_item: ${base_pkgs}
it is declarative programming? :slight_smile: the instrument is not too difficult ,but it can implement self describe and complex logic,the code will be reusable

sorry for my poor english.

Take a look at the ‘group_by’ module, which allows you to easily do make up groups where common conditions are true.

I think it does exactly what you want without the repeated ‘when’ things, and makes a lot nicer output.

thanks for response .i have tried group_by module,but it seems can’t used in roles and vars, just works for playbook’s task
maybe you can enahce it ,such as:

vars/main.yml:
group_by: $ansible_os_family:

  • Darwin:
    pack: “XXX”

Take a look at https://github.com/ansible/ansible-examples/tree/master/riak.
I think I'm doing something very similar to what you want. My role
structure for the riak role is as follows:

riak
├── common
│ ├── files
│ ├── handlers
│ ├── tasks
│ ├── templates
│ └── vars
├── redhat
│ ├── handlers
│ ├── tasks
│ └── templates
└── ubuntu
    ├── files
    ├── tasks
    └── templates
each subrole has

I have a bootstrap role that calls group_by module to group the the
systems by OS type the playbook looks like this:

It is not true that you can’t use group_by in roles.

However, group_by is a task, and not a variable, so you need to read the documentation a bit more :slight_smile: