在多个服务器上循环执行命令后重新启动服务

时间:2020-05-21 18:55:53

标签: ansible

我在这里戳了一下,但没有看到与我要完成的任务完全匹配的东西,所以去了。

因此,我整理了第一本Ansible剧本,该剧本针对一个或多个指定IP地址打开或关闭一个或多个主机的防火墙上的一个或多个端口。到目前为止效果很好。但是我要做的是在给定主机的所有任务完成后重启防火墙服务(当然没有错误)。

注意:hostvars/localhost引用仅将来自用户的vars_prompt输入保留在该任务上方的任务列表中。我将提示数​​据存储在hosts: localhost中,根据用户输入的内容建立动态主机列表,然后有一个单独的任务列表来实际执行工作。

所以:

- name: Execute remote firewall-cmd for each host in "dynamically created host group"
  hosts: dynamically_created_host_list
  gather_facts: no
  tasks:

    - set_fact:
        hostList: "{{hostvars['localhost']['hostList']}}"

    - set_fact:
        portList: "{{hostvars['localhost']['portList']}}"

    - set_fact:
        portStateRequested: "{{hostvars['localhost']['portStateRequested']}}"

    - set_fact:
        portState: "{{hostvars['localhost']['portState']}}"

    - set_fact:
        remoteIPs: "{{hostvars['localhost']['remoteIPs']}}"

    - name: Invoke firewall-cmd remotely
      firewalld:

         .. module-specific stuff here ...

      with_nested:
        - "{{ remoteIPs.split(',') }}"
        - "{{ portList.split(',') }}"
      register: requestStatus

在脚本的原始版本中,该脚本只为1个IP地址的1个主机提供1个端口,而我只是这样做:

    - name: Reload firewalld
      when: requestStatus.changed
      systemd:
      name: firewalld
      state: reloaded

但是由于嵌套,我认为这在这里不太容易实现。例如。假设我要为10个不同主机上的1.1.1.1远程IP地址打开端口9999。假设第5台主机由于某种原因出错。那时我可能不想重新启动防火墙服务。

实际上,现在我考虑了一下,我想在这种情况下,防火墙配置中将有4个新条目,而由于错误而没有6个新条目。现在,我想知道是否需要跟踪成功情况,并且在Playbook中有一个rescue块来备份确实通过的条目。

Grrr ....有什么想法吗?抱歉,这是Ansible的新功能。另外,我讨厌YAML这样的事情。 :D

谢谢您的指导。

1 个答案:

答案 0 :(得分:0)

在我看来,您所寻找的就是Ansible的电话handlers

我们已经提到过,模块应该是幂等的,并且可以在 他们对远程系统进行了更改。剧本认识到这一点 并具有可用于响应变化的基本事件系统。

这些“通知”操作在每个任务块结束时触发 在剧本中,即使由发出通知,也只会触发一次 多个不同的任务。

例如,多个资源可能表明apache需要 重新启动,因为他们更改了配置文件,但是apache会 只能反弹一次,以避免不必要的重启。

请注意,handlers只是一对

  1. 一项或多项任务的notify属性
  2. 处理程序,其name与您上面提到的notify属性匹配

所以您的剧本应该看起来像

- name: Execute remote firewall-cmd for each host in "dynamically created host group"
  hosts: dynamically_created_host_list
  gather_facts: no
  tasks:  
    # set_fact removed for concision

    - name: Invoke firewall-cmd remotely
      firewalld:
        #   .. module-specific stuff here ...
      with_nested:
        - "{{ remoteIPs.split(',') }}"
        - "{{ portList.split(',') }}"
      notify: Reload firewalld

handlers:
  - name: Reload firewalld
    systemd:
      name: firewalld
      state: reloaded