예제 #1
0
 def run(self, module_name='shell', module_args='', timeout=10, forks=10, pattern='*',
         become=False, become_method='sudo', become_user='******', become_pass=''):
     """
     run module from andible ad-hoc.
     module_name: ansible module_name
     module_args: ansible module args
     """
     if module_name == 'user_check':
         hoc = Runner(module_name='command',
                      module_args='cat /etc/group',
                      timeout=timeout,
                      inventory=self.inventory,
                      pattern=pattern,
                      forks=forks,
                      become=become,
                      become_method=become_method,
                      become_user=become_user,
                      become_pass=become_pass
                      )
         temp_result= hoc.run()
         output = temp_result['contacted']
         temp_list = list()
         for node in output.keys():
             lines = output[node]['stdout'].split('\n')
             groups = [line.split(':')[0] for line in lines]
             if module_name == 'user_check':
                 for g in groups:
                     temp_name = 'name='+g
                     if module_args.split(' ')[0] == temp_name:
                         temp_list.append(node)
                         break
         if temp_list:
             return {'flag': False, 'nodes': temp_list}
     
     hoc = Runner(module_name=module_name,
                  module_args=module_args,
                  timeout=timeout,
                  inventory=self.inventory,
                  pattern=pattern,
                  forks=forks,
                  become=become,
                  become_method=become_method,
                  become_user=become_user,
                  become_pass=become_pass
                  )
     self.results_raw = hoc.run()
     logger.debug(self.results_raw)
     return self.results_raw
예제 #2
0
    def execute(self, *args, **kwargs):
        """ Puts args and kwargs in a way ansible can understand. Calls ansible
        and interprets the result.

        """

        assert self.is_hooked_up, "the module should be hooked up to the api"

        self.module_args = module_args = self.get_module_args(args, kwargs)

        runner_args = {
            'module_name': self.module_name,
            'module_args': module_args,
            'pattern': 'all',
            'host_list': self.api.servers
        }
        runner_args.update(self.api.runner_args)

        runner = Runner(**runner_args)

        log.info(u'running {}'.format(u'- {module_name}: {module_args}'.format(
            module_name=self.module_name,
            module_args=module_args
        )))
        start = datetime.utcnow()

        results = runner.run()
        log.info(u'took {} to complete'.format(datetime.utcnow() - start))

        return RunnerResults(self.parse_results(results))
예제 #3
0
    def run(self, task, module_args, module_name="shell", timeout=10, forks=10, pattern='*', su_user=None):

        runner = Runner(
            module_name=module_name,
            module_args=module_args,
            inventory=self.inventory,
            pattern=pattern,
            forks=forks,
            timeout=timeout,
            su=su_user and True or False,
            su_user=su_user,
        )
        self.result_raw['celery_task_id'] = task
        tmp = runner.run()

        for (host, value) in tmp.get('contacted', {}).iteritems():
            if value.get('invocation', {}).get('module_name', '') != 'setup':
                if not self.result_raw.get(host):
                    self.result_raw[host] = {}
                self.result_raw[host]['result'] = value
        for (host, value) in tmp.get('dark', {}).iteritems():
            if not self.result_raw.get(host):
                    self.result_raw[host] = {}
            value['outcome'] = 'dark'
            self.result_raw[host]['result'] = value

        log_redis(self.result_raw)
        return self.result_raw
예제 #4
0
파일: jumserver.py 프로젝트: xiaomatech/ops
 def run(self,
         module_name='shell',
         module_args='',
         timeout=10,
         forks=10,
         pattern='*',
         become=False,
         become_method='sudo',
         become_user='******',
         become_pass='',
         transport='paramiko'):
     """
     run module from andible ad-hoc.
     module_name: ansible module_name
     module_args: ansible module args
     """
     hoc = Runner(
         module_name=module_name,
         module_args=module_args,
         timeout=timeout,
         inventory=self.inventory,
         private_key_file=private_key_file,
         pattern=pattern,
         forks=forks,
         become=become,
         become_method=become_method,
         become_user=become_user,
         become_pass=become_pass,
         transport=transport)
     self.results_raw = hoc.run()
     logger.debug(self.results_raw)
     return self.results_raw
예제 #5
0
파일: jumserver.py 프로젝트: xiaomatech/ops
    def run(self,
            command,
            module_name="command",
            timeout=10,
            forks=10,
            pattern=''):
        """
        run command from andible ad-hoc.
        command  : 必须是一个需要执行的命令字符串, 比如
                 'uname -a'
        """
        data = {}

        if module_name not in ["raw", "command", "shell"]:
            raise CommandValueError(
                "module_name",
                "module_name must be of the 'raw, command, shell'")
        hoc = Runner(
            module_name=module_name,
            module_args=command,
            timeout=timeout,
            inventory=self.inventory,
            pattern=pattern,
            forks=forks, )
        self.results_raw = hoc.run()
예제 #6
0
 def run(self,
         module_name='shell',
         module_args='',
         timeout=10,
         forks=10,
         pattern='*',
         become=False,
         become_method='sudo',
         become_user='******',
         become_pass='',
         transport='paramiko'):
     """
     run module from andible ad-hoc.
     module_name: ansible module_name
     module_args: ansible module args
     """
     hoc = Runner(module_name=module_name,
                  module_args=module_args,
                  timeout=timeout,
                  inventory=self.inventory,
                  pattern=pattern,
                  forks=forks,
                  become=become,
                  become_method=become_method,
                  become_user=become_user,
                  become_pass=become_pass,
                  transport=transport)
     self.results_raw = hoc.run()
     logging.debug(self.results_raw)
     return self.results_raw
예제 #7
0
class AnsibleTask(Task):
    def __init__(self,
                 name,
                 host_list,
                 module_name,
                 module_args,
                 pattern='*',
                 inject=None):
        super(AnsibleTask, self).__init__(name, inject=inject, provides=name)
        self.name = name
        self.host_list = host_list
        self.logger = logging.getLogger("AnsibleTask")
        self.runner = Runner(host_list=host_list,
                             pattern=pattern,
                             module_name=module_name,
                             module_args=module_args)

    def execute(self):
        self.logger.info('Executing Task ' + self.name + ':')
        self.logger.debug('\tHosts: ' + ','.join(self.host_list))
        self.logger.debug('\tModule_name: ' + self.runner.module_name)
        self.logger.debug('\tModule_args: ' + self.runner.module_args)
        self.logger.debug('\tPattern: ' + self.runner.pattern)
        result = self.runner.run()
        self.logger.debug('Result of Task ' + self.name + ':')
        self.logger.debug(json.dumps(result, indent=4, sort_keys=True))
        return result
예제 #8
0
    def run(self,
            module_arg,
            module_name="shell",
            complex_args=None,
            timeout=10,
            forks=10,
            pattern='*'):
        """
        run command from andible ad-hoc.

        Args:
            module_arg: ansible module argument
            complex_args: complex structure argument
            module_name: which module want to use, default use shell
            timeout: set runner api
            forks: see runner api
            pattern: set runner api
        """
        hoc = Runner(
            module_name=module_name,
            module_args=module_arg,
            complex_args=complex_args,
            timeout=timeout,
            inventory=self.inventory,
            pattern=pattern,
            forks=forks,
            module_path=C.DEFAULT_MODULE_PATH,
        )
        return_data = hoc.run()
        logger.info(return_data)
        return AnsibleResult(return_data)
