我正在将Ansible与Python和MySQL DB集成。我的用例的一部分是给出Ansible的组名,将该组名发送给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
我正在尝试将ip_list
中存储的值设置为第二次播放的hosts:
,但没有任何成功。我得到的错误是没有匹配的主机。这是运行硬编码部分的输出。忽略脚本的格式。
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
访问另一个游戏中的一个游戏中声明的变量。任何帮助表示赞赏。
答案 0 :(得分:1)
经过一些试错测试,我认为这对您有用:
- name: ping the hosts returned
hosts: "{{ hostvars['localhost']['ip_list'] | join(',') }}"
tasks:
- debug:
这似乎是一个众所周知的问题:pass array as "hosts" in playbook #16051和解决方法。