Copying different config files depending on operating system

ansibleansible-playbookconfiguration-management

I want to distribute different config files depending on the OS version using Ansible.

I'd like to distinguish the OS version with the ansible fact ansible_distribution so that I dont have to manually assign an OS version.

The problem I have is that I don't know where to specify which version of the configuration file to use for a specific OS version.
I'd like to assign this variable inside the playbook and not in some additional variable file, since it's absolutely only used inside this playbook.
I think I'd like something like:

- ansible_distribution == "Debian"
  - vars:
    vimrc_file = "vimrc.DEBIAN"
- ansible_distribution == "Ubuntu"
  - vars:
    vimrc_file = "vimrc.UBUNTU"

but I'm not sure if Ansible works like that (or if it does if you're supposed to use it like that)

I currently use the following, which obviously is terrible for multiple reasons:

---
- hosts: servers,workstations

  tasks:
  - name: Ensure vim is installed
    apt: name=vim state=latest

  - shell: echo "vimrc.DEBIAN"
    changed_when: false
    register: vimrc
  - name: "Copy Debian vimrc file"
    copy: src=/ansible/files/{{ vimrc.stdout }} dest=/etc/vim/vimrc
    when: ansible_distribution == "Debian"
    with_items: vimrc.stdout

  - shell: echo "vimrc.UBUNTU"
    changed_when: false
    register: vimrc
  - name: "Copy Ubuntu vimrc file"
    copy: src=/ansible/files/{{ vimrc.stdout }} dest=/etc/vim/vimrc
    when: ansible_distribution == "Ubuntu"
    with_items: vimrc.stdout
...

(I'm just starting to use Ansible and I'm still trying to figure out if it's even the right tool for what I want to do, so please excuse my horrible use of Ansible)

EDIT: I just realized this is a terrible example, since I could just use

/ansible/files/vimrc.{{ ansible_distribution }}

for the file source.
How would I assign the correct variables if the file DESTINATION is different on different OS?

Best Answer

An example playbook with a list of dictionaries:

---                                           
- hosts: localhost
  connection: local

  vars:
    distribution_settings:                                 
      - distribution: "MacOSX"
        vimrc_file: "vimrc.MACOSX"
        vimrc_location: "/destination/path/on/mac"
      - distribution: "Debian"
        vimrc_file: "vimrc.DEBIAN"
        vimrc_location: "/destination/path/on/debian"     

  tasks:                                         
    - set_fact:                                      
        current_distribution_settings: "{{ distribution_settings | selectattr('distribution', 'equalto', ansible_distribution) | list }}"                                 
    - debug:
        var: current_distribution_settings[0].vimrc_file
    - debug:
        var: current_distribution_settings[0].vimrc_location

Customise to your liking.