예제 #9
0
 def run(
     self,
     module_name="shell",
     module_args="",
     timeout=10,
     forks=10,
     pattern="*",
     become=False,
     become_method="sudo",
     become_user="******",
     become_pass="",
 ):
     """
     run module from andible ad-hoc.
     module_name: ansible module_name
     module_args: ansible module args
     """
     hoc = Runner(
         module_name=module_name,
         module_args=module_args,
         timeout=timeout,
         inventory=self.inventory,
         pattern=pattern,
         forks=forks,
         become=become,
         become_method=become_method,
         become_user=become_user,
         become_pass=become_pass,
     )
     self.results_raw = hoc.run()
     logger.debug(self.results_raw)
     return self.results_raw
예제 #10
0
    def run(self,
            command,
            module_name="command",
            timeout=10,
            forks=10,
            pattern=''):
        """
        run command from andible ad-hoc.
        command  : 必须是一个需要执行的命令字符串, 比如 
                 'uname -a'
        """
        data = {}

        if module_name not in ["raw", "command", "shell"]:
            raise CommandValueError(
                "module_name",
                "module_name must be of the 'raw, command, shell'")
        hoc = Runner(
            module_name=module_name,
            module_args=command,
            timeout=timeout,
            inventory=self.inventory,
            pattern=pattern,
            forks=forks,
        )
        self.results_raw = hoc.run()
예제 #11
0
파일: hosts.py 프로젝트: zhangyage/abck
def get_alias_info(pattern, remote_user):
    runner = Runner(module_name='setup',
                    module_args='',
                    pattern=pattern,
                    inventory=autils.get_inventory(g.mysql_db),
                    remote_user=remote_user)
    info = runner.run()

    results = {}

    if info['contacted']:
        if not info['contacted'][pattern].has_key('failed'):
            facts = info['contacted'][pattern]['ansible_facts']
            # Server info
            results['system_vendor'] = facts['ansible_system_vendor']
            results['product_name'] = facts['ansible_product_name']
            results['product_serial'] = facts['ansible_product_serial']
            # System info
            results['distribution'] = facts['ansible_distribution']
            results['distribution_version'] = facts[
                'ansible_distribution_version']
            results['architecture'] = facts['ansible_architecture']
            results['kernel'] = facts['ansible_kernel']
            # Cpu info
            results['processor_count'] = facts['ansible_processor_count']
            results['processor_cores'] = facts['ansible_processor_cores']
            results['processor_vcpus'] = facts['ansible_processor_vcpus']
            results['processor_threads_per_core'] = facts[
                'ansible_processor_threads_per_core']
            results['processor'] = set(facts['ansible_processor'])
            # Swap info
            results['swaptotal_mb'] = facts['ansible_swaptotal_mb']
            results['swapfree_mb'] = facts['ansible_swapfree_mb']
            # Mem info
            results['memtotal_mb'] = facts['ansible_memtotal_mb']
            results['memfree_mb'] = facts['ansible_memfree_mb']
            # Disk info
            results['devices'] = facts['ansible_devices']
            # Mount info
            results['mounts'] = facts['ansible_mounts']
            # Ip info
            results['default_ipv4'] = facts['ansible_default_ipv4']
            results['all_ipv4_addresses'] = facts['ansible_all_ipv4_addresses']
            # Software
            results['selinux'] = facts['ansible_selinux']
            results['python_version'] = facts['ansible_python_version']
        else:
            facts = info['contacted'][pattern]
            results['failed'] = facts['failed']
            results['msg'] = facts['msg']
    elif info['dark']:
        facts = info['dark'][pattern]
        results['failed'] = facts['failed']
        results['msg'] = facts['msg']
    else:
        results['failed'] = False
        results['msg'] = "host not found"

    return results
예제 #12
0
    def run(self):
        """Run ansible command and process results

        Run ansible command, returning output processed with
        self.process_results.
        """
        results = Runner.run(self)
        return self.process_results(results, show_colors=self.show_colors)
예제 #13
0
    def run(self):
        """Run ansible command and process results

        Run ansible command, returning output processed with
        self.process_results.
        """
        results = Runner.run(self)
        return self.process_results(results, show_colors=self.show_colors)
예제 #14
0
def run_module(module_name):
    subset = request.args.get('subset')

    r = Runner(host_list=app.config['ANSIBLE_HOSTS'], module_name=module_name, subset=subset)
    res = r.run()

    response = make_response(json.dumps(res), 200)
    response.headers['Content-Type'] = 'application/json'
    return response
예제 #15
0
    def _run(self, *module_args, **complex_args):
        """Execute an ansible adhoc command returning the results in a AdHocResult object."""
        # Assemble module argument string
        if True:
            module_args = ' '.join(module_args)
        else:
            if module_args:
                complex_args.update(dict(_raw_params=' '.join(module_args)))

        # Assert hosts matching the provided pattern exist
        hosts = self.options['inventory_manager'].list_hosts()
        no_hosts = False
        if len(hosts) == 0:
            no_hosts = True
            warnings.warn(
                "provided hosts list is empty, only localhost is available")

        self.options['inventory_manager'].subset(self.options.get('subset'))
        hosts = self.options['inventory_manager'].list_hosts(
            self.options['host_pattern'])
        if len(hosts) == 0 and not no_hosts:
            raise ansible.errors.AnsibleError(
                "Specified hosts and/or --limit does not match any hosts")

        # Log the module and parameters
        log.debug("[%s] %s: %s" % (self.options['host_pattern'],
                                   self.options['module_name'], complex_args))

        # Build module runner object
        kwargs = dict(
            inventory=self.options.get('inventory_manager'),
            pattern=self.options.get('host_pattern'),
            module_name=self.options.get('module_name'),
            module_args=module_args,
            complex_args=complex_args,
            transport=self.options.get('connection'),
            remote_user=self.options.get('user'),
            module_path=self.options.get('module_path'),
            become=self.options.get('become'),
            become_method=self.options.get('become_method'),
            become_user=self.options.get('become_user'),
        )

        # Run the module
        runner = Runner(**kwargs)
        results = runner.run()

        # Log the results
        log.debug(results)

        if 'dark' in results and results['dark']:
            raise AnsibleConnectionFailure("Host unreachable",
                                           dark=results['dark'],
                                           contacted=results['contacted'])

        # Success!
        return AdHocResult(contacted=results['contacted'])
예제 #16
0
def network_verify():
    heat_config_runner = Runner(host_list='hosts',
                                module_name='network_check',
                                remote_user='******',
                                become=True,
                                module_args='')
    run_result = heat_config_runner.run()
    heat_config = {}
    for k, v in run_result['contacted'].items():
        heat_config[k] = v['ansible_facts']
예제 #17
0
def network_verify():
    heat_config_runner = Runner(host_list='hosts',
                                module_name='network_check',
                                remote_user='******',
                                become=True,
                                module_args='')
    run_result = heat_config_runner.run()
    heat_config = {}
    for k, v in run_result['contacted'].items():
        heat_config[k] = v['ansible_facts']
