Ansible: copy file depending on hostname or role

Solution 1:

There are many ways to do this. Simplest:

- name: Copy file.role1 to host1
  copy: src=file.role1 dest=/somewhere/file
  when: inventory_hostname == "host1"
- name: Copy file.role2 to host2
  copy: src=file.role2 dest=/somewhere/file
  when: inventory_hostname == "host2"

Alternative, more compact:

- name: Copy file to host
  copy: src=file.{{ inventory_hostname }} dest=/somewhere/file

Or, using a template:

- name: Copy file to host
  template: src=file dest=/somewhere/file

where the template can be something like this:

{% if inventory_hostname == "host1" %}
{% include "file1" %}
{% endif %}
...

If you want different files in different roles, why don't you simply put this:

- name: Copy file.role1 to file
  copy: src=file.role1 dest=/somewhere/file

in each role's code?

There is no preferred way to do it - it depends on what you are actually trying to accomplish.