2016-12-14 105 views
1

我将Ansible与Python和MySQL DB集成。我的用例的一部分是给Ansible一个组名称,将该组名称发送给执行db读取的python,并返回与该组名称对应的IP列表。 为了测试我想ping返回的IP。在Python的Ansible中动态分配hosts属性

这是我达到同样的剧本:

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 

我想设置存储在ip_listhosts:的第二个上场,但没有任何成功的值。我得到的错误是没有匹配的主机。下面是运行时硬编码部分注释的输出。忽略脚本的格式。

PLAY [run a cmd] *************************************************************** 

TASK [setup] ******************************************************************* 
ok: [localhost] 

TASK [runs a python script with a parameter] *********************************** 
changed: [localhost] 

TASK [set_fact] **************************************************************** 
ok: [localhost] 

TASK [debug] ******************************************************************* 
ok: [localhost] => { 
    "hostvars['localhost']['ip_list']": [ 
     "127.0.0.1", 
     "54.147.177.9" 
    ] 
} 

PLAY [png the hosts returned] ************************************************** 
skipping: no hosts matched 

PLAY RECAP ********************************************************************* 
localhost     : ok=4 changed=1 unreachable=0 failed=0 

从我读,我应该能够访问一个发挥声明的变量在使用hostvars另一出戏。任何帮助表示赞赏。

回答

1

一些试验和错误的测试后,我认为这应该为你工作:

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

而且似乎这是一个已知的问题:pass array as "hosts" in playbook #16051和解决方法。

+0

谢谢!它为我工作。你能解释一下“join”的含义吗,因为从python返回的值已经被逗号分隔了吗? – shshnk

+0

'ip_list'输入是一个逗号分隔的字符串,但它被转换为列表对象,所以'ip_list'是一个列表对象,'ip_list | join(',')'将其转换为字符串。 – techraf