Ansible:根据主机名或角色复制文件


9

根据主机名复制文件的最佳方法是什么?

我需要将内容不同但文件名相同的文件复制到多台计算机上。

我有几个文件:

file.role1
file.role2
file.role3

根据主机名和/或角色,我想file.roleX将其复制并重命名为file

谢谢。

Answers:


31

有很多方法可以做到这一点。最简单的:

- 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"

替代方案,更紧凑:

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

或者,使用模板:

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

模板可以是这样的:

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

如果您想以不同的角色使用不同的文件,为什么不简单地输入以下内容:

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

在每个角色的代码中?

没有首选的方法可以执行此操作-这取决于您实际要完成的工作。


5
TIMTOWTDI的奖励积分!
tedder42 2014年

谢谢-实际上,我是根据操作系统和体系结构使用不同的apt.sources文件的,而不会造成混乱或角色过多/库存文件过多。我在清单文件中的主机名后面输入了一个变量:sources_list = debian,这导致sources.list.debian复制到sources.list。
Tuinslak
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.