【问题标题】:Ansible run playbook only for hosts that match some variablesAnsible 仅为匹配某些变量的主机运行剧本
【发布时间】:2016-09-16 07:20:26
【问题描述】:

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

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

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

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

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

另外,我认为最高效的性能方法是将 RHEL 6 服务器列表存储在一边,并仅在它们上执行此剧本,因为 Ansible 并没有真正缓存这些信息,所以它总是必须连接所有服务器只是为了弄清楚它们是否是 RHEL 和版本 6?

【问题讨论】:

  • 下面有一个很好的答案,但您说得对,最好的方法是将库存中的操作系统作为组进行跟踪。

标签: ansible


【解决方案1】:

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 变量冲突。

【讨论】:

    【解决方案2】:

    解决这个问题的一个策略是在主任务文件中包含一个任务文件,其中包含特定于分发版本的任务:

    - 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
    

    【讨论】:

    • 太好了,有没有办法捕捉“未知分布”,这样 ansible 就不会产生某种文件未找到运行时错误并导致一切失败?
    • 可能是这样的:- include: unknown_distribution.yml when: not {{ ansible_distribution }} is defined。但我不确定 Ansible 在无法确定分布时返回什么。
    猜你喜欢
    • 2021-12-28
    • 1970-01-01
    • 2020-08-16
    • 2017-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-21
    相关资源
    最近更新 更多