我有一个简单的手册来从共享中获取文件并将文件复制到远程Windows客户端:
- name: Test chocolatey module
hosts: win_clones
vars_files:
- /fullpath/hosts_vars
tasks:
- name: Fetching and copying the file on the client ...
win_get_url:
url: 'ftp://172.20.0.5/choco-repo/{{ item }}'
dest: 'C:\Test\{{ item }}'
with_items: "{{ clients[machine].to_install }}"
我使用子进程从python脚本运行此游戏:
for i in clients:
machine = "machine="
limit = "--limit="
an2 = subprocess.Popen(["ansible-playbook", "fetch.yml","-e", machine+i, limit+i], cwd='/home/diego/work/gitl_repo/ansible-software-deployment')
an2.wait()
当任务因任何原因失败时,我可以在终端中看到:
TASK [Fetching and copying the file on the client ...] *************************
failed: [cl1] (item=banana) => {"failed": true, "item": "banana", "msg": "Error downloading ftp://172.20.0.5/.....
是否可以将此信息传递给我的python脚本?换句话说,我怎么能告诉python某个任务的结果,即它是否失败或是否通过。谢谢
答案 0 :(得分:4)
您可以通过configuration文件或env变量stdout_callback = json
设置ANSIBLE_STDOUT_CALLBACK
ansible-playbook
将打印带有执行结果的巨大json文件到stdout。
答案 1 :(得分:3)
您可以从Python API运行playbook(虽然它的代码更多,Ansible并不正式支持外部调用者)。使用Python API 2.0中的示例作为基线,而不是加载播放,加载剧本:
from ansible.playbook import Playbook
playbook = Playbook(loader).load('fetch.yml' loader=loader, variable_manager=variable_manager)
然后替换
result = tqm.run(play)
这个
for play in playbook.get_plays():
result = tqm.run(play)
您需要进行一些调整以使其在上面的for循环中多次迭代,但这是框架。