How to use the copy mode in python API.

38 views
Skip to first unread message

PP letter

unread,
Aug 30, 2016, 4:28:22 PM8/30/16
to Ansible Project
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
from collections import namedtuple
from ansible.parsing.dataloader import DataLoader
from ansible.vars import VariableManager
from ansible.inventory import Inventory
from ansible.playbook.play import Play
from ansible.executor.task_queue_manager import TaskQueueManager
from ansible.plugins.callback import CallbackBase

# Create a callback object so we can capture the output
class 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()] = result


def ansibleRun(host_list,module,cmd):
   
Options = namedtuple('Options',
                         ['connection',
                          'module_path',
                          'forks',
                          'remote_user',
                          'private_key_file',
                          'ssh_common_args',
                          'ssh_extra_args',
                          'sftp_extra_args',
                          'scp_extra_args',
                          'become',
                          'become_method',
                          'become_user',
                          'verbosity',
                          'check'
                         ]
                       
)

   
# initialize needed objects
    variable_manager = VariableManager()
    loader
= DataLoader()
    options
= Options(  connection='smart',
                        module_path=None,
                        forks=100,
                        remote_user=None,
                        private_key_file=None,
                        ssh_common_args=None,
                        ssh_extra_args=None,
                        sftp_extra_args=None,
                        scp_extra_args=None,
                        become=None,
                        become_method=None,
                        become_user=None,
                        verbosity=None,
                        check=False
                     )

    passwords
= dict()

   
# create inventory and pass to var manager
    inventory = Inventory(loader=loader, variable_manager=variable_manager, host_list=host_list)
    variable_manager
.set_inventory(inventory)

   
# create play with tasks
    play_source =  dict(
           
name = "Ansible Play",
            hosts = host_list,
            gather_facts = 'no',
            tasks = [ dict(action=dict(module=module, args=dict(cmd=cmd))) ]
       
)
    play
= Play().load(play_source, variable_manager=variable_manager, loader=loader)

   
# actually run it
    tqm = None
    callback = ResultsCollector()
   
try:
        tqm
= TaskQueueManager(
               
inventory=inventory,
                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()

    results_raw
= {'success': {}, 'failed': {}, 'unreachable': {}}
   
#print ("success ***********")
    for host, result in callback.host_ok.items():
        results_raw
['success'][host] =  ('{} >>> {}'.format(host, result._result['stdout']))

   
#print ("failed *******")
    for host, result in callback.host_failed.items():
        results_raw
['failed'][host] = ('{} >>> {}'.format(host, result._result['msg']))

   
#print ("unreachable *********")
    for host, result in callback.host_unreachable.items():
        results_raw
['unreachable'][host] = ('{} >>> {}'.format(host, result._result['msg']))
   
return results_raw

if __name__ == '__main__':
    host_list
= ['10.14.86.177', '10.14.86.178']
   
module='command'
    cmd='uptime'
    print (ansibleRun(host_list,module,cmd))
i want use copy.
if __name__ == '__main__':
    host_list = ['10.14.86.177', '10.14.86.178']
    # module="command"
    module="copy"
    # cmd="uptime"
    cmd="src=/opt/scripts dest=/opt/"
    print ansibleRun(host_list,module,cmd)

error:
{'failed': {'10.14.86.177': '10.14.86.177 >>> src (or content) and dest are required', '10.14.86.178': '10.14.86.178 >>> src (or content) and dest are required'}, 'success': {}, 'unreachable': {}}

how to use other modules. 





Reply all
Reply to author
Forward
0 new messages