mirror of https://github.com/ansible/ansible.git
refactors junos modules to support persistent socket connections (#21365)
* updates junos_netconf module * updates junos_command module * updates junos_config module * updates _junos_template module * adds junos_rpc module * adds junos_user modulepull/20872/head
parent
47870c3385
commit
02d2b753db
@ -0,0 +1,151 @@
|
||||
#!/usr/bin/python
|
||||
#
|
||||
# This file is part of Ansible
|
||||
#
|
||||
# Ansible is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# Ansible is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
|
||||
#
|
||||
|
||||
ANSIBLE_METADATA = {
|
||||
'status': ['preview'],
|
||||
'supported_by': 'core',
|
||||
'version': '1.0'
|
||||
}
|
||||
|
||||
DOCUMENTATION = """
|
||||
---
|
||||
module: junos_rpc
|
||||
version_added: "2.3"
|
||||
author: "Peter Sprygada (@privateip)"
|
||||
short_description: Runs an arbitrary RPC on the remote device over NetConf
|
||||
description:
|
||||
- Sends a request to the remote device running JUNOS to execute the
|
||||
specified RPC using the NetConf transport. The reply is then
|
||||
returned to the playbook in the c(xml) key. If an alternate output
|
||||
format is requested, the reply is transformed to the requested output.
|
||||
options:
|
||||
rpc:
|
||||
description:
|
||||
- The C(rpc) argument specifies the RPC call to send to the
|
||||
remote devices to be executed. The RPC Reply message is parsed
|
||||
and the contents are returned to the playbook.
|
||||
required: true
|
||||
args:
|
||||
description:
|
||||
- The C(args) argument provides a set of arguments for the RPC
|
||||
call and are encoded in the request message. This argument
|
||||
accepts a set of key=value arguments.
|
||||
required: false
|
||||
default: null
|
||||
output:
|
||||
description:
|
||||
- The C(output) argument specifies the desired output of the
|
||||
return data. This argument accepts one of C(xml), C(text),
|
||||
or C(json). For C(json), the JUNOS device must be running a
|
||||
version of software that supports native JSON output.
|
||||
required: false
|
||||
default: xml
|
||||
"""
|
||||
|
||||
EXAMPLES = """
|
||||
- name: collect interface information using rpc
|
||||
junos_rpc:
|
||||
rpc: get-interface-information
|
||||
args:
|
||||
interface: em0
|
||||
media: True
|
||||
|
||||
- name: get system information
|
||||
junos_rpc:
|
||||
rpc: get-system-information
|
||||
"""
|
||||
|
||||
RETURN = """
|
||||
xml:
|
||||
description: The xml return string from the rpc request
|
||||
returned: always
|
||||
output:
|
||||
description: The rpc rely converted to the output format
|
||||
returned: always
|
||||
output_lines:
|
||||
description: The text output split into lines for readability
|
||||
returned: always
|
||||
"""
|
||||
from ncclient.xml_ import new_ele, sub_ele, to_xml, to_ele
|
||||
|
||||
from ansible.module_utils.basic import AnsibleModule
|
||||
from ansible.module_utils.netconf import send_request
|
||||
from ansible.module_utils.six import iteritems
|
||||
|
||||
|
||||
|
||||
def main():
|
||||
"""main entry point for Ansible module
|
||||
"""
|
||||
argument_spec = dict(
|
||||
rpc=dict(required=True),
|
||||
args=dict(type='dict'),
|
||||
output=dict(default='xml', choices=['xml', 'json', 'text']),
|
||||
)
|
||||
|
||||
module = AnsibleModule(argument_spec=argument_spec,
|
||||
supports_check_mode=False)
|
||||
|
||||
result = {'changed': False}
|
||||
|
||||
rpc = str(module.params['rpc']).replace('_', '-')
|
||||
|
||||
if all((module.check_mode, not rpc.startswith('get'))):
|
||||
module.fail_json(msg='invalid rpc for running in check_mode')
|
||||
|
||||
args = module.params['args'] or {}
|
||||
|
||||
xattrs = {'format': module.params['output']}
|
||||
|
||||
element = new_ele(module.params['rpc'], xattrs)
|
||||
|
||||
for key, value in iteritems(args):
|
||||
key = str(key).replace('_', '-')
|
||||
if isinstance(value, list):
|
||||
for item in value:
|
||||
child = sub_ele(element, key)
|
||||
if item is not True:
|
||||
child.text = item
|
||||
else:
|
||||
child = sub_ele(element, key)
|
||||
if value is not True:
|
||||
child.text = value
|
||||
|
||||
reply = send_request(module, element)
|
||||
|
||||
result['xml'] = str(to_xml(reply))
|
||||
|
||||
if module.params['output'] == 'text':
|
||||
reply = to_ele(reply)
|
||||
data = reply.xpath('//output')
|
||||
result['output'] = data[0].text.strip()
|
||||
result['output_lines'] = result['output'].split('\n')
|
||||
|
||||
elif module.params['output'] == 'json':
|
||||
reply = to_ele(reply)
|
||||
data = reply.xpath('//rpc-reply')
|
||||
result['output'] = module.from_json(data[0].text.strip())
|
||||
|
||||
else:
|
||||
result['output'] = str(to_xml(reply)).split('\n')
|
||||
|
||||
module.exit_json(**result)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
@ -0,0 +1,256 @@
|
||||
#!/usr/bin/python
|
||||
#
|
||||
# This file is part of Ansible
|
||||
#
|
||||
# Ansible is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# Ansible is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
|
||||
#
|
||||
|
||||
ANSIBLE_METADATA = {
|
||||
'status': ['preview'],
|
||||
'supported_by': 'core',
|
||||
'version': '1.0'
|
||||
}
|
||||
|
||||
DOCUMENTATION = """
|
||||
---
|
||||
module: junos_user
|
||||
version_added: "2.3"
|
||||
author: "Peter Sprygada (@privateip)"
|
||||
short_description: Manage local user accounts on Juniper devices
|
||||
description:
|
||||
- This module manages locally configured user accounts on remote
|
||||
network devices running the JUNOS operating system. It provides
|
||||
a set of arguments for creating, removing and updating locally
|
||||
defined accounts
|
||||
options:
|
||||
users:
|
||||
description:
|
||||
- The C(users) argument defines a list of users to be configured
|
||||
on the remote device. The list of users will be compared against
|
||||
the current users and only changes will be added or removed from
|
||||
the device configuration. This argument is mutually exclusive with
|
||||
the name argument.
|
||||
required: False
|
||||
default: null
|
||||
name:
|
||||
description:
|
||||
- The C(name) argument defines the username of the user to be created
|
||||
on the system. This argument must follow appropriate usernaming
|
||||
conventions for the target device running JUNOS. This argument is
|
||||
mutually exclusive with the C(users) argument.
|
||||
required: false
|
||||
default: null
|
||||
full_name:
|
||||
description:
|
||||
- The C(full_name) argument provides the full name of the user
|
||||
account to be created on the remote device. This argument accepts
|
||||
any text string value.
|
||||
required: false
|
||||
default: null
|
||||
role:
|
||||
description:
|
||||
- The C(role) argument defines the role of the user account on the
|
||||
remote system. User accounts can have more than one role
|
||||
configured.
|
||||
required: false
|
||||
default: read-only
|
||||
choices: ['operator', 'read-only', 'super-user', 'unauthorized']
|
||||
sshkey:
|
||||
description:
|
||||
- The C(sshkey) argument defines the public SSH key to be configured
|
||||
for the user account on the remote system. This argument must
|
||||
be a valid SSH key
|
||||
required: false
|
||||
default: null
|
||||
purge:
|
||||
description:
|
||||
- The C(purge) argument instructs the module to consider the
|
||||
users definition absolute. It will remove any previously configured
|
||||
users on the device with the exception of the current defined
|
||||
set of users.
|
||||
required: false
|
||||
default: false
|
||||
state:
|
||||
description:
|
||||
- The C(state) argument configures the state of the user definitions
|
||||
as it relates to the device operational configuration. When set
|
||||
to I(present), the user should be configured in the device active
|
||||
configuration and when set to I(absent) the user should not be
|
||||
in the device active configuration
|
||||
required: false
|
||||
default: present
|
||||
choices: ['present', 'absent']
|
||||
"""
|
||||
|
||||
EXAMPLES = """
|
||||
- name: create new user account
|
||||
junos_user:
|
||||
name: ansible
|
||||
role: super-user
|
||||
sshkey: "{{ lookup('file', '~/.ssh/ansible.pub') }}"
|
||||
state: present
|
||||
|
||||
- name: remove a user account
|
||||
junos_user:
|
||||
name: ansible
|
||||
state: absent
|
||||
|
||||
- name: remove all user accounts except ansible
|
||||
junos_user:
|
||||
name: ansible
|
||||
purge: yes
|
||||
"""
|
||||
|
||||
RETURN = """
|
||||
"""
|
||||
from functools import partial
|
||||
|
||||
from ncclient.xml_ import new_ele, sub_ele, to_xml
|
||||
|
||||
from ansible.module_utils.basic import AnsibleModule
|
||||
from ansible.module_utils.junos import load
|
||||
from ansible.module_utils.six import iteritems
|
||||
|
||||
ROLES = ['operator', 'read-only', 'super-user', 'unauthorized']
|
||||
|
||||
def map_obj_to_ele(want):
|
||||
element = new_ele('system')
|
||||
login = sub_ele(element, 'login', {'replace': 'replace'})
|
||||
|
||||
for item in want:
|
||||
if item['state'] != 'present':
|
||||
operation = 'delete'
|
||||
else:
|
||||
operation = 'replace'
|
||||
|
||||
user = sub_ele(login, 'user', {'operation': operation})
|
||||
|
||||
sub_ele(user, 'name').text = item['name']
|
||||
|
||||
if operation == 'replace':
|
||||
sub_ele(user, 'class').text = item['role']
|
||||
|
||||
if item.get('full_name'):
|
||||
sub_ele(user, 'full-name').text = item['full_name']
|
||||
|
||||
if item.get('sshkey'):
|
||||
auth = sub_ele(user, 'authentication')
|
||||
ssh_rsa = sub_ele(auth, 'ssh-rsa')
|
||||
key = sub_ele(ssh_rsa, 'name').text = item['sshkey']
|
||||
|
||||
return element
|
||||
|
||||
def get_param_value(key, item, module):
|
||||
# if key doesn't exist in the item, get it from module.params
|
||||
if not item.get(key):
|
||||
value = module.params[key]
|
||||
|
||||
# if key does exist, do a type check on it to validate it
|
||||
else:
|
||||
value_type = module.argument_spec[key].get('type', 'str')
|
||||
type_checker = module._CHECK_ARGUMENT_TYPES_DISPATCHER[value_type]
|
||||
type_checker(item[key])
|
||||
value = item[key]
|
||||
|
||||
# validate the param value (if validator func exists)
|
||||
validator = globals().get('validate_%s' % key)
|
||||
if all((value, validator)):
|
||||
validator(value, module)
|
||||
|
||||
return value
|
||||
|
||||
def map_params_to_obj(module):
|
||||
users = module.params['users']
|
||||
if not users:
|
||||
if not module.params['name'] and module.params['purge']:
|
||||
return list()
|
||||
elif not module.params['name']:
|
||||
module.fail_json(msg='missing required argument: name')
|
||||
else:
|
||||
collection = [{'name': module.params['name']}]
|
||||
else:
|
||||
collection = list()
|
||||
for item in users:
|
||||
if not isinstance(item, dict):
|
||||
collection.append({'username': item})
|
||||
elif 'name' not in item:
|
||||
module.fail_json(msg='missing required argument: name')
|
||||
else:
|
||||
collection.append(item)
|
||||
|
||||
objects = list()
|
||||
|
||||
for item in collection:
|
||||
get_value = partial(get_param_value, item=item, module=module)
|
||||
item.update({
|
||||
'full_name': get_value('full_name'),
|
||||
'role': get_value('role'),
|
||||
'sshkey': get_value('sshkey'),
|
||||
'state': get_value('state')
|
||||
})
|
||||
|
||||
for key, value in iteritems(item):
|
||||
# validate the param value (if validator func exists)
|
||||
validator = globals().get('validate_%s' % key)
|
||||
if all((value, validator)):
|
||||
validator(value, module)
|
||||
|
||||
objects.append(item)
|
||||
|
||||
return objects
|
||||
|
||||
|
||||
def main():
|
||||
""" main entry point for module execution
|
||||
"""
|
||||
argument_spec = dict(
|
||||
users=dict(type='list'),
|
||||
name=dict(),
|
||||
|
||||
full_name=dict(),
|
||||
role=dict(choices=ROLES, default='unauthorized'),
|
||||
sshkey=dict(),
|
||||
|
||||
purge=dict(type='bool'),
|
||||
|
||||
state=dict(choices=['present', 'absent'], default='present')
|
||||
)
|
||||
|
||||
mutually_exclusive = [('users', 'name')]
|
||||
|
||||
module = AnsibleModule(argument_spec=argument_spec,
|
||||
mutually_exclusive=mutually_exclusive,
|
||||
supports_check_mode=True)
|
||||
|
||||
result = {'changed': False}
|
||||
|
||||
want = map_params_to_obj(module)
|
||||
ele = map_obj_to_ele(want)
|
||||
|
||||
kwargs = {'commit': not module.check_mode}
|
||||
if module.params['purge']:
|
||||
kwargs['action'] = 'replace'
|
||||
|
||||
diff = load(module, ele, **kwargs)
|
||||
|
||||
if diff:
|
||||
result.update({
|
||||
'changed': True,
|
||||
'diff': {'prepared': diff}
|
||||
})
|
||||
|
||||
module.exit_json(**result)
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
@ -0,0 +1,119 @@
|
||||
#
|
||||
# (c) 2016 Red Hat Inc.
|
||||
#
|
||||
# This file is part of Ansible
|
||||
#
|
||||
# Ansible is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# Ansible is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
|
||||
#
|
||||
from __future__ import (absolute_import, division, print_function)
|
||||
__metaclass__ = type
|
||||
|
||||
import os
|
||||
import sys
|
||||
import copy
|
||||
|
||||
from ansible.plugins.action.normal import ActionModule as _ActionModule
|
||||
from ansible.utils.path import unfrackpath
|
||||
from ansible.plugins import connection_loader
|
||||
from ansible.compat.six import iteritems
|
||||
from ansible.module_utils.junos import junos_argument_spec
|
||||
from ansible.module_utils.basic import AnsibleFallbackNotFound
|
||||
from ansible.module_utils._text import to_bytes
|
||||
|
||||
from ncclient.xml_ import new_ele, sub_ele, to_xml
|
||||
|
||||
try:
|
||||
from __main__ import display
|
||||
except ImportError:
|
||||
from ansible.utils.display import Display
|
||||
display = Display()
|
||||
|
||||
class ActionModule(_ActionModule):
|
||||
|
||||
def run(self, tmp=None, task_vars=None):
|
||||
|
||||
if self._play_context.connection != 'local':
|
||||
return dict(
|
||||
fail=True,
|
||||
msg='invalid connection specified, expected connection=local, '
|
||||
'got %s' % self._play_context.connection
|
||||
)
|
||||
|
||||
provider = self.load_provider()
|
||||
|
||||
pc = copy.deepcopy(self._play_context)
|
||||
pc.network_os = 'junos'
|
||||
|
||||
if self._task.action in ('junos_command', 'junos_netconf', 'junos_config', '_junos_template'):
|
||||
pc.connection = 'network_cli'
|
||||
pc.port = provider['port'] or self._play_context.port or 22
|
||||
else:
|
||||
pc.connection = 'netconf'
|
||||
pc.port = provider['port'] or self._play_context.port or 830
|
||||
|
||||
pc.remote_user = provider['username'] or self._play_context.connection_user
|
||||
pc.password = provider['password'] or self._play_context.password
|
||||
pc.private_key_file = provider['ssh_keyfile'] or self._play_context.private_key_file
|
||||
|
||||
socket_path = self._get_socket_path(pc)
|
||||
|
||||
if not os.path.exists(socket_path):
|
||||
# start the connection if it isn't started
|
||||
connection = self._shared_loader_obj.connection_loader.get('persistent', pc, sys.stdin)
|
||||
|
||||
if pc.connection == 'network_cli':
|
||||
rc, out, err = connection.exec_command('show version')
|
||||
display.vvv('%s %s %s' % (rc, out, err))
|
||||
|
||||
if pc.connection == 'netconf':
|
||||
# <get-software-information />
|
||||
req = new_ele('get-software-information')
|
||||
connection.exec_command(to_xml(req))
|
||||
|
||||
task_vars['ansible_socket'] = socket_path
|
||||
|
||||
return super(ActionModule, self).run(tmp, task_vars)
|
||||
|
||||
def _get_socket_path(self, play_context):
|
||||
ssh = connection_loader.get('ssh', class_only=True)
|
||||
path = unfrackpath("$HOME/.ansible/pc")
|
||||
cp = ssh._create_control_path(play_context.remote_addr, play_context.port, play_context.remote_user)
|
||||
return cp % dict(directory=path)
|
||||
|
||||
def load_provider(self):
|
||||
provider = self._task.args.get('provider', {})
|
||||
for key, value in iteritems(junos_argument_spec):
|
||||
if key != 'provider' and key not in provider:
|
||||
if key in self._task.args:
|
||||
provider[key] = self._task.args[key]
|
||||
elif 'fallback' in value:
|
||||
provider[key] = self._fallback(value['fallback'])
|
||||
elif key not in provider:
|
||||
provider[key] = None
|
||||
return provider
|
||||
|
||||
def _fallback(self, fallback):
|
||||
strategy = fallback[0]
|
||||
args = []
|
||||
kwargs = {}
|
||||
|
||||
for item in fallback[1:]:
|
||||
if isinstance(item, dict):
|
||||
kwargs = item
|
||||
else:
|
||||
args = item
|
||||
try:
|
||||
return strategy(*args, **kwargs)
|
||||
except AnsibleFallbackNotFound:
|
||||
pass
|
@ -0,0 +1,122 @@
|
||||
# (c) 2016 Red Hat Inc.
|
||||
#
|
||||
# This file is part of Ansible
|
||||
#
|
||||
# Ansible is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# Ansible is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
# Make coding more python3-ish
|
||||
from __future__ import (absolute_import, division, print_function)
|
||||
__metaclass__ = type
|
||||
|
||||
import os
|
||||
import json
|
||||
import sys
|
||||
|
||||
from ansible.compat.tests import unittest
|
||||
from ansible.compat.tests.mock import patch, Mock
|
||||
from ansible.module_utils import basic
|
||||
from ansible.module_utils._text import to_bytes
|
||||
|
||||
|
||||
def set_module_args(args):
|
||||
args = json.dumps({'ANSIBLE_MODULE_ARGS': args})
|
||||
basic._ANSIBLE_ARGS = to_bytes(args)
|
||||
|
||||
fixture_path = os.path.join(os.path.dirname(__file__), 'fixtures')
|
||||
fixture_data = {}
|
||||
|
||||
def load_fixture(name):
|
||||
path = os.path.join(fixture_path, name)
|
||||
|
||||
if path in fixture_data:
|
||||
return fixture_data[path]
|
||||
|
||||
with open(path) as f:
|
||||
data = f.read()
|
||||
|
||||
try:
|
||||
data = json.loads(data)
|
||||
except:
|
||||
pass
|
||||
|
||||
fixture_data[path] = data
|
||||
return data
|
||||
|
||||
class AnsibleExitJson(Exception):
|
||||
pass
|
||||
|
||||
class AnsibleFailJson(Exception):
|
||||
pass
|
||||
|
||||
|
||||
mock_modules = {
|
||||
'ncclient': Mock(),
|
||||
'ncclient.xml_': Mock()
|
||||
}
|
||||
patch_import = patch.dict('sys.modules', mock_modules)
|
||||
patch_import.start()
|
||||
|
||||
|
||||
class TestJunosModule(unittest.TestCase):
|
||||
|
||||
def execute_module(self, failed=False, changed=False, commands=None,
|
||||
sort=True, defaults=False):
|
||||
|
||||
self.load_fixtures(commands)
|
||||
|
||||
if failed:
|
||||
result = self.failed()
|
||||
self.assertTrue(result['failed'], result)
|
||||
else:
|
||||
result = self.changed(changed)
|
||||
self.assertEqual(result['changed'], changed, result)
|
||||
|
||||
if commands:
|
||||
if sort:
|
||||
self.assertEqual(sorted(commands), sorted(result['commands']), result['commands'])
|
||||
else:
|
||||
self.assertEqual(commands, result['commands'], result['commands'])
|
||||
|
||||
return result
|
||||
|
||||
def failed(self):
|
||||
def fail_json(*args, **kwargs):
|
||||
kwargs['failed'] = True
|
||||
raise AnsibleFailJson(kwargs)
|
||||
|
||||
with patch.object(basic.AnsibleModule, 'fail_json', fail_json):
|
||||
with self.assertRaises(AnsibleFailJson) as exc:
|
||||
self.module.main()
|
||||
|
||||
result = exc.exception.args[0]
|
||||
self.assertTrue(result['failed'], result)
|
||||
return result
|
||||
|
||||
def changed(self, changed=False):
|
||||
def exit_json(*args, **kwargs):
|
||||
if 'changed' not in kwargs:
|
||||
kwargs['changed'] = False
|
||||
raise AnsibleExitJson(kwargs)
|
||||
|
||||
with patch.object(basic.AnsibleModule, 'exit_json', exit_json):
|
||||
with self.assertRaises(AnsibleExitJson) as exc:
|
||||
self.module.main()
|
||||
|
||||
result = exc.exception.args[0]
|
||||
self.assertEqual(result['changed'], changed, result)
|
||||
return result
|
||||
|
||||
def load_fixtures(self, commands=None):
|
||||
pass
|
||||
|
Loading…
Reference in New Issue