What's the best way to copy over a file depending on a hostname?

I need to copy over files with different content but with the same filename to several machines.

I have several files:


Depending on hostname and/or role, I'd like like to copy file.roleX and rename it to file


1 Answer 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.

  • 6
    bonus points for TIMTOWTDI!
    – tedder42
    Nov 22, 2014 at 17:23
  • Thanks -- I was actually for a different apt.sources file depending on OS & architecture without creating a mess or having too many roles/a big inventory file. I went for a variable behind the hostname in the inventory file: sources_list=debian and that causes sources.list.debian to copy to sources.list.
    – Tuinslak
    Nov 23, 2014 at 1:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.