如何将主机从剧本的“任务”中排除,我将在运行剧本时从用户那里获取“主机名”作为参数

时间:2019-08-05 23:07:58

标签: ansible

基本上,清单主机列表上有6个节点,我想一次停止5个主机上的服务,最后一次停止一个。 而且最后一个主机不会每次都一样,我要用户在触发剧本时输入该主机名作为参数。

这是我所做的,但“!”在委托_至选项中不起作用。

- name: Action on processor - stop
  shell: ./all.ksh "{{ Action }}"
  args:
   chdir: "/local"
  register: action_result_stop_inactive
  #delegate_to: UAT:!"{{ active_server }}"
  when: parameter == "stop"
  notify:
   - "If action is to stop the service"

- name: Action on processor - stop
  shell: ./all.ksh "{{ Action }}"
  args:
   chdir: "/local"
  register: action_result_stop_active
  delegate_to: "{{ active_server }}"
  when: parameter == "stop"
  notify:
   - "If action is to stop the service"

- name: Action on processor - status, start, restart
  shell: ./all.ksh "{{ Action }}"
  args:
   chdir: "/local"
  register: action_result
  when: parameter == "status" or parameter == "start" or parameter == "restart"
  notify:
   - "if action is status or start or restart"

处理程序:

- name: If action is to start service or to query status of service
  debug:
    msg: "{{ action_result.stdout }}"
  when: action_result is defined
  listen:
   - "if action is status or start or restart"

- name: If action is to stop the service
  debug:
    msg: "Stop service: {{item}}"
  with_items:
   - "{{ action_result_stop_inactive.stdout }}"
   - "{{ action_result_stop_active.stdout }}"
  when: action_result_stop_inactive is defined or action_result_stop_active is defined
  listen:
   - "If action is to stop the service"

我试图一次性执行./all.ksh在主机列表中的所有节点上停止,“ active_consumer”节点(也是主机列表的一部分)除外 和 然后执行./all.ksh在“ active_consumer”节点上停止

2 个答案:

答案 0 :(得分:0)

一个简单的方法是在有条件时附加到您的对象上。如果“ active_server”是您在命令行上提供的最终用户,则可以将时间更改为此:

when: parameter == "stop" and inventory_hostname != active_server

然后在下一个任务上将其更改为:

when: parameter == "stop" and inventory_hostname == active_server

此外,如果您要在清单中当前所在的主机之外的其他主机上运行任务,则仅需要delegeate_to行。因此,在您的示例中,第二个委托命令将在“ active_server”上运行同一命令6次。因此,除非您要这样做,否则就可以省略该行。

答案 1 :(得分:0)

  

我想一次停止5台主机上的服务,最后一次停止一台

很容易,您可以使用serial命令,该命令将一次遍历清单5个主机:

- hosts: '{{ inventory }}'
  serial: 5
  tasks:
  - name: Action on processor - stop

您可以使用one at last并使用外部变量或delegate_to之类的set_fact,例如{{ singe_host }}。比起您的代码,您可以根据需要进行操作。