在特定主机上执行ansible任务

时间:2020-08-05 11:58:41

标签: ansible

我有一群主持人:

[hosts]
host1
host2
host3

我只想在给定的主机上运行一些脚本(这并不重要),然后在第二个任务中,运行另一个脚本,但是仅在剩下的两个主机上运行,​​上一个任务是没有执行。

- name: Task to be run on any host from given group of host
  shell: sth
  .
  .

- name: Task to be run on the other 2 hosts from the same group
  shell: sth else
  .
  .

例如,我知道可以实现。使用serial,但没有其他想法。不胜感激!

1 个答案:

答案 0 :(得分:1)

还有更多选择。

  1. 运行块中的第一个任务一次,然后将清单主机名放入变量中。在没有第一台主机的情况下运行循环中的下一个任务。例如
- name: Play1
  hosts: all
  gather_facts: false
  tasks:
    - block:
        - name: Task to be run on any host from given group of host
          command: echo {{ inventory_hostname }}
          register: result_first
        - set_fact:
            first_host: "{{ inventory_hostname }}"
      run_once: true
    - name: Task to be run on the other 2 hosts from the same group
      command: echo {{ item }}
      register: result_others
      loop: "{{ groups.all|difference([first_host]) }}"
      delegate_to: "{{ item }}"
      run_once: true

    - debug:
        msg:
          - "{{ result_first.stdout }}"
          - "{{ result_others.results|map(attribute='stdout')|list }}"
      run_once: true

给予

ok: [host1] => 
  msg:
  - host1
  - - host2
    - host3

  1. 下一个选项是创建一组没有第一个主机的主机。这种方法不需要委派。例如
- name: Play2
  hosts: all
  gather_facts: false
  tasks:
    - block:
        - name: Task to be run on any host from given group of host
          command: echo {{ inventory_hostname }}
          register: result_first
        - set_fact:
            first_host: "{{ inventory_hostname }}"
        - add_host:
            name: "{{ item }}"
            groups: my_group_without_first_host
            result_first: "{{ result_first }}"
          loop: "{{ groups.all|difference([first_host]) }}"
      run_once: true

- hosts: my_group_without_first_host
  gather_facts: false
  tasks:
    - name: Task to be run on the other 2 hosts from the same group
      command: echo {{ inventory_hostname }}
      register: result_others
    - debug:
        msg:
          - "{{ result_first.stdout }}"
          - "{{ result_others.stdout }}"

给予

ok: [host2] => 
  msg:
  - host1
  - host2
ok: [host3] => 
  msg:
  - host1
  - host3
相关问题