本文整理汇总了Python中ansible.runner.Runner.run方法的典型用法代码示例。如果您正苦于以下问题:Python Runner.run方法的具体用法?Python Runner.run怎么用?Python Runner.run使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ansible.runner.Runner
的用法示例。
在下文中一共展示了Runner.run方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: run
# 需要导入模块: from ansible.runner import Runner [as 别名]
# 或者: from ansible.runner.Runner import run [as 别名]
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
示例2: execute
# 需要导入模块: from ansible.runner import Runner [as 别名]
# 或者: from ansible.runner.Runner import run [as 别名]
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
# 需要导入模块: from ansible.runner import Runner [as 别名]
# 或者: from ansible.runner.Runner import run [as 别名]
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()
示例4: run
# 需要导入模块: from ansible.runner import Runner [as 别名]
# 或者: from ansible.runner.Runner import run [as 别名]
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
示例5: run
# 需要导入模块: from ansible.runner import Runner [as 别名]
# 或者: from ansible.runner.Runner import run [as 别名]
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)
示例6: network_verify
# 需要导入模块: from ansible.runner import Runner [as 别名]
# 或者: from ansible.runner.Runner import run [as 别名]
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']
示例7: get_local_facts
# 需要导入模块: from ansible.runner import Runner [as 别名]
# 或者: from ansible.runner.Runner import run [as 别名]
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"]
示例8: on_ok
# 需要导入模块: from ansible.runner import Runner [as 别名]
# 或者: from ansible.runner.Runner import run [as 别名]
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(','))
示例9: execute
# 需要导入模块: from ansible.runner import Runner [as 别名]
# 或者: from ansible.runner.Runner import run [as 别名]
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()
示例10: run_task_call_callback
# 需要导入模块: from ansible.runner import Runner [as 别名]
# 或者: from ansible.runner.Runner import run [as 别名]
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()
示例11: check_health
# 需要导入模块: from ansible.runner import Runner [as 别名]
# 或者: from ansible.runner.Runner import run [as 别名]
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))
示例12: _run
# 需要导入模块: from ansible.runner import Runner [as 别名]
# 或者: from ansible.runner.Runner import run [as 别名]
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'])
示例13: run
# 需要导入模块: from ansible.runner import Runner [as 别名]
# 或者: from ansible.runner.Runner import run [as 别名]
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
# 需要导入模块: from ansible.runner import Runner [as 别名]
# 或者: from ansible.runner.Runner import run [as 别名]
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: _perform_task
# 需要导入模块: from ansible.runner import Runner [as 别名]
# 或者: from ansible.runner.Runner import run [as 别名]
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