在Ansible from Python中动态分配hosts属性

在Ansible from Python中动态分配hosts属性,ansible,ansible-playbook,Ansible,Ansible Playbook,我正在将Ansible与Python和MySQL数据库集成。我的用例的一部分是,给Ansible一个组名,将该组名发送给python,python执行db读取并返回与该组名对应的IP列表。 对于测试,我想ping返回的IP 以下是我实现同样目标的行动手册: name: run a cmd hosts: localhost connection: local tasks: name: runs a python script with a parameter shell: pyth

我正在将Ansible与Python和MySQL数据库集成。我的用例的一部分是,给Ansible一个组名,将该组名发送给python,python执行db读取并返回与该组名对应的IP列表。 对于测试,我想ping返回的IP

以下是我实现同样目标的行动手册:

name: run a cmd
hosts: localhost
connection: local
tasks:
  name: runs a python script with a parameter
      shell: python /pythonScripts/AnsibleDBRead.py <someGroupName>
      register: py_ret
    - set_fact:
       ip_list: "{{py_ret.stdout}}"
   - debug: var=hostvars['localhost']['ip_list']  # option to set messages here as well but not both together


name: png the hosts returned 
hosts: hostvars['localhost']['ip_list'] #this does not work
#hosts: [ "127.0.0.1", "54.147.177.9"] #this works same value but hardcoded
tasks: 
    - debug: var=hostvars['localhost']['ip_list']  # able to print the value

根据我所读到的内容,我应该能够使用
hostvars
访问在一个剧本或另一个剧本中声明的变量。非常感谢您的帮助。

经过一些尝试和错误测试,我认为这应该对您有用:

- name: ping the hosts returned 
  hosts: "{{ hostvars['localhost']['ip_list'] | join(',') }}"
  tasks: 
    - debug:

这似乎是一个已知的问题:和解决方法。

谢谢!这对我有用。你能解释一下“join”的意义吗,因为python返回的值已经是逗号分隔的吗?
ip_-list
input是逗号分隔的字符串,但是它被转换成了一个列表对象,所以
ip_-list
是一个列表对象,
ip_-list | join(',')
将其转换成字符串。
- name: ping the hosts returned 
  hosts: "{{ hostvars['localhost']['ip_list'] | join(',') }}"
  tasks: 
    - debug: