I have been using ansible for a while with the yml's and love the 
simplicity of the tool.  
Now, I have used a snippet of a script to try run various ansible tasks on 
a host via Python.

Would one of you be able to point me in the right direction to get the 
script working?  I copied it off another site and adjusted.  Ultimatly, I 
would like to send it some VARS instead.
If you have a better way of running the script, it would be great also as I 
feel this is much longer then asking python to run the ansible executable...

I believe the SSH works well as when I run the script : 

*$ ansible -i "," all -m ping -become --connection=ssh 
--user=bobvilla --ask-become-passSUDO password: | SUCCESS => 
{    "changed": false,    "ping": "pong"}*

When I run my script, it throws this error....

*$ ./runner.py*
*UP ************
*FAILED ********
*DOWN **********

Here are a few details on my env.

*$ python --version*
*Python 2.7.12*
*$ python3 --version*
*Python 3.5.2*
*$ ansible --version*
*  config file = None*
*  configured module search path = ['/home/dave/.ansible/plugins/modules', 
*  ansible python module location = 
*  executable location = /usr/local/bin/ansible*
*  python version = 3.5.2 (default, Nov 23 2017, 16:37:01) [GCC 5.4.0 

Script Bellow.

*#!/usr/bin/env python3# -*- coding: utf-8 -*-from collections import 
namedtuplefrom ansible.executor.task_queue_manager import 
TaskQueueManagerfrom ansible.inventory.manager import InventoryManagerfrom 
ansible.parsing.dataloader import DataLoaderfrom ansible.playbook.play 
import Playfrom ansible.plugins.callback import CallbackBasefrom 
ansible.vars.manager import VariableManager# Create a callback object so we 
can capture the outputclass ResultsCollector(CallbackBase):    def 
__init__(self, *args, **kwargs):        super(ResultsCollector, 
self).__init__(*args, **kwargs)        self.host_ok = {}        
self.host_unreachable = {}        self.host_failed = {}    def 
v2_runner_on_unreachable(self, result):        
self.host_unreachable[result._host.get_name()] = result    def 
v2_runner_on_ok(self, result, *args, **kwargs):        
self.host_ok[result._host.get_name()] = result    def 
v2_runner_on_failed(self, result, *args, **kwargs):        
self.host_failed[result._host.get_name()] = resultdef main():    host_list 
= ['','']    Options = namedtuple('Options', 
'check',                                     'diff'])    # required for    
sources = ','.join(host_list)    if len(host_list) == 1:        sources += 
','    # initialize needed objects    loader = DataLoader()    options = 
module_path='',                      forks=100,                      
verbosity=3,                      check=False,                      
diff=False)    passwords = dict()    # create inventory and pass to var 
manager    inventory = InventoryManager(loader=loader, sources=sources)    
variable_manager = VariableManager(loader=loader, inventory=inventory)    # 
create play with tasks    play_source = dict(        name="Ansible 
Play",        hosts=host_list,        gather_facts='yes',        
#tasks=[dict(action=dict(module='command', args=dict(cmd='tail -10 
/var/log/syslog')))]        tasks=[dict(action=dict(module='ping'))]    
)    play = Play().load(play_source, variable_manager=variable_manager, 
loader=loader)    # actually run it    tqm = None    callback = 
ResultsCollector()    try:        tqm = TaskQueueManager(            
variable_manager=variable_manager,            loader=loader,            
options=options,            passwords=passwords,        )        
tqm._stdout_callback = callback        result = tqm.run(play)    
finally:        if tqm is not None:            tqm.cleanup()    print("UP 
***********")    for host, result in callback.host_ok.items():        
print('{0} >>> {1}'.format(host, result._result['stdout']))    
print("FAILED *******")    for host, result in 
callback.host_failed.items():        print('{0} >>> {1}'.format(host, 
result._result['msg']))    print("DOWN *********")    for host, result in 
callback.host_unreachable.items():        print('{0} >>> {1}'.format(host, 
result._result['msg']))if __name__ == '__main__':    main()*

You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To post to this group, send email to ansible-project@googlegroups.com.
To view this discussion on the web visit 
For more options, visit https://groups.google.com/d/optout.

Reply via email to