Parametric ansible command based on facts, how to do it

ansiblednfyum

I am updating some of my ansible playbooks to run on the latest version of Fedora, that now uses dnf by default.

Since most of my playbooks should run on CentOS as well, I would like my script to run the ansible yum command when running against a CentOS machine, and run the dnf command (new in Ansible 1.9) when running against Fedora, but using the rest of the role as-is.

In other words, I would like to write a single operation that can intelligently pick the righ command (something akin to):

- name: Install zsh
  sudo: yes
  yum|dnf: name=zsh state=latest

…rather than copy-pasting the same command twice, replacing yum with dnf in one of the two, and then implementing some logic that says wich one of the two distinct roles to run:

- name: Install zsh (yum version)
  sudo: yes
  yum: name=zsh state=latest

- name: Install zsh (dnf version)
  sudo: yes
  dnf: name=zsh state=latest

Before somebody rushes to it: I know that yum in an alias of dnf on the latest Fedora, and that I could just leave the playbook as-is… My question is not about writing CentOS/Fedora compatible playbooks, my question is about picking a different command for the same parameters depending on the target environment

Best Answer

Ansible 2 has a generic package manager now:

http://docs.ansible.com/ansible/package_module.html

For older versions you can associate package managers via facts

- name: Install packages
  with_items: package_list
  action: "{{ ansible_pkg_mgr }} state=installed name={{ item }}"

Now all you need is some logic that sets ansible_pkg_mgr to apt or yum etc and all the when logic goes away.

Looks like Ansible are also working on doing what you want in a future module.