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

Use Ansible task output as hostlist in another task or play

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

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

问:"hosts:(上一局的主机列表)"

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