在另一个任务或播放中使用 Ansible 任务输出作为主机列表

问题描述

我正在尝试运行一个能够动态抓取主机的剧本。我们目前有一个脚本,它根据输入参数抓取主机并输出到标准输出,类似于:

host1
host2
host3
host4

有没有办法让这些信息在剧中使用

- name: Prep
  hosts: localhost
  gather_facts: False
  tasks:
    - name: Grab Host List
      shell: somecommand.py
      register: hostlist
      changed_when: False
      always_run: yes

- name: Do something on Hosts from the prevIoUs play
  hosts: (host list from prevIoUs play)
  gather_facts: False
  tasks:
    - name: Do something on Hosts from the prevIoUs task
      shell: BlahBlah.sh

解决方法

问:主持人:(上一场比赛的主持人名单)

A:使用 add_host 并创建新的主机组,例如

- name: Prep
  hosts: localhost
  gather_facts: False
  tasks:
    - name: Grab Host List
      shell: somecommand.py
      register: hostlist
      changed_when: False
      always_run: yes
    - add_host:
        hostname: "{{ item }}"
        groups: new_group
      loop: "{{ hostlist.stdout_lines }}"

- name: Do something on Hosts from the previous play
  hosts: new_group
  gather_facts: False
  tasks:
    - name: Do something on Hosts from the previous task
      shell: BlahBlah.sh