Ansible仅为匹配某些变量的主机运行playbook

时间:2016-09-16 07:20:26

标签: ansible

我有一个我想在RHEL 6服务器上执行的剧本。我知道我可以把

when: ansible_distribution == "RedHat" and ansible_distribution_major_version == 6

整个剧本中的每一项任务,但这对我来说似乎效率很低。

是不是有办法将整本剧本限制在这些机器上,这样我就不必把这一行放到每一项任务中?

我认为它甚至可以更快地执行,因为它不需要在每个任务中检查服务器是否为RedHat 6。

另外,我认为最有效的方法是将RHEL 6服务器列表放在一边,只在它们上面执行这个剧本,因为Ansible并没有真正缓存这些信息,所以它总会有连接到所有服务器只是为了确定它们是RHEL还是版本6?

2 个答案:

答案 0 :(得分:3)

includewith_first_found

一起使用
- include: "{{ include_path }}"
  with_first_found:
   - "{{ ansible_distribution }}.yml"
   - "{{ ansible_os_family }}.yml"
   - "default.yml"
  loop_control:
    loop_var: include_path

更新:添加loop_var以防止可能的item变量冲突。

答案 1 :(得分:0)

处理此问题的一种策略是在主任务文件中包含一个任务文件,其中包含特定于此类分发版本的任务:

- include: "{{ ansible_distribution }}-{{ ansible_distribution_major_version }}.yml"

文件tasks/RedHat-6.yml将包含特定于RHEL6的所有任务。

如果您希望在不支持发布时您的剧本失败,您可以执行以下操作:

- include: RedHat6.yml
  when: ansible_distribution == "RedHat" and ansible_distribution_major_version == 6

- fail:
    msg: "Distribution not supported"
    when: ansible_distribution != "RedHat" or whatever conditions you want