如何在add_host中引用hostvars时遍历Ansible资源清册
我想动态创建一个内存资源清册,它是一个标准资源清册的过滤器,只包括安装了特定服务的主机。过滤后的库存将在后续播放中使用 因此,我确定安装服务的主机的IP地址如何在add_host中引用hostvars时遍历Ansible资源清册,ansible,Ansible,我想动态创建一个内存资源清册,它是一个标准资源清册的过滤器,只包括安装了特定服务的主机。过滤后的库存将在后续播放中使用 因此,我确定安装服务的主机的IP地址 - name: find where the service is installed win_service: name: "{{ service }}" register: service_info 这将返回一个布尔值“exists”。使用此值作为条件,将尝试添加运行服务的主机 - name: create filte
- name: find where the service is installed
win_service:
name: "{{ service }}"
register: service_info
这将返回一个布尔值“exists”。使用此值作为条件,将尝试添加运行服务的主机
- name: create filtered in memory inventory
add_host:
name: "{{ ansible_host }}"
when: service_info.exists
添加主机模块绕过播放主机循环,仅对播放中的所有主机运行一次,因此,只有在添加主机运行的主机是安装了服务的主机时,此模块才起作用
- name: find where the service is installed
win_service:
name: "{{ service }}"
register: service_info
下面试图强制add_host在资源清册中的主机之间进行迭代,但是似乎没有将HostVar和service_info.exists传递给add_host,因此条件“when”检查始终返回false
- name: create filtered in memory inventory
add_host:
name: "{{ ansible_host }}"
when: service_info.exists
with_items: "{{ ansible_play_batch }}"
有没有一种方法可以通过主机及其hostvars将\u主机添加为迭代器 我建议在
add_host
之前创建一个tasks,在executor上创建一个临时文件,其中包含与条件匹配的服务器列表,然后在模块add_host
中循环该文件
我以前问过的例子
---
- hosts: servers
tasks:
- name: find where the service is installed
win_service:
name: "{{ service }}"
register: service_info
- name: write server name in file on control node
lineinfile:
path: /tmp/servers_foo.txt
state: present
line: "{{ inventory_hostname }}"
delegate_to: 127.0.0.1
when: service_info.exists
- name: assign target to group
add_host:
name: "{{ item }}"
groups:
- foo
with_lines: cat /tmp/servers_foo.txt
delegate_to: 127.0.0.1