Ansible: How to inform a python script about the o

2020-02-15 07:50发布

问题:

I have simple playbook to fetch and copy files from a share to remote windows clients:

- 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 }}"

I run this play from a python script using subprocess:

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()

When a task fails for whatever reason I can see that in my terminal:

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/.....

Is it possible to pass this information to my python script? In other words, How could I tell python about the outcome of a certain task, i.e. if it failed or if it went through. Thanks

回答1:

You can set stdout_callback = json via configuration file or env variable ANSIBLE_STDOUT_CALLBACK.
ansible-playbook will print huge json file with execution result to stdout.



回答2:

You can run the playbook from the Python API (though it's more code and Ansible doesn't officially support it for external callers). Use the example from Python API 2.0 as a baseline, and instead of loading a play, load a playbook:

from ansible.playbook import Playbook

playbook = Playbook(loader).load('fetch.yml' loader=loader, variable_manager=variable_manager)

Then substitute

result = tqm.run(play)

for this

for play in playbook.get_plays():
    result = tqm.run(play)

You'll need some adaptation to get it to iterate multiple times per your for loop above, but this is the framework.