예제 #18
0
파일: commands.py 프로젝트: href/suitable
    def execute(self, servers, arguments):
        runner_args = {
            'module_name': self.module_name,
            'module_args': arguments,
            'pattern': 'all',
            'host_list': ' '.join(servers)
        }

        runner = Runner(**runner_args)
        return runner.run()
예제 #19
0
 def run(self):
     runner = Runner(
         module_name=self.module_name,
         module_args=self.module_args,
         pattern=self.pattern,
         forks=10
     )
     self.results_raw = runner.run()
     data = json.dumps(self.results_raw, indent=4)
     print data
 def get_local_facts(self):
     """
     Loads the Ansible local facts in self.facts
     Calls the Ansible Python API v1 'setup' module
     """
     inventory = Inventory(["localhost"])
     runner = Runner(module_name='setup', module_args='',
                            pattern='localhost', inventory=inventory,
                            transport="local")
     result = runner.run()
     self.facts = result["contacted"]["localhost"]["ansible_facts"]
예제 #21
0
 def on_ok(self, host, res):
     module = res['invocation']['module_name']
     print "%s ok:[%s]" % (str(datetime.now()), host)
     if 'git' == module and host == self.inventory.get_hosts()[0].name:
         r = Runner(module_name='shell', 
             module_args='find . -name "Test*java" -exec basename {} \; | sed -e "s/.java//g" | tr "\n" "," chdir=$target_dir/%s' % self.module,
             remote_user=self.remote_user, private_key_file=self.private_key_file,
             inventory=self.inventory,
             pattern=host) 
         res = r.run()
         gen_test_lists(self.build_dir, self.inventory, res['contacted'][host]['stdout'].split(','))
예제 #22
0
def run_task_call_callback(module_name, module_path, inventory_path, subset, extra_vars, event_callback):
    callbacks_object = EmitterCallbacks(event_callback)
    runner = Runner(
        module_name     =   module_name,
        module_path     =   module_path,
        inventory       =   Inventory(inventory_path),
        module_args     =   extra_vars,
        callbacks       =   callbacks_object,
        subset          =   subset
    )
    results = runner.run()
    callbacks_object.on_complete()
예제 #23
0
파일: commands.py 프로젝트: href/suitable
    def execute(self, servers, arguments):
        runner_args = {
            'module_name': self.module_name,
            'module_args': arguments,
            'pattern': 'all',
            'host_list': ' '.join(
                servers
            )
        }

        runner = Runner(**runner_args)
        return runner.run()
예제 #24
0
파일: check.py 프로젝트: seocam/copr
def check_health(opts, vm_name, vm_ip):
    """
    Test connectivity to the VM

    :param vm_ip: ip address to the newly created VM
    :raises: :py:class:`~backend.exceptions.CoprWorkerSpawnFailError`: validation fails
    """
    # setproctitle("check VM: {}".format(vm_ip))

    log = get_redis_logger(opts, "vmm.check_health.detached", "vmm")

    runner_options = dict(
        remote_user=opts.build_user or "root",
        host_list="{},".format(vm_ip),
        pattern=vm_ip,
        forks=1,
        transport=opts.ssh.transport,
        timeout=opts.vm_ssh_check_timeout
    )
    connection = Runner(**runner_options)
    connection.module_name = "shell"
    connection.module_args = "echo hello"

    result = {
        "vm_ip": vm_ip,
        "vm_name": vm_name,
        "msg": "",
        "result": "OK",
        "topic": EventTopics.HEALTH_CHECK
    }
    err_msg = None
    try:
        res = connection.run()
        if vm_ip not in res.get("contacted", {}):
            err_msg = (
                "VM is not responding to the testing playbook."
                "Runner options: {}".format(runner_options) +
                "Ansible raw response:\n{}".format(res))

    except Exception as error:
        err_msg = "Failed to check  VM ({})due to ansible error: {}".format(vm_ip, error)
        log.exception(err_msg)

    try:
        if err_msg:
            result["result"] = "failed"
            result["msg"] = err_msg
        rc = get_redis_connection(opts)
        rc.publish(PUBSUB_MB, json.dumps(result))
    except Exception as err:
        log.exception("Failed to publish msg health check result: {} with error: {}"
                      .format(result, err))
 def get_local_facts(self):
     """
     Loads the Ansible local facts in self.facts
     Calls the Ansible Python API v1 'setup' module
     """
     inventory = Inventory(["localhost"])
     runner = Runner(module_name='setup',
                     module_args='',
                     pattern='localhost',
                     inventory=inventory,
                     transport="local")
     result = runner.run()
     self.facts = result["contacted"]["localhost"]["ansible_facts"]
예제 #26
0
파일: v1.py 프로젝트: jlaska/pytest-ansible
    def _run(self, *module_args, **complex_args):
        """Execute an ansible adhoc command returning the results in a AdHocResult object."""
        # Assemble module argument string
        if True:
            module_args = ' '.join(module_args)
        else:
            if module_args:
                complex_args.update(dict(_raw_params=' '.join(module_args)))

        # Assert hosts matching the provided pattern exist
        hosts = self.options['inventory_manager'].list_hosts()
        no_hosts = False
        if len(hosts) == 0:
            no_hosts = True
            warnings.warn("provided hosts list is empty, only localhost is available")

        self.options['inventory_manager'].subset(self.options.get('subset'))
        hosts = self.options['inventory_manager'].list_hosts(self.options['host_pattern'])
        if len(hosts) == 0 and not no_hosts:
            raise ansible.errors.AnsibleError("Specified hosts and/or --limit does not match any hosts")

        # Log the module and parameters
        log.debug("[%s] %s: %s" % (self.options['host_pattern'], self.options['module_name'], complex_args))

        # Build module runner object
        kwargs = dict(
            inventory=self.options.get('inventory_manager'),
            pattern=self.options.get('host_pattern'),
            module_name=self.options.get('module_name'),
            module_args=module_args,
            complex_args=complex_args,
            transport=self.options.get('connection'),
            remote_user=self.options.get('user'),
            module_path=self.options.get('module_path'),
            become=self.options.get('become'),
            become_method=self.options.get('become_method'),
            become_user=self.options.get('become_user'),
        )

        # Run the module
        runner = Runner(**kwargs)
        results = runner.run()

        # Log the results
        log.debug(results)

        if 'dark' in results and results['dark']:
            raise AnsibleConnectionFailure("Host unreachable", dark=results['dark'], contacted=results['contacted'])

        # Success!
        return AdHocResult(contacted=results['contacted'])
