Skip to main content
 首页 » 编程设计

python之Ansible:如何将任务的结果通知 python 脚本

2025年05月04日14luoye11

我有一个简单的剧本来从共享中获取文件并将其复制到远程 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 某项任务的结果,即它是失败了还是通过了。谢谢

请您参考如下方法:

您可以通过 configuration 设置 stdout_callback = json文件或环境变量 ANSIBLE_STDOUT_CALLBACK。
ansible-playbook 会将巨大的 json 文件和执行结果打印到标准输出。