15

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:

file.role1
file.role2
file.role3

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

Thanks.

Tuinslak
  • 1,465
  • 8
  • 32
  • 56

1 Answers1

39

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.

grant tailor
  • 505
  • 2
  • 6
  • 13
Antonis Christofides
  • 2,598
  • 2
  • 23
  • 35
  • 6
    bonus points for [TIMTOWTDI](https://en.wikipedia.org/wiki/There%27s_more_than_one_way_to_do_it)! – tedder42 Nov 22 '14 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 '14 at 01:10