예제 #27
0
파일: check.py 프로젝트: tedwardia/copr
def check_health(opts, vm_name, vm_ip):
    """
    Test connectivity to the VM

    :param vm_ip: ip address to the newly created VM
    :raises: :py:class:`~backend.exceptions.CoprWorkerSpawnFailError`: validation fails
    """
    # setproctitle("check VM: {}".format(vm_ip))

    log = get_redis_logger(opts, "vmm.check_health.detached", "vmm")

    runner_options = dict(remote_user=opts.build_user or "root",
                          host_list="{},".format(vm_ip),
                          pattern=vm_ip,
                          forks=1,
                          transport=opts.ssh.transport,
                          timeout=opts.vm_ssh_check_timeout)
    connection = Runner(**runner_options)
    connection.module_name = "shell"
    connection.module_args = "echo hello"

    result = {
        "vm_ip": vm_ip,
        "vm_name": vm_name,
        "msg": "",
        "result": "OK",
        "topic": EventTopics.HEALTH_CHECK
    }
    err_msg = None
    try:
        res = connection.run()
        if vm_ip not in res.get("contacted", {}):
            err_msg = ("VM is not responding to the testing playbook."
                       "Runner options: {}".format(runner_options) +
                       "Ansible raw response:\n{}".format(res))

    except Exception as error:
        err_msg = "Failed to check  VM ({})due to ansible error: {}".format(
            vm_ip, error)
        log.exception(err_msg)

    try:
        if err_msg:
            result["result"] = "failed"
            result["msg"] = err_msg
        rc = get_redis_connection(opts)
        rc.publish(PUBSUB_MB, json.dumps(result))
    except Exception as err:
        log.exception(
            "Failed to publish msg health check result: {} with error: {}".
            format(result, err))
예제 #28
0
 def run(self):
     runner = Runner(
         host_list = self.host_list,
         module_name = self.module_name,
         module_args = self.module_args,
         pattern = self.pattern,
         forks = self.forks
     )
     datastructure = runner.run()
     if len(datastructure['dark']) == 0 and len(datastructure['contacted']) == 0:
         results = {"error": "No hosts found"}
     else:
         results = datastructure
     return results
예제 #29
0
 def run(self, module_name='shell', module_args='', timeout=10, forks=10, pattern='*', become=False, become_method='sudo', become_user='******', become_pass=''):
     hoc = Runner(module_name=module_name,
                  module_args=module_args,
                  timeout=timeout,
                  inventory=self.inventory,
                  pattern=pattern,
                  forks=forks,
                  become=become,
                  become_user=become_user,
                  become_method=become_method,
                  become_pass=become_pass
                  )
     self.result_raw = hoc.run()
     loginfo.info(self.result_raw)
     return self.result_raw
예제 #30
0
 def run(self, module_name='shell', module_args='', timeout=10, forks=2, pattern='*',
         become=False, become_method='sudo', become_user='******', become_pass='', transport='paramiko'):
     hoc = Runner(module_name=module_name,
                  module_args=module_args,
                  timeout=timeout,
                  inventory=self.inventory,
                  pattern=pattern,
                  forks=forks,
                  become=become,
                  become_method=become_method,
                  become_user=become_user,
                  become_pass=become_pass,
                  transport=transport
                  )
     self.results_raw = hoc.run()
     return self.results_raw
예제 #31
0
파일: agent.py 프로젝트: haxsaw/actuator
    def _perform_task(self, task, logfile=None):
        task.fix_arguments()
        if isinstance(task, (NullTask, StructuralTask)):
            task.perform()
        else:
            cmapper = get_mapper(_agent_domain)
            processor = cmapper[task.__class__]()
#             task.get_task_role().fix_arguments()
#             task_host = task.get_task_host()
            task_host = self._get_run_host(task)
            if task_host is not None:
                msg = "Task {} being run on {}".format(task.name, task_host)
                if logfile:
                    logfile.write("{}\n".format(msg))
                hlist = [task_host]
            else:
                raise ExecutionException("We need a default execution host")
            kwargs = processor.make_args(task, hlist)
            kwargs["forks"] = 1
            kwargs["timeout"] = 20
            if logfile:
                logfile.write(">>>Params:\n{}\n".format(json.dumps(kwargs)))
            
#             msg = json.dumps(kwargs)
#             runner_file = find_file(json_runner.__file__)
#             args = [sys.executable,
#                     runner_file]
#             proc = subprocess32.Popen(args, stdin=subprocess32.PIPE,
#                                       stdout=subprocess32.PIPE,
#                                       stderr=subprocess32.PIPE)
#             proc.stdin.write(msg)
#             proc.stdin.flush()
#             proc.stdin.close()
#             reply = proc.stdout.read()
#             proc.wait()
#             if logfile:
#                 logfile.write(">>>Result:\n{}\n".format(reply))
#             result = json.loads(reply)
            
            runner = Runner(**kwargs)
            result = runner.run()
            
            if logfile:
                logfile.write(">>>Result:\n{}\n".format(json.dumps(result)))
            processor.result_check(task, result, logfile=logfile)
        return
예제 #32
0
 def run_module(self, inventory, source, sshpass, sudopass):
     runner_cb = BattleschoolRunnerCallbacks()
     runner_cb.options = self.options
     runner_cb.options.module_name = self.module_name()
     module_args = self.module_args(source)
     #TODO: get workstation from options
     runner = Runner(
         pattern='workstation',
         module_name=self.module_name(),
         module_path=self.options.module_path,
         module_args=module_args,
         inventory=inventory,
         callbacks=runner_cb,
         timeout=self.options.timeout,
         transport=self.options.connection,
         #sudo=self.options.sudo,
         sudo=False,
         sudo_user=self.options.sudo_user,
         sudo_pass=sudopass,
         check=self.options.check,
         diff=self.options.diff,
         private_key_file=self.options.private_key_file,
         remote_user=self.options.remote_user,
         remote_pass=sshpass,
         forks=self.options.forks)
     try:
         results = runner.run()
         for result in results['contacted'].values():
             if 'failed' in result or result.get('rc', 0) != 0:
                 display("ERROR: failed source type (%s) '%s': %s" %
                         (self.type(), module_args, result['msg']),
                         stderr=True,
                         color='red')
                 sys.exit(2)
         if results['dark']:
             display("ERROR: failed source type (%s) '%s': DARK" %
                     (self.type(), module_args),
                     stderr=True,
                     color='red')
             sys.exit(2)
     except errors.AnsibleError, e:
         # Generic handler for ansible specific errors
         display("ERROR: %s" % str(e), stderr=True, color='red')
         sys.exit(1)
예제 #33
0
 def run_module(self, inventory, source, sshpass, sudopass):
     runner_cb = BattleschoolRunnerCallbacks()
     runner_cb.options = self.options
     runner_cb.options.module_name = self.module_name()
     module_args = self.module_args(source)
     #TODO: get workstation from options
     runner = Runner(
         pattern='workstation',
         module_name=self.module_name(),
         module_path=self.options.module_path,
         module_args=module_args,
         inventory=inventory,
         callbacks=runner_cb,
         timeout=self.options.timeout,
         transport=self.options.connection,
         #sudo=self.options.sudo,
         become=False,
         become_method="sudo",
         become_user=self.options.sudo_user,
         become_pass=sudopass,
         check=self.options.check,
         diff=self.options.diff,
         private_key_file=self.options.private_key_file,
         remote_user=self.options.remote_user,
         remote_pass=sshpass,
         forks=self.options.forks
     )
     try:
         results = runner.run()
         for result in results['contacted'].values():
             if 'failed' in result or result.get('rc', 0) != 0:
                 display("ERROR: failed source type (%s) '%s': %s" % (self.type(), module_args, result['msg']),
                         stderr=True, color='red')
                 sys.exit(2)
         if results['dark']:
             display("ERROR: failed source type (%s) '%s': DARK" % (self.type(), module_args),
                     stderr=True, color='red')
             sys.exit(2)
     except errors.AnsibleError, e:
         # Generic handler for ansible specific errors
         display("ERROR: %s" % str(e), stderr=True, color='red')
         sys.exit(1)
예제 #34
0
    def run(self, module_arg, module_name="shell", timeout=10, forks=10, pattern='*'):
        """
        run command from andible ad-hoc.

        Args:
            module_arg: ansible module argument
            module_name: which module want to use, default use shell
            timeout: set runner api
            forks: see runner api
            pattern: set runner api
        """
        hoc = Runner(module_name=module_name,
                     module_args=module_arg,
                     timeout=timeout,
                     inventory=self.inventory,
                     pattern=pattern,
                     forks=forks,
                     )
        self.results_raw = hoc.run()
        return AnsibleResult(self.results_raw)
예제 #35
0
파일: hosts.py 프로젝트: zhangyage/abck
def add_sshkey(alias):
    form = AddSSHKeyForm()
    if form.validate_on_submit():
        remote_user = form.remote_user.data
        remote_pass = form.remote_pass.data

        runner = Runner(module_name='authorized_key',
                        module_args={
                            'user': remote_user,
                            'key': open(app.config['ANSIBLE_KEY']).read()
                        },
                        pattern=alias,
                        inventory=autils.get_inventory(g.mysql_db),
                        remote_user=remote_user,
                        remote_pass=remote_pass)
        info = runner.run()
        return redirect(url_for('.index'))

    host = g.mysql_db.get('SELECT * FROM hosts WHERE alias=%s', alias)
    return render_template('add_sshkey.html', host=host, form=form)
예제 #36
0
def heat_config_check():
    heat_config_runner = Runner(host_list='hosts',
                                module_name='heat_config',
                                remote_user='******',
                                become=True,
                                module_args='')
    run_result = heat_config_runner.run()
    heat_config = {}
    for k, v in run_result['contacted'].items():
        heat_config[k] = v['ansible_facts']

    discoverd_data = get_discoverd_data()
    print '\n\nIronic discoverd data:'
    for hwid, data in discoverd_data.items():
        print hwid, data

    # NOTE(shadower): the entire heat_config is HUGE
    print '\n\nos-net-config input:'
    for ip, config in heat_config.items():
        print ip
        pprint.pprint(config['complete'].get('os_net_config', {}))
    pprint.pprint(heat_config)
예제 #37
0
파일: views.py 프로젝트: zhangyage/an
def add_sshkey(id=None):
    form = SshkeyForm()
    host = Host.query.get_or_404(id)
    if form.validate_on_submit():
        data = form.data
        remote_user = data["remote_user"]
        remote_password = data["remote_password"]
         
        runner = Runner(
                        module_name='authorized_key',
                        module_args={'user': remote_user,
                                     'key': open(app.config["ANSIBLE_KEY"]).read()
                                     },
                        pattern=host.ip1,
                        #inventory=autils.get_inventory(g.mysql_db),
			host_list='/root/my_app/app/host.py',
                        remote_user=remote_user,
                        remote_pass=remote_password)
        info = runner.run()
        print info 
	print  remote_user, remote_password,host.ip1,app.config["ANSIBLE_KEY"]
    return render_template("host_addsshk.html",form=form,host=host)
예제 #38
0
class AnsibleTask(Task):
    def __init__(self,
                 name,
                 host_list,
                 module_name,
                 module_args,
                 pattern='*',
                 inject=None):
        super(AnsibleTask, self).__init__(
            name, inject=inject,
            provides=name)  #provides send out the results to engine.storage
        self.name = name
        self.host_list = host_list
        self.logger = logging.getLogger("RecoveryHandler:Base")
        self.runner = Runner(host_list=host_list,
                             pattern=pattern,
                             module_name=module_name,
                             module_args=module_args)

    def add_result_handler(self, result_handler):
        self.result_handler = result_handler

    def execute(self):
        self.logger.info('Executing Task ' + self.name + ':')
        self.logger.info('\tHosts: ' + ','.join(self.host_list))
        self.logger.info('\tModule_name: ' + self.runner.module_name)
        self.logger.info('\tModule_args: ' + self.runner.module_args)
        self.logger.info('\tPattern: ' + self.runner.pattern)
        result = self.runner.run()
        # fake_task = Runner(
        #     host_list=['10.175.150.16'],
        #     pattern= '*',
        #     module_name = 'shell',
        #     module_args='echo "Hello World"')
        # result = fake_task.run()
        self.logger.debug('Result of Task ' + self.name + ':')
        self.logger.debug(json.dumps(result, indent=4, sort_keys=True))
        self.result_handler.analyze(self.name, result)
        return result
예제 #39
0
def heat_config_check():
    heat_config_runner = Runner(host_list='hosts',
                                module_name='heat_config',
                                remote_user='******',
                                become=True,
                                module_args='')
    run_result = heat_config_runner.run()
    heat_config = {}
    for k, v in run_result['contacted'].items():
        heat_config[k] = v['ansible_facts']

    discoverd_data = get_discoverd_data()
    print '\n\nIronic discoverd data:'
    for hwid, data in discoverd_data.items():
        print hwid, data

    # NOTE(shadower): the entire heat_config is HUGE
    print '\n\nos-net-config input:'
    for ip, config in heat_config.items():
        print ip
        pprint.pprint(config['complete'].get('os_net_config', {}))
    pprint.pprint(heat_config)
예제 #40
0
    def execute(self, ansible_mod, ansible_patt, ansible_args=None):
        ret = None

        if ansible_args:
            runner_obj = Runner(
                module_name=ansible_mod,
                module_args=ansible_args,
                host_list=self.ansible_host_list,
                pattern=ansible_patt,
                become=True,
                become_user='******',
            )
        else:
            runner_obj = Runner(
                module_name=ansible_mod,
                host_list=self.ansible_host_list,
                pattern=ansible_patt,
                become=True,
                become_user='******',
            )

        ret = runner_obj.run()
예제 #41
0
파일: ansi1v.py 프로젝트: 527593036/AnsiApi
 def execute(self, ansible_mod, ansible_patt, ansible_args=None):
     ret = None
     
     if ansible_args:
         runner_obj = Runner(
                 module_name=ansible_mod,
                 module_args=ansible_args,
                 host_list=self.ansible_host_list,
                 pattern=ansible_patt,
                 become=True,
                 become_user='******',
             )
     else:
         runner_obj = Runner(
                 module_name=ansible_mod,
                 host_list=self.ansible_host_list,
                 pattern=ansible_patt,
                 become=True,
                 become_user='******',
             )
     
     ret = runner_obj.run()
예제 #42
0
class AnsibleTask(Task):
    def __init__(self, name, host_list, module_name, module_args,
                 pattern='*', inject=None):
        super(AnsibleTask, self).__init__(name, inject=inject, provides=name)
        self.name = name
        self.host_list = host_list
        self.logger = logging.getLogger("AnsibleTask")
        self.runner = Runner(host_list=host_list,
                             pattern=pattern,
                             module_name=module_name,
                             module_args=module_args)

    def execute(self):
        self.logger.info('Executing Task ' + self.name + ':')
        self.logger.debug('\tHosts: ' + ','.join(self.host_list))
        self.logger.debug('\tModule_name: ' + self.runner.module_name)
        self.logger.debug('\tModule_args: ' + self.runner.module_args)
        self.logger.debug('\tPattern: ' + self.runner.pattern)
        result = self.runner.run()
        self.logger.debug('Result of Task ' + self.name + ':')
        self.logger.debug(json.dumps(result, indent=4, sort_keys=True))
        return result
예제 #43
0
 def run_ansible(self,
                 module_name='shell',
                 module_args='',
                 ip='',
                 keyfile='',
                 pattern='all',
                 hosts_file=None,
                 become=False):
     """
     run module use ansible ad-hoc.
     Args:
         module_name (string): ansible module name
         module_args (string): ansible module arg
         ip (string): destination ip, if ip more than one, use comma split, when set this, must specify keyfile
         keyfile (string): ssh private key file path
         pattern (string): specify hosts by pattern
         hosts_file (string): hosts file path
         become (bool): if true, will run command in remote instance use root.
                        if false, user as same as current instance user(ubuntu).
     """
     logger.debug('execute ansible module: %s, args: %s in instances: %s' %
                  (module_name, module_args, ip))
     if ip:
         hoc = Runner(
             module_name=module_name,
             module_args=module_args,
             host_list=ip.split(','),
             private_key_file=keyfile,
             become=become,
         )
     else:
         inventory = Inventory(hosts_file)
         hoc = Runner(module_name=module_name,
                      module_args=module_args,
                      inventory=inventory,
                      pattern=pattern)
     self.results_raw = hoc.run()
     logger.debug('ansible results: %s' % self.results_raw)
예제 #44
0
 def run(self, module_name='shell', module_args='', timeout=10, forks=70, pattern='*',
         become=False, become_method='sudo', become_user='******', become_pass=''):
     """
     run module from andible ad-hoc.
     module_name: ansible module_name
     module_args: ansible module args
     """
     hoc = Runner(module_name=module_name,
                  module_args=module_args,
                  timeout=timeout,
                  inventory=self.inventory,
                  pattern=pattern,
                  forks=forks,
                  become=become,
                  become_method=become_method,
                  become_user=become_user,
                  become_pass=become_pass
                  )
     if module_name == 'copy':
         self.results_raw = hoc.run()
     else:
         self.results_raw = hoc.run_async(30)[1].poll()
    #logger.debug(self.results_raw)
     return self.results
예제 #45
0
 def cmdrun(self,
            module_name='shell',
            module_args='',
            timeout=30,
            forks=10,
            pattern='*',
            become=False,
            become_user='******',
            transport='paramiko'):
     '''
     执行命令
     :return:
     '''
     hoc = Runner(host_list=os.path.join(project_dir, 'temp', 'hosts'),
                  module_name=module_name,
                  module_args=module_args,
                  timeout=timeout,
                  pattern=pattern,
                  forks=forks,
                  become=become,
                  remote_user=become_user,
                  transport=transport)
     results_raw = hoc.run()
     return results_raw
예제 #46
0
    def run(self, options, args):
        ''' use Runner lib to do SSH things '''

        pattern = args[0]

        sshpass = becomepass = vault_pass = become_method = None

        # Never ask for an SSH password when we run with local connection
        if options.connection == "local":
            options.ask_pass = False
        else:
            options.ask_pass = options.ask_pass or C.DEFAULT_ASK_PASS

        options.ask_vault_pass = options.ask_vault_pass or C.DEFAULT_ASK_VAULT_PASS

        # become
        utils.normalize_become_options(options)
        prompt_method = utils.choose_pass_prompt(options)
        (sshpass, becomepass, vault_pass) = utils.ask_passwords(ask_pass=options.ask_pass, become_ask_pass=options.become_ask_pass, ask_vault_pass=options.ask_vault_pass, become_method=prompt_method)

        # read vault_pass from a file
        if not options.ask_vault_pass and options.vault_password_file:
            vault_pass = utils.read_vault_file(options.vault_password_file)

        extra_vars = utils.parse_extra_vars(options.extra_vars, vault_pass)

        inventory_manager = inventory.Inventory(options.inventory, vault_password=vault_pass)
        if options.subset:
            inventory_manager.subset(options.subset)
        hosts = inventory_manager.list_hosts(pattern)

        if len(hosts) == 0:
            callbacks.display("No hosts matched", stderr=True)
            sys.exit(0)

        if options.listhosts:
            for host in hosts:
                callbacks.display('    %s' % host)
            sys.exit(0)

        if options.module_name in ['command','shell'] and not options.module_args:
            callbacks.display("No argument passed to %s module" % options.module_name, color='red', stderr=True)
            sys.exit(1)

        if options.tree:
            utils.prepare_writeable_dir(options.tree)



        runner = Runner(
            module_name=options.module_name,
            module_path=options.module_path,
            module_args=options.module_args,
            remote_user=options.remote_user,
            remote_pass=sshpass,
            inventory=inventory_manager,
            timeout=options.timeout,
            private_key_file=options.private_key_file,
            forks=options.forks,
            pattern=pattern,
            callbacks=self.callbacks,
            transport=options.connection,
            subset=options.subset,
            check=options.check,
            diff=options.check,
            vault_pass=vault_pass,
            become=options.become,
            become_method=options.become_method,
            become_pass=becomepass,
            become_user=options.become_user,
            extra_vars=extra_vars,
        )

        import pdb
        pdb.set_trace() 
        if options.seconds:
            callbacks.display("background launch...\n\n", color='cyan')
            results, poller = runner.run_async(options.seconds)
            results = self.poll_while_needed(poller, options)
        else:
            results = runner.run()

        return (runner, results)
예제 #47
0
    def __run(self, *args, **kwargs):
        '''
        The API provided by ansible is not intended as a public API.
        '''
        # Assemble module argument string
        module_args = list()
        if args:
            module_args += list(args)
        module_args = ' '.join(module_args)

        # Assert hosts matching the provided pattern exist
        hosts = self.inventory_manager.list_hosts(self.pattern)
        if len(hosts) == 0:
            raise AnsibleNoHostsMatch("No hosts match:'%s'" % self.pattern)

        # Log the module and parameters
        log.debug("[%s] %s: %s, %s" % (self.pattern, self.module_name, module_args, kwargs))

        # Build module runner object
        kwargs = dict(
            inventory=self.inventory_manager,
            pattern=self.pattern,
            module_name=self.module_name,
            module_args=module_args,
            complex_args=kwargs,
            transport=self.options.get('connection'),
            remote_user=self.options.get('user'),
            module_path=self.options.get('module_path'),
        )

        # Handle >= 1.9.0 options
        if has_ansible_become:
            kwargs.update(dict(
                become=self.options.get('become'),
                become_method=self.options.get('become_method'),
                become_user=self.options.get('become_user'),)
            )
        else:
            kwargs.update(dict(
                sudo=self.options.get('sudo'),
                sudo_user=self.options.get('sudo_user'),)
            )

        runner = Runner(**kwargs)

        # Run the module
        results = runner.run()

        # Log the results
        log.debug(results)

        # FIXME - should command failures raise an exception, or return?
        # If we choose to raise, callers will need to adapt accordingly
        # Catch any failures in the response
        # for host in results['contacted'].values():
        #     if 'failed' in host or host.get('rc', 0) != 0:
        #         raise Exception("Command failed: %s" % self.module_name, results)

        # Raise exception if host(s) unreachable
        # FIXME - if multiple hosts were involved, should an exception be raised?
        if results['dark']:
            raise AnsibleHostUnreachable("Host unreachable", dark=results['dark'], contacted=results['contacted'])

        # No hosts contacted
        # if not results['contacted']:
        #     raise ansible.errors.AnsibleConnectionFailed("Provided hosts list is empty")

        # Success!
        # return results
        return results['contacted']
예제 #48
0
#!/bin/env python2.7
#coding:utf-8
##### code  by  mik ####
##### qiangchuan.wu ####

from ansible.runner import Runner
from ansible.inventory import Inventory

result = Runner(
    #host_list= ['127.0.0.1','123.207.86.123'],
    module_name='shell',
    module_args='cat /etc/passwd',
    inventory=Inventory(host_list=['127.0.0.1', '123.207.86.123']),

    #    resource
    #remote_user='******',
    #remote_port='22',
    #remote_pass='******',
    #pattern=   [{"hostname": "127.0.0.1119.29.205.114", "port": "81", "username": "******", "password": "******"}, ],
)

data = result.run()

print data
예제 #49
0
def run_from_json(json_msg):
    kwargs = json.loads(json_msg)
    runner = Runner(**kwargs)
    result = runner.run()
    return json.dumps(result)
예제 #50
0
 def __call__(self, argv, help):
     import ansible.constants as C
     from ansible.runner import Runner
     from ansible import callbacks
     from mr.awsome.ansible.inventory import Inventory
     from ansible import utils
     parser = utils.base_parser(
         constants=C,
         runas_opts=True,
         subset_opts=True,
         output_opts=True,
         check_opts=True,
         diff_opts=False,
         usage='aws ansible <host-pattern> [options]'
     )
     parser.remove_option('-i')
     parser.remove_option('-k')
     parser.add_option('-a', '--args', dest='module_args',
         help="module arguments", default=C.DEFAULT_MODULE_ARGS)
     parser.add_option('-m', '--module-name', dest='module_name',
         help="module name to execute (default=%s)" % C.DEFAULT_MODULE_NAME,
         default=C.DEFAULT_MODULE_NAME)
     options, args = parser.parse_args(argv)
     if len(args) == 0 or len(args) > 1:
         parser.print_help()
         sys.exit(1)
     cbs = callbacks.CliRunnerCallbacks()
     cbs.options = options
     pattern = args[0]
     patch_connect(self.aws)
     inventory_manager = Inventory(self.aws)
     if options.subset:
         inventory_manager.subset(options.subset)
     hosts = inventory_manager.list_hosts(pattern)
     if len(hosts) == 0:
         callbacks.display("No hosts matched", stderr=True)
         sys.exit(1)
     if options.listhosts:
         for host in hosts:
             callbacks.display('    %s' % host)
         sys.exit(0)
     if ((options.module_name == 'command' or options.module_name == 'shell')
             and not options.module_args):
         callbacks.display("No argument passed to %s module" % options.module_name, color='red', stderr=True)
         sys.exit(1)
     sudopass = None
     options.ask_sudo_pass = options.ask_sudo_pass or C.DEFAULT_ASK_SUDO_PASS
     sudopass = utils.ask_passwords(ask_sudo_pass=options.ask_sudo_pass)
     if options.sudo_user or options.ask_sudo_pass:
         options.sudo = True
     options.sudo_user = options.sudo_user or C.DEFAULT_SUDO_USER
     if options.tree:
         utils.prepare_writeable_dir(options.tree)
     runner = Runner(
         module_name=options.module_name, module_path=options.module_path,
         module_args=options.module_args,
         remote_user=options.remote_user,
         inventory=inventory_manager, timeout=options.timeout,
         private_key_file=options.private_key_file,
         forks=options.forks,
         pattern=pattern,
         callbacks=cbs, sudo=options.sudo,
         sudo_pass=sudopass,sudo_user=options.sudo_user,
         transport='ssh', subset=options.subset,
         check=options.check,
         diff=options.check)
     results = runner.run()
     for result in results['contacted'].values():
         if 'failed' in result or result.get('rc', 0) != 0:
             sys.exit(2)
     if results['dark']:
         sys.exit(3)
예제 #51
0
    def __call__(self, *args, **kwargs):
        '''
        Adhoc execution wrapper
        :param args: module arguments
        :param kwargs:
         kwargs[run_async]: Running async
         kwargs[time_limit]: related to async
         kwargs[forks]: amount of parallel processes
         kwargs[remote_user]: costume remote user login
         kwargs[remote_pass]: costume remote user password
         kwargs[remote_port]: costume remote port
         kwargs[transport]: support "ssh, paramiko, local"
         kwargs[become_user]: connect as sudo user
         kwargs[become_method]: set to ‘sudo’/’su’/’pbrun’/’pfexec’/’doas’
        :return: Future object in case of async, result dict in case of sync
        '''
        # Assemble module argument string
        module_args = list()
        if args:
            module_args += list(args)
        module_args = ' '.join(module_args)

        # pop async parameters
        async = kwargs.pop('run_async', False)
        time_limit = kwargs.pop('time_limit', 60)

        # Build module runner object
        options = dict(
            inventory=self.inventory_manager,
            pattern=self.pattern,
            callbacks=AnsibleRunnerCallback(),
            module_name=self.module_name,
            module_args=module_args,
            complex_args=kwargs,
            forks=kwargs.pop('forks', C.DEFAULT_FORKS),
            remote_user=kwargs.pop('remote_user', C.DEFAULT_REMOTE_USER),
            remote_pass=kwargs.pop('remote_pass', C.DEFAULT_REMOTE_PASS),
            remote_port=kwargs.pop('remote_port', None),
            transport=kwargs.pop('connection', C.DEFAULT_TRANSPORT),
        )

        if 'become_user' in kwargs:
            # Handle >= 1.9.0 options
            if has_ansible_become:
                options.update(dict(
                    become=True,
                    become_method=kwargs.pop('become_method', C.DEFAULT_BECOME_METHOD),
                    become_user=kwargs.pop('become_user', C.DEFAULT_BECOME_USER)
                ))
            else:
                options.update(dict(
                    sudo=True,
                    sudo_user=kwargs.pop('become_user', C.DEFAULT_BECOME_USER))
                )

        runner = Runner(**options)

        # Run the module
        if async:
            res, poll = runner.run_async(time_limit=time_limit)
            return _ExtendedPoll(res, poll)
        else:
            return _ExtendedPoll(runner.run(), None).poll()
예제 #52
0
                    default=200,
                    help='specify number of parallel processes to use')

args = parser.parse_args()

FORKS = args.forks
COMMAND = 'grep "^nameserver" /etc/resolv.conf | cut -d" " -f2'
PATTERN = args.pattern

inventory = Inventory('../inventory.py')
runner = Runner(forks=FORKS,
                pattern=PATTERN,
                inventory=inventory,
                module_name='shell',
                module_args=COMMAND)
