在运行Ansible剧本的机器上让ansible跳过运行剧本

时间:2020-03-28 00:46:14

标签: ansible ansible-inventory

如何构造剧本,以免在运行Ansible的计算机上执行单个剧本?

例如,如果我有一个简单的两人游戏剧本:

- name: Patch and reboot
  hosts: all
  gather_facts: true

  tasks:
  - name: Fully patch system
    package:
      name: "*"
      state: latest
    become: true
    register: patchstatus

  - name: Reboot if patched
    reboot:
    become: true
    when: patchstatus is changed

但是我不希望重新启动在运行Ansible的计算机上运行时触发。

我知道维护得更好的库存不会使我的Ansible系统与其他系统一起使用,但这是一个实验室,我希望我能每晚夜间启动一个简单的剧本-我宁愿不重启我的Ansible剧本(至少直到它是最后一个重新启动为止。

简而言之,我正在寻找一个预定义的变量,因此我可以使用一个简单的when: ansible_hostname != ansible_execution_server来跳过播放。 (假设ansible_execution_server是执行ansible-playbook的系统的名称。)

然后重新启动部分可能是这样的:

  - name: Reboot if patched
    reboot:
    become: true
    when:
      - patchstatus is changed
      - ansible_hostname != ansible_execution_server

2 个答案:

答案 0 :(得分:1)

如果您在运行Playbook时未将现有清单文件作为目标,则Implicit Localhost将您的工作站作为目标。

您遇到的行为是因为全局hosts变量设置为all。您可能知道,它指定每个任务应在清单中的所有主机上运行。

如果您不希望重新启动在运行Playbook的计算机上触发,则需要确保将其排除在外。这通常是通过清单文件中的组来完成的。

我对使用Ansible库存文件比较熟悉,而且从未遇到过使用其中一个添加了您在描述最后一段中描述的限制的情况。

首先,here is the documentation用于Ansible库存文件。我知道Ansible文档非常冗长。但是Ansible的许多更好的工作都是细微的,如果您通常在文档中搜索特定的实现信息,则可能会错过很多上下文。我建议您先阅读整个文档,然后再继续阅读。

然后,像这样构建清单文件:

[hardware]
my.router.name
my.switch.name
my.computer.name
my.first.server
my.second.server
my.third.server

[networking]
my.router.name
my.switch.name
my.second.server

[servers]
my.first.server
my.second.server
my.third.server

[computers]
my.computer.name
wife.computer.name

[instances:children]
my.router.name
my.switch.name
my.computer.name
wife.computer.name
my.first.server
my.second.server
my.third.server

在此示例中,您总共定义了7个设备。它们出现在您的children部分中。从那里,您可以派生不同的主机组。例如,在这里,我创建了hardwarenetworkingserverscomputers组。

假设您要使用Playbook重新启动所有个人计算机。然后,将第2行设置为hosts: computers。如果您想重新引导所有服务器和所有网络设备,则可以将其设置为以下形式:hosts: networking:servers

如果您希望除my.computer.name之外的所有设备进行补丁和重启,则可以这样编写Playbook:

- hosts: hardware:networking:servers:wife.computer.name
  gather_facts: true
  become: true

  tasks:
    - package:
        name: "*"
        state: latest
      register: patchstatus

    - reboot:
      when: patchstatus is changed

让我知道这是否有帮助,或者我错过了您的问题。 Ansible使用起来很有趣,所以我总是很乐意为您提供帮助。

答案 1 :(得分:1)

仅在当前主机名等于localhost或当前主机是ansible控制器主机的FQDN时跳过(基本上,第二个条件仅在您在hosts文件中显式定义了ansible控制器的fqdn时适用)

- name: Patch and reboot
  hosts: all
  gather_facts: true

  tasks:
  - name: Fully patch system
    package:
      name: "*"
      state: latest
    become: true
    register: patchstatus

  - name: Reboot if patched
    reboot:
    become: true
    when: 
      - patchstatus is changed
      - inventory_hostname != 'localhost' or inventory_hostname != 'ansible_controller_fqdn'