Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- (ansible-latest) [dcc@mbp ~/lang/python/sohonet_ansible]$ ansible-playbook --version
- ansible-playbook 2.7.5
- config file = None
- configured module search path = [u'/Users/dcc/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
- ansible python module location = /Users/dcc/venvs/ansible-latest/lib/python2.7/site-packages/ansible
- executable location = /Users/dcc/venvs/ansible-latest/bin/ansible-playbook
- python version = 2.7.10 (default, Feb 7 2017, 00:08:15) [GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.34)]
- (ansible-latest) [dcc@mbp ~/lang/python/sohonet_ansible]$ cat dev_inentory.txt
- [em316]
- MR-EM316LNXNM-I-1-LAP01-US
- MR-EM316LNXNM-I-1-LDP07-GB
- [em316:vars]
- ansible_ssh_user=admin
- ansible_ssh_pass=xxxxxxxxxxxxx
- ansible_network_os=EM316LNXNM
- (ansible-latest) [dcc@mbp ~/lang/python/sohonet_ansible]$ cat agnostic.yml
- ---
- - name: AGNOSTIC PLAYBOOK
- hosts: em316
- gather_facts: false
- connection: network_cli
- tasks:
- - name: Set remote server
- cli_config:
- config: aaa remote-server host 1 10.64.21.16 SECRET
- (ansible-latest) [dcc@mbp ~/lang/python/sohonet_ansible]$ ansible-playbook -i dev_inentory.txt agnostic.yml
- PLAY [AGNOSTIC PLAYBOOK] *********************************************************************************************************************************************************************************************************************************
- TASK [Set remote server] *********************************************************************************************************************************************************************************************************************************
- ok: [MR-EM316LNXNM-I-1-LAP01-US]
- ok: [MR-EM316LNXNM-I-1-LDP07-GB]
- PLAY RECAP ***********************************************************************************************************************************************************************************************************************************************
- MR-EM316LNXNM-I-1-LAP01-US : ok=1 changed=0 unreachable=0 failed=0
- MR-EM316LNXNM-I-1-LDP07-GB : ok=1 changed=0 unreachable=0 failed=0
- (ansible-latest) [dcc@mbp ~/lang/python/sohonet_ansible]$ cat /Users/dcc/venvs/ansible-latest/lib/python2.7/site-packages/ansible/plugins/terminal/EM316LNXNM.py
- from __future__ import (absolute_import, division, print_function)
- __metaclass__ = type
- import json
- import re
- from ansible.errors import AnsibleConnectionFailure
- from ansible.module_utils._text import to_text, to_bytes
- from ansible.plugins.terminal import TerminalBase
- from ansible.utils.display import Display
- display = Display()
- class TerminalModule(TerminalBase):
- terminal_stdout_re = [
- re.compile(br"[\r\n]?[\w\+\-\.:\/\[\]]+(?:\([^\)]+\)){0,3}(?:[>#]) ?$")
- ]
- terminal_stderr_re = [
- re.compile(br"% ?Error"),
- # re.compile(br"^% \w+", re.M),
- re.compile(br"% ?Bad secret"),
- re.compile(br"[\r\n%] Bad passwords"),
- re.compile(br"invalid input", re.I),
- re.compile(br"(?:incomplete|ambiguous) command", re.I),
- re.compile(br"connection timed out", re.I),
- re.compile(br"[^\r\n]+ not found"),
- re.compile(br"'[^']' +returned error code: ?\d+"),
- re.compile(br"Bad mask", re.I),
- re.compile(br"% ?(\S+) ?overlaps with ?(\S+)", re.I),
- re.compile(br"[%\S] ?Error: ?[\s]+", re.I),
- re.compile(br"[%\S] ?Informational: ?[\s]+", re.I),
- re.compile(br"Command authorization failed")
- ]
- def on_open_shell(self):
- try:
- self._exec_cli_command(b'terminal length 0')
- except AnsibleConnectionFailure:
- raise AnsibleConnectionFailure('unable to set terminal parameters')
- try:
- self._exec_cli_command(b'terminal width 512')
- except AnsibleConnectionFailure:
- display.display('WARNING: Unable to set terminal width, command responses may be truncated')
- def on_become(self, passwd=None):
- if self._get_prompt().endswith(b'#'):
- return
- def on_unbecome(self):
- prompt = self._get_prompt()
- if prompt is None:
- # if prompt is None most likely the terminal is hung up at a prompt
- return
- if b'(config' in prompt:
- self._exec_cli_command(b'end')
- (ansible-latest) [dcc@mbp ~/lang/python/sohonet_ansible]$ cat /Users/dcc/venvs/ansible-latest/lib/python2.7/site-packages/ansible/plugins/cliconf/EM316LNXNM.py
- from __future__ import (absolute_import, division, print_function)
- __metaclass__ = type
- import re
- import json
- from itertools import chain
- from ansible.module_utils._text import to_text
- from ansible.module_utils.network.common.utils import to_list
- from ansible.plugins.cliconf import CliconfBase
- class Cliconf(CliconfBase):
- def get_device_info(self):
- device_info = {}
- device_info['network_os'] = 'EM316LNXNM'
- reply = self.get('show version')
- data = to_text(reply, errors='surrogate_or_strict').strip()
- match = re.search(r'EM316LNXNM\s(v\S+\s\S+\s\S+)', data)
- if match:
- device_info['network_os_version'] = match.group(1)
- device_info['network_os_model'] = 'EM316LNXNM'
- return device_info
- def get_config(self, source='running', format='text', flags=None):
- return self.send_command('show running-config')
- def edit_config(self, candidate=None, commit=True, replace=None, comment=None):
- resp = {}
- operations = self.get_device_operations()
- self.check_edit_config_capability(operations, candidate, commit, replace, comment)
- results = []
- requests = []
- if commit:
- self.send_command('configure terminal')
- for line in to_list(candidate):
- if not isinstance(line, Mapping):
- line = {'command': line}
- cmd = line['command']
- if cmd != 'end' and cmd[0] != '!':
- results.append(self.send_command(**line))
- requests.append(cmd)
- self.send_command('end')
- else:
- raise ValueError('check mode is not supported')
- resp['request'] = requests
- resp['response'] = results
- return resp
- def edit_macro(self, candidate=None, commit=True, replace=None, comment=None):
- resp = {}
- operations = self.get_device_operations()
- self.check_edit_config_capabiltiy(operations, candidate, commit, replace, comment)
- results = []
- requests = []
- if commit:
- commands = ''
- for line in candidate:
- if line != 'None':
- commands += (' ' + line + '\n')
- self.send_command('config terminal', sendonly=True)
- obj = {'command': commands, 'sendonly': True}
- results.append(self.send_command(**obj))
- requests.append(commands)
- self.send_command('end', sendonly=True)
- time.sleep(0.1)
- results.append(self.send_command('\n'))
- requests.append('\n')
- resp['request'] = requests
- resp['response'] = results
- return resp
- def get(self, command=None, prompt=None, answer=None, sendonly=False, output=None, check_all=False):
- if not command:
- raise ValueError('must provide value of command to execute')
- if output:
- raise ValueError("'output' value %s is not supported for get" % output)
- return self.send_command(command=command, prompt=prompt, answer=answer, sendonly=sendonly, check_all=check_all)
- def get_option_values(self):
- return {
- 'format': ['text'],
- 'diff_match': ['line', 'strict', 'exact', 'none'],
- 'diff_replace': ['line', 'block'],
- 'output': ['text']
- }
- def get_capabilities(self):
- result = dict()
- result['rpc'] = self.get_base_rpc()
- result['network_api'] = 'cliconf'
- result['device_info'] = self.get_device_info()
- result['device_operations'] = self.get_device_operations()
- result.update(self.get_option_values())
- return json.dumps(result)
- def get_device_operations(self):
- return {
- 'supports_diff_replace': False,
- 'supports_commit': False,
- 'supports_rollback': False,
- 'supports_defaults': True,
- 'supports_onbox_diff': False,
- 'supports_commit_comment': False,
- 'supports_multiline_delimiter': True,
- 'supports_diff_match': False,
- 'supports_diff_ignore_lines': False,
- 'supports_generate_diff': False,
- 'supports_replace': False
- }
- (ansible-latest) [dcc@mbp ~/lang/python/sohonet_ansible]$ cat /Users/dcc/venvs/ansible-latest/lib/python2.7/site-packages/ansible/modules/network/EM316LNXNM/EM316LNXNM_command.py
- #!/usr/bin/python
- from __future__ import (absolute_import, division, print_function)
- __metaclass__ = type
- ANSIBLE_METADATA = {'metadata_version': '1.1',
- 'status': ['preview'],
- 'supported_by': 'community'}
- import time
- from ansible.module_utils._text import to_text
- from ansible.module_utils.basic import AnsibleModule
- from ansible.module_utils.network.common.parsing import Conditional
- from ansible.module_utils.network.common.utils import ComplexList
- from ansible.module_utils.network.edgeos.edgeos import run_commands
- from ansible.module_utils.six import string_types
- def to_lines(stdout):
- for item in stdout:
- if isinstance(item, string_types):
- item = to_text(item).split('\n')
- yield item
- def parse_commands(module, warnings):
- spec = dict(
- command=dict(key=True),
- prompt=dict(),
- answer=dict(),
- )
- transform = ComplexList(spec, module)
- commands = transform(module.params['commands'])
- if module.check_mode:
- for item in list(commands):
- if not item['command'].startswith('show'):
- warnings.append(
- 'Only show commands are supported when using check_mode, '
- 'not executing %s' % item['command'])
- commands.remove(item)
- return commands
- def main():
- spec = dict(
- commands=dict(type='list', required=True),
- wait_for=dict(type='list'),
- match=dict(default='all', choices=['all', 'any']),
- retries=dict(default=10, type='int'),
- interval=dict(default=1, type='int')
- )
- module = AnsibleModule(argument_spec=spec, supports_check_mode=True)
- warnings = list()
- result = {'changed': False}
- commands = parse_commands(module, warnings)
- wait_for = module.params['wait_for'] or list()
- try:
- conditionals = [Conditional(c) for c in wait_for]
- except AttributeError as e:
- module.fail_json(msg=to_text(e))
- retries = module.params['retries']
- interval = module.params['interval']
- match = module.params['match']
- while retries > 0:
- responses = run_commands(module, commands)
- for item in list(conditionals):
- if item(responses):
- if match == 'any':
- conditionals = list()
- break
- conditionals.remove(item)
- if not conditionals:
- break
- time.sleep(interval)
- retries -= 1
- if conditionals:
- failed_conditions = [item.raw for item in conditionals]
- msg = 'One or more conditional statements have not been satisfied'
- module.fail_json(msg=msg, failed_conditions=failed_conditions)
- result = {
- 'changed': False,
- 'stdout': responses,
- 'warnings': warnings,
- 'stdout_lines': list(to_lines(responses))
- }
- module.exit_json(**result)
- if __name__ == '__main__':
- main()
- (ansible-latest) [dcc@mbp ~/lang/python/sohonet_ansible]$ cat /Users/dcc/venvs/ansible-latest/lib/python2.7/site-packages/ansible/modules/network/EM316LNXNM/EM316LNXNM_config.py
- #!/usr/bin/python
- ANSIBLE_METADATA = {'metadata_version': '1.1',
- 'status': ['preview'],
- 'supported_by': 'community'}
- import json
- from ansible.module_utils._text import to_text
- from ansible.module_utils.connection import ConnectionError
- from ansible.module_utils.network.EM316LNXNM.EM316LNXNM import run_commands, get_config
- from ansible.module_utils.basic import AnsibleModule
- from ansible.module_utils.network.common.config import NetworkConfig, dumps
- def save_config(module, result):
- result['changed'] = True
- if not module.check_mode:
- run_commands(module, 'write file\r')
- else:
- module.warn('Skipping command `write term` due to check_mode. '
- 'Configuration not copied to non-volatile storage')
- def main():
- spec = dict(
- src=dict(type='path'),
- lines=dict(type='list'),
- match=dict(default='line', choices=['line', 'none']),
- comment=dict(default=DEFAULT_COMMENT),
- config=dict(),
- backup=dict(type='bool', default=False),
- save=dict(type='bool', default=False),
- )
- mutually_exclusive = [('lines', 'src')]
- module = AnsibleModule(
- argument_spec=spec,
- mutually_exclusive=mutually_exclusive,
- supports_check_mode=True
- )
- warnings = list()
- result = dict(changed=False, warnings=warnings)
- if module.params['backup']:
- result['__backup__'] = get_config(module=module)
- if any((module.params['src'], module.params['lines'])):
- run(module, result)
- running_config = module.params['running_config']
- startup_config = None
- if module.params['save_when'] == 'always' or module.params['save']:
- save_config(module, result)
- elif module.params['save_when'] == 'modified':
- output = run_commands(module, ['show running-config', 'show startup-config'])
- running_config = NetworkConfig(indent=1, contents=output[0], ignore_lines=diff_ignore_lines)
- startup_config = NetworkConfig(indent=1, contents=output[1], ignore_lines=diff_ignore_lines)
- if running_config.sha1 != startup_config.sha1:
- save_config(module, result)
- elif module.params['save_when'] == 'changed' and result['changed']:
- save_config(module, result)
- #if module.params['save']:
- # diff = run_commands(module, commands=['configure', 'compare saved'])[1]
- # if diff != '[edit]':
- # run_commands(module, commands=['save'])
- # result['changed'] = True
- # run_commands(module, commands=['exit'])
- module.exit_json(**result)
- if __name__ == '__main__':
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement