本文整理汇总了Python中ansible.module_utils.network.NetworkModule.exit_json方法的典型用法代码示例。如果您正苦于以下问题:Python NetworkModule.exit_json方法的具体用法?Python NetworkModule.exit_json怎么用?Python NetworkModule.exit_json使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ansible.module_utils.network.NetworkModule
的用法示例。
在下文中一共展示了NetworkModule.exit_json方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: main
# 需要导入模块: from ansible.module_utils.network import NetworkModule [as 别名]
# 或者: from ansible.module_utils.network.NetworkModule import exit_json [as 别名]
def main():
""" Main entry point for AnsibleModule
"""
spec = dict(
config=dict(type='bool'),
config_format=dict(default='text', choices=['xml', 'text']),
transport=dict(default='netconf', choices=['netconf'])
)
module = NetworkModule(argument_spec=spec,
supports_check_mode=True)
result = dict(changed=False)
facts = module.connection.get_facts()
if '2RE' in facts:
facts['has_2RE'] = facts['2RE']
del facts['2RE']
facts['version_info'] = dict(facts['version_info'])
if module.params['config'] is True:
config_format = module.params['config_format']
resp_config = module.config.get_config(config_format=config_format)
if config_format in ['text']:
facts['config'] = resp_config
elif config_format == "xml":
facts['config'] = xml_to_string(resp_config)
facts['config_json'] = xml_to_json(resp_config)
result['ansible_facts'] = facts
module.exit_json(**result)
示例2: main
# 需要导入模块: from ansible.module_utils.network import NetworkModule [as 别名]
# 或者: from ansible.module_utils.network.NetworkModule import exit_json [as 别名]
def main():
spec = dict(
commands=dict(type='list', required=True),
wait_for=dict(type='list'),
retries=dict(default=10, type='int'),
interval=dict(default=1, type='int')
)
module = NetworkModule(argument_spec=spec,
connect_on_load=False,
supports_check_mode=True)
commands = module.params['commands']
conditionals = module.params['wait_for'] or list()
warnings = list()
runner = CommandRunner(module)
for cmd in commands:
if module.check_mode and not cmd.startswith('show'):
warnings.append('only show commands are supported when using '
'check mode, not executing `%s`' % cmd)
else:
if cmd.startswith('conf'):
module.fail_json(msg='dellos10_command does not support running '
'config mode commands. Please use '
'dellos10_config instead')
runner.add_command(cmd)
for item in conditionals:
runner.add_conditional(item)
runner.retries = module.params['retries']
runner.interval = module.params['interval']
try:
runner.run()
except FailedConditionsError:
exc = get_exception()
module.fail_json(msg=str(exc), failed_conditions=exc.failed_conditions)
except NetworkError:
exc = get_exception()
module.fail_json(msg=str(exc))
result = dict(changed=False)
result['stdout'] = list()
for cmd in commands:
try:
output = runner.get_command(cmd)
except ValueError:
output = 'command not executed due to check_mode, see warnings'
result['stdout'].append(output)
result['warnings'] = warnings
result['stdout_lines'] = list(to_lines(result['stdout']))
module.exit_json(**result)
示例3: main
# 需要导入模块: from ansible.module_utils.network import NetworkModule [as 别名]
# 或者: from ansible.module_utils.network.NetworkModule import exit_json [as 别名]
def main():
spec = dict(
src=dict(type='path', required=True, aliases=['package']),
version=dict(),
reboot=dict(type='bool', default=True),
no_copy=dict(default=False, type='bool'),
force=dict(type='bool', default=False),
transport=dict(default='netconf', choices=['netconf'])
)
module = NetworkModule(argument_spec=spec,
supports_check_mode=True)
if not HAS_SW:
module.fail_json(msg='Missing jnpr.junos.utils.sw module')
result = dict(changed=False)
do_upgrade = module.params['force'] or False
if not module.params['force']:
has_ver = module.connection.get_facts().get('version')
wants_ver = module.params['version']
do_upgrade = has_ver != wants_ver
if do_upgrade:
if not module.check_mode:
install_package(module)
result['changed'] = True
module.exit_json(**result)
示例4: main
# 需要导入模块: from ansible.module_utils.network import NetworkModule [as 别名]
# 或者: from ansible.module_utils.network.NetworkModule import exit_json [as 别名]
def main():
spec = dict(gather_subset=dict(default=["!config"], type="list"))
module = NetworkModule(argument_spec=spec, supports_check_mode=True)
gather_subset = module.params["gather_subset"]
runable_subsets = set()
exclude_subsets = set()
for subset in gather_subset:
if subset == "all":
runable_subsets.update(VALID_SUBSETS)
continue
if subset.startswith("!"):
subset = subset[1:]
if subset == "all":
exclude_subsets.update(VALID_SUBSETS)
continue
exclude = True
else:
exclude = False
if subset not in VALID_SUBSETS:
module.fail_json(msg="Bad subset")
if exclude:
exclude_subsets.add(subset)
else:
runable_subsets.add(subset)
if not runable_subsets:
runable_subsets.update(VALID_SUBSETS)
runable_subsets.difference_update(exclude_subsets)
runable_subsets.add("default")
facts = dict()
facts["gather_subset"] = list(runable_subsets)
runner = CommandRunner(module)
instances = list()
for key in runable_subsets:
instances.append(FACT_SUBSETS[key](runner))
runner.run()
try:
for inst in instances:
inst.populate()
facts.update(inst.facts)
except Exception:
module.exit_json(out=module.from_json(runner.items))
ansible_facts = dict()
for key, value in facts.items():
key = "ansible_net_%s" % key
ansible_facts[key] = value
module.exit_json(ansible_facts=ansible_facts)
示例5: main
# 需要导入模块: from ansible.module_utils.network import NetworkModule [as 别名]
# 或者: from ansible.module_utils.network.NetworkModule import exit_json [as 别名]
def main():
""" main entry point for module execution
"""
argument_spec = dict(
src=dict(type='path'),
lines=dict(aliases=['commands'], type='list'),
parents=dict(type='list'),
before=dict(type='list'),
after=dict(type='list'),
match=dict(default='line', choices=['line', 'strict', 'exact', 'none']),
replace=dict(default='line', choices=['line', 'block']),
# this argument is deprecated in favor of setting match: none
# it will be removed in a future version
force=dict(default=False, type='bool'),
config=dict(),
defaults=dict(type='bool', default=False),
backup=dict(type='bool', default=False),
save=dict(type='bool', default=False),
)
mutually_exclusive = [('lines', 'src')]
required_if = [('match', 'strict', ['lines']),
('match', 'exact', ['lines']),
('replace', 'block', ['lines'])]
module = NetworkModule(argument_spec=argument_spec,
connect_on_load=False,
mutually_exclusive=mutually_exclusive,
required_if=required_if,
supports_check_mode=True)
if module.params['force'] is True:
module.params['match'] = 'none'
warnings = list()
check_args(module, warnings)
result = dict(changed=False, warnings=warnings)
if module.params['backup']:
result['__backup__'] = module.config.get_config()
try:
run(module, result)
except NetworkError:
exc = get_exception()
module.fail_json(msg=str(exc), **exc.kwargs)
module.exit_json(**result)
示例6: main
# 需要导入模块: from ansible.module_utils.network import NetworkModule [as 别名]
# 或者: from ansible.module_utils.network.NetworkModule import exit_json [as 别名]
def main():
""" main entry point for module execution
"""
argument_spec = dict(
src=dict(required=True),
force=dict(default=False, type='bool'),
include_defaults=dict(default=False, type='bool'),
backup=dict(default=False, type='bool'),
replace=dict(default=False, type='bool'),
config=dict()
)
mutually_exclusive = [('config', 'backup'), ('config', 'force')]
module = NetworkModule(argument_spec=argument_spec,
mutually_exclusive=mutually_exclusive,
supports_check_mode=True)
replace = module.params['replace']
commands = list()
running = None
result = dict(changed=False)
candidate = NetworkConfig(contents=module.params['src'], indent=3)
if replace:
if module.params['transport'] == 'cli':
module.fail_json(msg='config replace is only supported over eapi')
commands = str(candidate).split('\n')
else:
contents = get_config(module)
if contents:
running = NetworkConfig(contents=contents, indent=3)
result['_backup'] = contents
if not module.params['force']:
commands = candidate.difference((running or list()))
commands = dumps(commands, 'commands').split('\n')
commands = [str(c) for c in commands if c]
else:
commands = str(candidate).split('\n')
commands = filter_exit(commands)
if commands:
if not module.check_mode:
response = module.config.load_config(commands, replace=replace,
commit=True)
result['responses'] = response
result['changed'] = True
result['updates'] = commands
module.exit_json(**result)
示例7: main
# 需要导入模块: from ansible.module_utils.network import NetworkModule [as 别名]
# 或者: from ansible.module_utils.network.NetworkModule import exit_json [as 别名]
def main():
argument_spec = dict(
src=dict(required=True, type='path'),
confirm=dict(default=0, type='int'),
comment=dict(default=DEFAULT_COMMENT),
action=dict(default='merge', choices=['merge', 'overwrite', 'replace']),
config_format=dict(choices=['text', 'set', 'xml']),
backup=dict(default=False, type='bool'),
transport=dict(default='netconf', choices=['netconf'])
)
module = NetworkModule(argument_spec=argument_spec,
supports_check_mode=True)
comment = module.params['comment']
confirm = module.params['confirm']
commit = not module.check_mode
replace = False
overwrite = False
action = module.params['action']
if action == 'overwrite':
overwrite = True
elif action == 'replace':
replace = True
src = module.params['src']
fmt = module.params['config_format']
if action == 'overwrite' and fmt == 'set':
module.fail_json(msg="overwrite cannot be used when format is "
"set per junos-pyez documentation")
results = dict(changed=False)
results['_backup'] = unicode(module.config.get_config()).strip()
try:
diff = module.config.load_config(src, commit=commit, replace=replace,
confirm=confirm, comment=comment, config_format=fmt)
if diff:
results['changed'] = True
results['diff'] = dict(prepared=diff)
except NetworkError:
exc = get_exception()
module.fail_json(msg=str(exc), **exc.kwargs)
module.exit_json(**results)
示例8: main
# 需要导入模块: from ansible.module_utils.network import NetworkModule [as 别名]
# 或者: from ansible.module_utils.network.NetworkModule import exit_json [as 别名]
def main():
""" main entry point for module execution
"""
argument_spec = dict(
http=dict(aliases=['enable_http'], default=False, type='bool', setter='set_protocol_http'),
http_port=dict(default=80, type='int', setter='set_protocol_http'),
https=dict(aliases=['enable_https'], default=True, type='bool', setter='set_protocol_https'),
https_port=dict(default=443, type='int', setter='set_protocol_https'),
local_http=dict(aliases=['enable_local_http'], default=False, type='bool', setter='set_local_http'),
local_http_port=dict(default=8080, type='int', setter='set_local_http'),
socket=dict(aliases=['enable_socket'], default=False, type='bool'),
vrf=dict(default='default'),
config=dict(),
# Only allow use of transport cli when configuring eAPI
transport=dict(default='cli', choices=['cli']),
state=dict(default='started', choices=['stopped', 'started']),
)
module = NetworkModule(argument_spec=argument_spec,
connect_on_load=False,
supports_check_mode=True)
state = module.params['state']
result = dict(changed=False)
commands = list()
instance = get_instance(module)
invoke(state, module, instance, commands)
try:
load(module, instance, commands, result)
except NetworkError:
exc = get_exception()
module.fail_json(msg=str(exc), **exc.kwargs)
collect_facts(module, result)
clean_result(result)
module.exit_json(**result)
示例9: main
# 需要导入模块: from ansible.module_utils.network import NetworkModule [as 别名]
# 或者: from ansible.module_utils.network.NetworkModule import exit_json [as 别名]
def main():
""" main entry point for module execution
"""
argument_spec = dict(
lines=dict(type='list'),
src=dict(type='path'),
src_format=dict(choices=['xml', 'text', 'set', 'json']),
# update operations
replace=dict(default=False, type='bool'),
confirm=dict(default=0, type='int'),
comment=dict(default=DEFAULT_COMMENT),
# config operations
backup=dict(type='bool', default=False),
rollback=dict(type='int'),
zeroize=dict(default=False, type='bool'),
transport=dict(default='netconf', choices=['netconf'])
)
mutually_exclusive = [('lines', 'rollback'), ('lines', 'zeroize'),
('rollback', 'zeroize'), ('lines', 'src'),
('src', 'zeroize'), ('src', 'rollback')]
required_if = [('replace', True, ['src'])]
module = NetworkModule(argument_spec=argument_spec,
mutually_exclusive=mutually_exclusive,
required_if=required_if,
supports_check_mode=True)
result = dict(changed=False)
if module.params['backup']:
result['__backup__'] = module.config.get_config()
try:
run(module, result)
except NetworkError:
exc = get_exception()
module.fail_json(msg=str(exc), **exc.kwargs)
module.exit_json(**result)
示例10: main
# 需要导入模块: from ansible.module_utils.network import NetworkModule [as 别名]
# 或者: from ansible.module_utils.network.NetworkModule import exit_json [as 别名]
def main():
""" main entry point for module execution
"""
argument_spec = dict(
src=dict(),
force=dict(default=False, type='bool'),
include_defaults=dict(default=True, type='bool'),
backup=dict(default=False, type='bool'),
config=dict(),
)
mutually_exclusive = [('config', 'backup'), ('config', 'force')]
module = NetworkModule(argument_spec=argument_spec,
mutually_exclusive=mutually_exclusive,
supports_check_mode=True)
result = dict(changed=False)
candidate = NetworkConfig(contents=module.params['src'], indent=2)
contents = get_config(module)
if contents:
config = NetworkConfig(contents=contents, indent=2)
result['_backup'] = str(contents)
if not module.params['force']:
commands = candidate.difference(config)
commands = dumps(commands, 'commands').split('\n')
commands = [str(c) for c in commands if c]
else:
commands = str(candidate).split('\n')
if commands:
if not module.check_mode:
response = module.config(commands)
result['responses'] = response
result['changed'] = True
result['updates'] = commands
module.exit_json(**result)
示例11: main
# 需要导入模块: from ansible.module_utils.network import NetworkModule [as 别名]
# 或者: from ansible.module_utils.network.NetworkModule import exit_json [as 别名]
def main():
"""main entry point for module execution
"""
argument_spec = dict(
netconf_port=dict(type='int', default=830, aliases=['listens_on']),
state=dict(default='present', choices=['present', 'absent']),
transport=dict(default='cli', choices=['cli'])
)
module = NetworkModule(argument_spec=argument_spec,
supports_check_mode=True)
state = module.params['state']
port = module.params['netconf_port']
result = dict(changed=False)
instance = get_instance(module)
if state == 'present' and instance.get('state') == 'absent':
commands = 'set system services netconf ssh port %s' % port
elif state == 'present' and port != instance.get('port'):
commands = 'set system services netconf ssh port %s' % port
elif state == 'absent' and instance.get('state') == 'present':
commands = 'delete system services netconf'
else:
commands = None
if commands:
if not module.check_mode:
try:
comment = 'configuration updated by junos_netconf'
module.config(commands, comment=comment)
except NetworkError:
exc = get_exception()
module.fail_json(msg=str(exc), **exc.kwargs)
result['changed'] = True
result['commands'] = commands
module.exit_json(**result)
示例12: main
# 需要导入模块: from ansible.module_utils.network import NetworkModule [as 别名]
# 或者: from ansible.module_utils.network.NetworkModule import exit_json [as 别名]
def main():
""" main entry point for module execution
"""
argument_spec = dict(
src=dict(type='str'),
force=dict(default=False, type='bool'),
backup=dict(default=False, type='bool'),
config=dict(type='dict'),
)
mutually_exclusive = [('config', 'backup'), ('config', 'force')]
module = NetworkModule(argument_spec=argument_spec,
mutually_exclusive=mutually_exclusive,
supports_check_mode=True)
if not module.params['transport'] and not HAS_OPS:
module.fail_json(msg='unable to import ops.dc library')
result = dict(changed=False)
contents = get_config(module)
result['_backup'] = contents
if module.params['transport'] in ['ssh', 'rest']:
config = contents
try:
src = module.from_json(module.params['src'])
except ValueError:
module.fail_json(msg='unable to load src due to json parsing error')
changeset = diff(src, config)
candidate = merge(changeset, config)
updates = dict()
for path, key, new_value, old_value in changeset:
path = '%s.%s' % ('.'.join(path), key)
updates[path] = str(new_value)
result['updates'] = updates
if changeset:
if not module.check_mode:
module.config(config)
result['changed'] = True
else:
candidate = NetworkConfig(contents=module.params['src'], indent=4)
if contents:
config = NetworkConfig(contents=contents, indent=4)
if not module.params['force']:
commands = candidate.difference(config)
commands = dumps(commands, 'commands').split('\n')
commands = [str(c) for c in commands if c]
else:
commands = str(candidate).split('\n')
if commands:
if not module.check_mode:
response = module.config(commands)
result['responses'] = response
result['changed'] = True
result['updates'] = commands
module.exit_json(**result)
示例13: main
# 需要导入模块: from ansible.module_utils.network import NetworkModule [as 别名]
# 或者: from ansible.module_utils.network.NetworkModule import exit_json [as 别名]
def main():
argument_spec = dict(
lines=dict(aliases=['commands'], type='list'),
parents=dict(type='list'),
src=dict(type='path'),
before=dict(type='list'),
after=dict(type='list'),
match=dict(default='line',
choices=['line', 'strict', 'exact', 'none']),
replace=dict(default='line', choices=['line', 'block']),
update=dict(choices=['merge', 'check'], default='merge'),
save=dict(type='bool', default=False),
config=dict(),
backup=dict(type='bool', default=False)
)
mutually_exclusive = [('lines', 'src')]
module = NetworkModule(argument_spec=argument_spec,
connect_on_load=False,
mutually_exclusive=mutually_exclusive,
supports_check_mode=True)
parents = module.params['parents'] or list()
match = module.params['match']
replace = module.params['replace']
result = dict(changed=False, saved=False)
candidate = get_candidate(module)
if match != 'none':
config = get_config(module)
if parents:
config = get_sublevel_config(config, module)
configobjs = candidate.difference(config, match=match, replace=replace)
else:
configobjs = candidate.items
if module.params['backup']:
result['__backup__'] = module.cli('show running-config')[0]
commands = list()
if configobjs:
commands = dumps(configobjs, 'commands')
commands = commands.split('\n')
if module.params['before']:
commands[:0] = module.params['before']
if module.params['after']:
commands.extend(module.params['after'])
if not module.check_mode and module.params['update'] == 'merge':
response = module.config.load_config(commands)
result['responses'] = response
if module.params['save']:
module.config.save_config()
result['saved'] = True
result['changed'] = True
result['updates'] = commands
module.exit_json(**result)
示例14: main
# 需要导入模块: from ansible.module_utils.network import NetworkModule [as 别名]
# 或者: from ansible.module_utils.network.NetworkModule import exit_json [as 别名]
def main():
"""main entry point for Ansible module
"""
spec = dict(
commands=dict(type="list"),
rpcs=dict(type="list"),
display=dict(default="xml", choices=["text", "xml"], aliases=["format", "output"]),
wait_for=dict(type="list", aliases=["waitfor"]),
match=dict(default="all", choices=["all", "any"]),
retries=dict(default=10, type="int"),
interval=dict(default=1, type="int"),
transport=dict(default="netconf", choices=["netconf"]),
)
mutually_exclusive = [("commands", "rpcs")]
module = NetworkModule(argument_spec=spec, mutually_exclusive=mutually_exclusive, supports_check_mode=True)
commands = list()
for key in VALID_KEYS.keys():
commands.extend(list(parse(module, key)))
conditionals = module.params["wait_for"] or list()
warnings = list()
runner = CommandRunner(module)
for cmd in commands:
if module.check_mode and not cmd["command"].startswith("show"):
warnings.append(
"only show commands are supported when using " "check mode, not executing `%s`" % cmd["command"]
)
else:
if cmd["command"].startswith("co"):
module.fail_json(
msg="junos_command does not support running "
"config mode commands. Please use "
"junos_config instead"
)
try:
runner.add_command(**cmd)
except AddCommandError:
exc = get_exception()
warnings.append("duplicate command detected: %s" % cmd)
try:
for item in conditionals:
runner.add_conditional(item)
except (ValueError, AddConditionError):
exc = get_exception()
module.fail_json(msg=str(exc), condition=exc.condition)
runner.retries = module.params["retries"]
runner.interval = module.params["interval"]
runner.match = module.params["match"]
try:
runner.run()
except FailedConditionsError:
exc = get_exception()
module.fail_json(msg=str(exc), failed_conditions=exc.failed_conditions)
except FailedConditionalError:
exc = get_exception()
module.fail_json(msg=str(exc), failed_conditional=exc.failed_conditional)
except NetworkError:
exc = get_exception()
module.fail_json(msg=str(exc))
result = dict(changed=False, stdout=list())
for cmd in commands:
try:
output = runner.get_command(cmd["command"], cmd.get("output"))
except ValueError:
output = "command not executed due to check_mode, see warnings"
result["stdout"].append(output)
result["warnings"] = warnings
result["stdout_lines"] = list(to_lines(result["stdout"]))
module.exit_json(**result)
示例15: main
# 需要导入模块: from ansible.module_utils.network import NetworkModule [as 别名]
# 或者: from ansible.module_utils.network.NetworkModule import exit_json [as 别名]
def main():
spec = dict(
gather_subset=dict(default=['!config'], type='list')
)
module = NetworkModule(argument_spec=spec, supports_check_mode=True)
gather_subset = module.params['gather_subset']
runable_subsets = set()
exclude_subsets = set()
for subset in gather_subset:
if subset == 'all':
runable_subsets.update(VALID_SUBSETS)
continue
if subset.startswith('!'):
subset = subset[1:]
if subset == 'all':
exclude_subsets.update(VALID_SUBSETS)
continue
exclude = True
else:
exclude = False
if subset not in VALID_SUBSETS:
module.fail_json(msg='Bad subset')
if exclude:
exclude_subsets.add(subset)
else:
runable_subsets.add(subset)
if not runable_subsets:
runable_subsets.update(VALID_SUBSETS)
runable_subsets.difference_update(exclude_subsets)
runable_subsets.add('default')
facts = dict()
facts['gather_subset'] = list(runable_subsets)
instances = list()
for key in runable_subsets:
instances.append(FACT_SUBSETS[key](module))
failed_commands = list()
try:
for inst in instances:
inst.populate()
failed_commands.extend(inst.failed_commands)
facts.update(inst.facts)
except Exception:
exc = get_exception()
module.fail_json(msg=str(exc))
ansible_facts = dict()
for key, value in iteritems(facts):
key = 'ansible_net_%s' % key
ansible_facts[key] = value
module.exit_json(ansible_facts=ansible_facts, failed_commands=failed_commands)