results = runner.run()

if not results['dark'] and not results['contacted']:
    print('[X] No servers matched pattern, exiting')
    exit(1)

if results['dark']:
    print('[X] Some servers were not contacted:')
    for server, why in results['dark'].items():
        print('\t%s: %s' % (server, why['msg']))
    print('\n\n\n')

if not results['contacted']:
    print('[X] All servers failed, exiting')
    exit(1)
예제 #53
0
from psycopg2 import connect
import argparse

parser = argparse.ArgumentParser(description='Fetch dns config from servers and feed them in the database')
parser.add_argument('-p', '--pattern', default='*', help='limit selected hosts to an additional pattern')
parser.add_argument('-f', '--forks', type=int, default=200, help='specify number of parallel processes to use')

args = parser.parse_args()

FORKS = args.forks
COMMAND = 'grep "^nameserver" /etc/resolv.conf | cut -d" " -f2'
PATTERN = args.pattern

inventory = Inventory('../inventory.py')
runner = Runner(forks=FORKS, pattern=PATTERN, inventory=inventory, module_name='shell', module_args=COMMAND)
results = runner.run()

if not results['dark'] and not results['contacted']:
    print('[X] No servers matched pattern, exiting')
    exit(1)

if results['dark']:
    print('[X] Some servers were not contacted:')
    for server, why in results['dark'].items():
        print('\t%s: %s' % (server, why['msg']))
    print('\n\n\n')

if not results['contacted']:
    print('[X] All servers failed, exiting')
    exit(1)
예제 #54
0
#!/usr/bin/env python
from ansible.runner import Runner
import sys

username=sys.argv[1]

runner = Runner(
    module_name='shell',
    module_args='last -5 %s |cut -c40-55' % username,
    pattern='lopsa',
    forks=2
    )
ds = runner.run()

results = {}

for (hostname,result) in ds['contacted'].items():
  if not 'failed' in result:
    for line in result['stdout'].splitlines():
      results[line] = hostname
print "Last by host:\n"
for x in sorted(results):
  print "\t%s (%s)" % (x,results[x])
try:
  print "Not contacted: "
  for (hostname,result) in results['dark'].items():
    print "%s " % hostname
  print "\n"
except:
  pass
예제 #55
0
    def __run(self, *args, **kwargs):
        '''
        The API provided by ansible is not intended as a public API.
        '''
        # Assemble module argument string
        module_args = list()
        if args:
            module_args += list(args)
        module_args = ' '.join(module_args)

        # Assert hosts matching the provided pattern exist
        hosts = self.inventory_manager.list_hosts(self.pattern)
        if len(hosts) == 0:
            raise AnsibleNoHostsMatch("No hosts match:'%s'" % self.pattern)

        # Log the module and parameters
        log.debug("[%s] %s: %s, %s" %
                  (self.pattern, self.module_name, module_args, kwargs))

        # Build module runner object
        kwargs = dict(
            inventory=self.inventory_manager,
            pattern=self.pattern,
            module_name=self.module_name,
            module_args=module_args,
            complex_args=kwargs,
            transport=self.options.get('connection'),
            remote_user=self.options.get('user'),
            module_path=self.options.get('module_path'),
        )

        # Handle >= 1.9.0 options
        if has_ansible_become:
            kwargs.update(
                dict(
                    become=self.options.get('become'),
                    become_method=self.options.get('become_method'),
                    become_user=self.options.get('become_user'),
                ))
        else:
            kwargs.update(
                dict(
                    sudo=self.options.get('sudo'),
                    sudo_user=self.options.get('sudo_user'),
                ))

        runner = Runner(**kwargs)

        # Run the module
        results = runner.run()

        # Log the results
        log.debug(results)

        # FIXME - should command failures raise an exception, or return?
        # If we choose to raise, callers will need to adapt accordingly
        # Catch any failures in the response
        # for host in results['contacted'].values():
        #     if 'failed' in host or host.get('rc', 0) != 0:
        #         raise Exception("Command failed: %s" % self.module_name, results)

        # Raise exception if host(s) unreachable
        # FIXME - if multiple hosts were involved, should an exception be raised?
        if results['dark']:
            raise AnsibleHostUnreachable("Host unreachable",
                                         dark=results['dark'],
                                         contacted=results['contacted'])

        # No hosts contacted
        # if not results['contacted']:
        #     raise ansible.errors.AnsibleConnectionFailed("Provided hosts list is empty")

        # Success!
        # return results
        return results['contacted']
예제 #56
0
    def playbook_on_stats(self, stats):
        if self.disable:
            return

        history = {}

        history['stats'] = {}
        hosts = sorted(stats.processed.keys())
        for h in hosts:
            history['stats'][h] = stats.summarize(h)

        os.close(self.pipeout)
        pipein = os.fdopen(self.pipein)
        failed_at = pipein.readlines()
        self._fill_failed_at(failed_at)

        history['failed_at'] = self.failed_at

        history['roles'] = list(set([role[:role.find('|')].strip()
                                     for role in self.executed_task
                                     if role.find('|') != -1]))

        history['date'] = time.strftime("%a, %d %b %Y %H:%M:%S +0000",
                                        time.gmtime())

        history['ansible_version'] = ansible.utils.version("ansible")

        history['aeriscloud_version'] = ac_version

        ac_repo_path = os.path.join(aeriscloud_path, '.git')
        history['aeriscloud_commit'] = _git_repo_info(ac_repo_path)['commit']

        if os.path.isfile('.aeriscloud.yml'):
            import yaml
            with open('.aeriscloud.yml') as fd:
                history['services'] = yaml.load(fd).get('services')

        # Re-create a parser and extract all the parameters we need
        # to run ansible
        parser = ansible.utils.base_parser(
            constants=ansible.constants,
            runas_opts=True,
            subset_opts=True,
            async_opts=True,
            output_opts=True,
            connect_opts=True,
            check_opts=True,
            diff_opts=False,
            usage='%prog <host-pattern> [options]'
        )

        filtered_arguments = []
        for arg in sys.argv:
            for opt in [
                'limit',
                'inventory-file',
                'private-key',
                'user',
                'connection'
            ]:
                if arg.startswith('--' + opt + '='):
                    filtered_arguments.append(arg)

        if '-i' in sys.argv:
            inventory_index = sys.argv.index('-i')
            if inventory_index > -1:
                filtered_arguments.append(sys.argv[inventory_index])
                filtered_arguments.append(sys.argv[inventory_index + 1])

        (options, args) = parser.parse_args(filtered_arguments)

        inventory_manager = ansible.inventory.Inventory(options.inventory)
        if options.subset:
            inventory_manager.subset(options.subset)

        # Create the command to append the history data to the file
        command = "echo '" + json.dumps(history) + "' >> ~/.provision"

        # Disable the callback plugins to have no output
        ansible.callbacks.callback_plugins = []
        runner = Runner(
            inventory=inventory_manager,
            subset=options.subset,
            module_name='raw',
            module_args=command,
            private_key_file=options.private_key_file,
            remote_user=options.remote_user,
            transport=options.connection,
            callbacks=None
        )
        runner.run()