首页 > 解决方案 > 在特定主机上执行 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,虽然没有其他想法。将不胜感激任何帮助!

标签: ansible

解决方案


还有更多选择。

  1. 运行一次块中的第一个任务并将inventory_hostname 放入一个变量中。在没有第一个主机的情况下运行循环中的下一个任务。例如
- 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

推荐阅读