本文整理汇总了Python中ansible.runner.Runner类的典型用法代码示例。如果您正苦于以下问题:Python Runner类的具体用法?Python Runner怎么用?Python Runner使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Runner类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: run
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()
示例2: execute
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: run
def run(
self,
module_name="shell",
module_args="",
timeout=10,
forks=10,
pattern="*",
become=False,
become_method="sudo",
become_user="root",
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
示例4: network_verify
def network_verify():
heat_config_runner = Runner(host_list='hosts',
module_name='network_check',
remote_user='heat-admin',
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']
示例5: get_local_facts
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"]
示例6: on_ok
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(','))
示例7: run_task_call_callback
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()
示例8: execute
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()
示例9: show_template
def show_template(host, path, gather_facts=True,
inventory_file=None, password_file=None):
inventory = get_inventory(inventory_file, password_file)
setup_cache = get_gathered_facts(host, inventory) if gather_facts else {}
# Show the template
runner = Runner(
inventory=inventory,
setup_cache=setup_cache,
)
host_vars = runner.get_inject_vars(host)
print template_from_file('.', path, host_vars)
示例10: check_health
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))
示例11: _run
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'])
示例12: _run
def _run(self):
self.start = datetime.now()
self.save()
# initial jobs
for host in Inventory(ANSIBLE_INVENTORY).list_hosts(self.inventory):
self.job_set.add(Job(host = host, cmd = self.cmd,
start = datetime.now()))
self.save()
runner = Runner(module_name = 'shell', module_args = self.cmd,
pattern = self.inventory, sudo = self.sudo,
forks = ANSIBLE_FORKS, host_list = ANSIBLE_INVENTORY)
_, poller = runner.run_async(time_limit = WORKER_TIMEOUT)
now = time.time()
while True:
if poller.completed or time.time() - now > WORKER_TIMEOUT: # TIMEOUT
break
results = poller.poll()
results = results.get('contacted')
if results:
for host, result in results.items():
job = self.job_set.get(host = host)
job.end = result.get('end')
job.rc = result.get('rc')
job.stdout = result.get('stdout')
job.stderr = result.get('stderr')
job.save()
time.sleep(1)
jobs_timeout = filter(lambda job: job.rc is None, self.job_set.all()) # rc is None
jobs_failed = filter(lambda job: job.rc, self.job_set.all()) # rc > 0
for job in jobs_timeout:
job.rc = 1
job.stderr = 'JOB TIMEOUT' # marked as 'TIMEOUT'
job.save()
self.rc = (jobs_timeout or jobs_failed) and 1 or 0
self.end = datetime.now()
self.save()
self.done()
示例13: run
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
示例14: run
def run(self, module_name='shell', module_args='', timeout=10, forks=10, pattern='*', become=False, become_method='sudo', become_user='root', 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
示例15: run
def run(self, module_name='shell', module_args='', timeout=10, forks=10, pattern='*',
become=False, become_method='sudo', become_user='root', 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