def main(): """ main entry point for module execution """ element_spec = dict( name=dict(), full_name=dict(), role=dict(choices=ROLES), encrypted_password=dict(), sshkey=dict(), state=dict(choices=['present', 'absent'], default='present'), active=dict(type='bool', default=True) ) aggregate_spec = deepcopy(element_spec) aggregate_spec['name'] = dict(required=True) # remove default in aggregate spec, to handle common arguments remove_default_spec(aggregate_spec) argument_spec = dict( aggregate=dict(type='list', elements='dict', options=aggregate_spec, aliases=['collection', 'users']), purge=dict(default=False, type='bool') ) argument_spec.update(element_spec) argument_spec.update(junos_argument_spec) mutually_exclusive = [['aggregate', 'name']] module = AnsibleModule(argument_spec=argument_spec, mutually_exclusive=mutually_exclusive, supports_check_mode=True) warnings = list() result = {'changed': False, 'warnings': warnings} want = map_params_to_obj(module) ele = map_obj_to_ele(module, want) purge_request = None if module.params['purge']: purge_request = handle_purge(module, want) with locked_config(module): if purge_request: load_config(module, tostring(purge_request), warnings, action='replace') diff = load_config(module, tostring(ele), warnings, action='merge') commit = not module.check_mode if diff: if commit: commit_configuration(module) else: discard_changes(module) result['changed'] = True if module._diff: result['diff'] = {'prepared': diff} module.exit_json(**result)
def set_state(self, want, have): """ Select the appropriate function based on the state provided :param want: the desired configuration as a dictionary :param have: the current configuration as a dictionary :rtype: A list :returns: the commands necessary to migrate the current configuration to the desired configuration """ state = self._module.params['state'] root = build_root_xml_node('configuration') routing_options = build_child_xml_node(root, 'routing-options') routing_instances = build_child_xml_node(root, 'routing-instances') if state == 'overridden': config_xmls = self._state_overridden(want, have) elif state == 'deleted': config_xmls = self._state_deleted(want, have) elif state == 'merged': config_xmls = self._state_merged(want, have) elif state == 'replaced': config_xmls = self._state_replaced(want, have) for xml in config_xmls: if xml['root_type'] == 'routing-options': routing_options.append(xml['static_route_xml']) elif xml['root_type'] == 'routing-instances': routing_instances.append(xml['static_route_xml']) return [tostring(xml) for xml in root.getchildren()]
def main(): """ main entry point for module execution """ argument_spec = dict( hostname=dict(), domain_name=dict(), domain_search=dict(type='list'), name_servers=dict(type='list'), state=dict(choices=['present', 'absent'], default='present'), active=dict(default=True, type='bool') ) argument_spec.update(junos_argument_spec) params = ['hostname', 'domain_name', 'domain_search', 'name_servers'] required_if = [('state', 'present', params, True), ('state', 'absent', params, True), ('state', 'active', params, True), ('state', 'suspend', params, True)] module = AnsibleModule(argument_spec=argument_spec, required_if=required_if, supports_check_mode=True) warnings = list() result = {'changed': False} if warnings: result['warnings'] = warnings top = 'system' param_to_xpath_map = collections.OrderedDict() param_to_xpath_map.update([ ('hostname', {'xpath': 'host-name', 'leaf_only': True}), ('domain_name', {'xpath': 'domain-name', 'leaf_only': True}), ('domain_search', {'xpath': 'domain-search', 'leaf_only': True, 'value_req': True}), ('name_servers', {'xpath': 'name-server/name', 'is_key': True}) ]) validate_param_values(module, param_to_xpath_map) want = map_params_to_obj(module, param_to_xpath_map) ele = map_obj_to_ele(module, want, top) with locked_config(module): diff = load_config(module, tostring(ele), warnings, action='merge') commit = not module.check_mode if diff: if commit: commit_configuration(module) else: discard_changes(module) result['changed'] = True if module._diff: result['diff'] = {'prepared': diff} module.exit_json(**result)
def set_state(self, want, have): """ Select the appropriate function based on the state provided :param want: the desired configuration as a dictionary :param have: the current configuration as a dictionary :rtype: A list :returns: the commands necessary to migrate the current configuration to the desired configuration """ root = build_root_xml_node('protocols') lldp_intf_ele = build_subtree(root, 'lldp') state = self._module.params['state'] if state == 'overridden': config_xmls = self._state_overridden(want, have) elif state == 'deleted': config_xmls = self._state_deleted(want, have) elif state == 'merged': config_xmls = self._state_merged(want, have) elif state == 'replaced': config_xmls = self._state_replaced(want, have) for xml in config_xmls: lldp_intf_ele.append(xml) return tostring(root)
def main(): """ main entry point for module execution """ argument_spec = dict( interval=dict(type='int'), transmit_delay=dict(type='int'), hold_multiplier=dict(type='int'), state=dict(default='present', choices=['present', 'absent', 'enabled', 'disabled']), active=dict(default=True, type='bool') ) argument_spec.update(junos_argument_spec) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) warnings = list() result = {'changed': False} if warnings: result['warnings'] = warnings top = 'protocols/lldp' param_to_xpath_map = collections.OrderedDict() param_to_xpath_map.update([ ('interval', {'xpath': 'advertisement-interval', 'leaf_only': True}), ('transmit_delay', {'xpath': 'transmit-delay', 'leaf_only': True}), ('hold_multiplier', {'xpath': 'hold-multiplier', 'leaf_only': True}), ('disable', {'xpath': 'disable', 'tag_only': True, 'is_key': True}) ]) item = module.params.copy() state = item.get('state') item['disable'] = True if state in ('disabled', 'absent') else False if state in ('enabled', 'disabled'): item['state'] = 'present' want = map_params_to_obj(module, param_to_xpath_map, param=item) ele = map_obj_to_ele(module, want, top, param=item) with locked_config(module): diff = load_config(module, tostring(ele), warnings, action='merge') commit = not module.check_mode if diff: if commit: commit_configuration(module) else: discard_changes(module) result['changed'] = True if module._diff: result['diff'] = {'prepared': diff} module.exit_json(**result)
def get_resource_config(connection, config_filter=None, attrib=None): if attrib is None: attrib = {'inherit': 'inherit'} get_ele = new_ele('get-configuration', attrib) if config_filter: get_ele.append(to_ele(config_filter)) return connection.execute_rpc(tostring(get_ele))
def main(): """ main entry point for module execution """ argument_spec = dict(banner=dict(required=True, choices=['login', 'motd']), text=dict(), state=dict(default='present', choices=['present', 'absent']), active=dict(default=True, type='bool')) argument_spec.update(junos_argument_spec) required_if = [('state', 'present', ('text', ))] module = AnsibleModule(argument_spec=argument_spec, required_if=required_if, supports_check_mode=True) warnings = list() result = {'changed': False} if warnings: result['warnings'] = warnings top = 'system/login' param_to_xpath_map = collections.OrderedDict() param_to_xpath_map.update([('text', { 'xpath': 'message' if module.params['banner'] == 'login' else 'announcement', 'leaf_only': True })]) validate_param_values(module, param_to_xpath_map) want = map_params_to_obj(module, param_to_xpath_map) ele = map_obj_to_ele(module, want, top) with locked_config(module): diff = load_config(module, tostring(ele), warnings, action='merge') commit = not module.check_mode if diff: if commit: commit_configuration(module) else: discard_changes(module) result['changed'] = True if module._diff: result['diff'] = {'prepared': diff} module.exit_json(**result)
def populate(self): config_format = self.module.params['config_format'] reply = get_configuration(self.module, format=config_format) if config_format == 'xml': config = tostring(reply.find('configuration')).strip() elif config_format == 'text': config = self.get_text(reply, 'configuration-text') elif config_format == 'json': config = self.module.from_json(reply.text.strip()) elif config_format == 'set': config = self.get_text(reply, 'configuration-set') self.facts['config'] = config
def handle_purge(module, want): want_users = [item['name'] for item in want] element = Element('system') login = SubElement(element, 'login') conn = get_connection(module) reply = conn.execute_rpc(tostring(Element('get-configuration')), ignore_warning=False) users = reply.xpath('configuration/system/login/user/name') if users: for item in users: name = item.text if name not in want_users and name != 'root': user = SubElement(login, 'user', {'operation': 'delete'}) SubElement(user, 'name').text = name if element.xpath('/system/login/user/name'): return element
def populate(self): ele = Element('get-interface-information') SubElement(ele, 'detail') reply = exec_rpc(self.module, tostring(ele)) interfaces = {} for item in reply[0]: name = self.get_text(item, 'name') obj = { 'oper-status': self.get_text(item, 'oper-status'), 'admin-status': self.get_text(item, 'admin-status'), 'speed': self.get_text(item, 'speed'), 'macaddress': self.get_text(item, 'hardware-physical-address'), 'mtu': self.get_text(item, 'mtu'), 'type': self.get_text(item, 'if-type'), } interfaces[name] = obj self.facts['interfaces'] = interfaces
def rpc(self, rpc): return exec_rpc(self.module, tostring(Element(rpc)))
def main(): """ main entry point for module execution """ element_spec = dict(name=dict(), ipv4=dict(), ipv6=dict(), unit=dict(default=0, type='int'), state=dict(default='present', choices=['present', 'absent']), active=dict(default=True, type='bool')) aggregate_spec = deepcopy(element_spec) aggregate_spec['name'] = dict(required=True) # remove default in aggregate spec, to handle common arguments remove_default_spec(aggregate_spec) argument_spec = dict(aggregate=dict(type='list', elements='dict', options=aggregate_spec), ) argument_spec.update(element_spec) argument_spec.update(junos_argument_spec) required_one_of = [['name', 'aggregate']] mutually_exclusive = [['name', 'aggregate']] module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True, mutually_exclusive=mutually_exclusive, required_one_of=required_one_of) warnings = list() result = {'changed': False} if warnings: result['warnings'] = warnings top = 'interfaces/interface' param_to_xpath_map = collections.OrderedDict() param_to_xpath_map.update([('name', { 'xpath': 'name', 'parent_attrib': False, 'is_key': True }), ('unit', { 'xpath': 'name', 'top': 'unit', 'parent_attrib': False, 'is_key': True }), ('ipv4', { 'xpath': 'inet/address/name', 'top': 'unit/family', 'is_key': True }), ('ipv6', { 'xpath': 'inet6/address/name', 'top': 'unit/family', 'is_key': True })]) params = to_param_list(module) requests = list() for param in params: # if key doesn't exist in the item, get it from module.params for key in param: if param.get(key) is None: param[key] = module.params[key] item = param.copy() if not item['ipv4'] and not item['ipv6']: module.fail_json(msg="one of the following is required: ipv4,ipv6") want = map_params_to_obj(module, param_to_xpath_map, param=item) requests.append(map_obj_to_ele(module, want, top, param=item)) diff = None with locked_config(module): for req in requests: diff = load_config(module, tostring(req), warnings, action='merge') commit = not module.check_mode if diff: if commit: commit_configuration(module) else: discard_changes(module) result['changed'] = True if module._diff: result['diff'] = {'prepared': diff} module.exit_json(**result)
def main(): """ main entry point for module execution """ element_spec = dict(name=dict(), mode=dict(choices=['access', 'trunk']), access_vlan=dict(), native_vlan=dict(type='int'), trunk_vlans=dict(type='list'), unit=dict(default=0, type='int'), filter_input=dict(), filter_output=dict(), description=dict(), enhanced_layer=dict(default=True, type='bool'), state=dict(default='present', choices=['present', 'absent']), active=dict(default=True, type='bool')) aggregate_spec = deepcopy(element_spec) aggregate_spec['name'] = dict(required=True) # remove default in aggregate spec, to handle common arguments remove_default_spec(aggregate_spec) required_one_of = [['name', 'aggregate']] mutually_exclusive = [['name', 'aggregate'], ['access_vlan', 'trunk_vlans'], ['access_vlan', 'native_vlan']] required_if = [('mode', 'access', ('access_vlan', )), ('mode', 'trunk', ('trunk_vlans', ))] argument_spec = dict(aggregate=dict(type='list', elements='dict', options=aggregate_spec, mutually_exclusive=mutually_exclusive, required_if=required_if), ) argument_spec.update(element_spec) argument_spec.update(junos_argument_spec) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True, mutually_exclusive=mutually_exclusive, required_one_of=required_one_of, required_if=required_if) warnings = list() result = {'changed': False} if warnings: result['warnings'] = warnings top = 'interfaces/interface' param_to_xpath_map = collections.OrderedDict() param_to_xpath_map.update([('name', { 'xpath': 'name', 'is_key': True }), ('unit', { 'xpath': 'name', 'top': 'unit', 'is_key': True }), ('mode', { 'xpath': 'interface-mode', 'top': 'unit/family/ethernet-switching' }), ('access_vlan', { 'xpath': 'members', 'top': 'unit/family/ethernet-switching/vlan' }), ('trunk_vlans', { 'xpath': 'members', 'top': 'unit/family/ethernet-switching/vlan' }), ('filter_input', { 'xpath': 'input', 'top': 'unit/family/ethernet-switching/filter' }), ('filter_output', { 'xpath': 'output', 'top': 'unit/family/ethernet-switching/filter' }), ('native_vlan', { 'xpath': 'native-vlan-id' }), ('description', 'description')]) params = to_param_list(module) requests = list() for param in params: # if key doesn't exist in the item, get it from module.params for key in param: if param.get(key) is None: param[key] = module.params[key] item = param.copy() validate_param_values(module, param_to_xpath_map, param=item) param_to_xpath_map['mode']['xpath'] = \ 'interface-mode' if param['enhanced_layer'] else 'port-mode' want = map_params_to_obj(module, param_to_xpath_map, param=item) requests.append(map_obj_to_ele(module, want, top, param=item)) diff = None with locked_config(module): for req in requests: diff = load_config(module, tostring(req), warnings, action='replace') commit = not module.check_mode if diff: if commit: commit_configuration(module) else: discard_changes(module) result['changed'] = True if module._diff: result['diff'] = {'prepared': diff} module.exit_json(**result)
def main(): """ main entry point for module execution """ element_spec = dict(address=dict(aliases=['prefix']), next_hop=dict(), preference=dict(type='int', aliases=['admin_distance']), qualified_next_hop=dict(type='str'), qualified_preference=dict(type='int'), state=dict(default='present', choices=['present', 'absent']), active=dict(default=True, type='bool')) aggregate_spec = deepcopy(element_spec) aggregate_spec['address'] = dict(required=True) # remove default in aggregate spec, to handle common arguments remove_default_spec(aggregate_spec) argument_spec = dict(aggregate=dict(type='list', elements='dict', options=aggregate_spec), purge=dict(default=False, type='bool')) argument_spec.update(element_spec) argument_spec.update(junos_argument_spec) required_one_of = [['aggregate', 'address']] mutually_exclusive = [['aggregate', 'address']] module = AnsibleModule(argument_spec=argument_spec, required_one_of=required_one_of, mutually_exclusive=mutually_exclusive, supports_check_mode=True) warnings = list() result = {'changed': False} if warnings: result['warnings'] = warnings top = 'routing-options/static/route' param_to_xpath_map = collections.OrderedDict() param_to_xpath_map.update([('address', { 'xpath': 'name', 'is_key': True }), ('next_hop', 'next-hop'), ('preference', 'preference/metric-value'), ('qualified_next_hop', { 'xpath': 'name', 'top': 'qualified-next-hop' }), ('qualified_preference', { 'xpath': 'preference', 'top': 'qualified-next-hop' })]) params = to_param_list(module) requests = list() for param in params: # if key doesn't exist in the item, get it from module.params for key in param: if param.get(key) is None: param[key] = module.params[key] item = param.copy() if item['state'] == 'present': if not item['address'] and item['next_hop']: module.fail_json( msg= "parameters are required together: ['address', 'next_hop']" ) want = map_params_to_obj(module, param_to_xpath_map, param=item) requests.append(map_obj_to_ele(module, want, top, param=item)) with locked_config(module): for req in requests: diff = load_config(module, tostring(req), warnings, action='merge') commit = not module.check_mode if diff: if commit: commit_configuration(module) else: discard_changes(module) result['changed'] = True if module._diff: result['diff'] = {'prepared': diff} module.exit_json(**result)
def main(): """ main entry point for module execution """ element_spec = dict(name=dict(), mode=dict(default='on', choices=['on', 'off', 'active', 'passive']), members=dict(type='list'), min_links=dict(type='int'), device_count=dict(type='int'), description=dict(), state=dict(default='present', choices=['present', 'absent', 'up', 'down']), active=dict(default=True, type='bool')) aggregate_spec = deepcopy(element_spec) aggregate_spec['name'] = dict(required=True) # remove default in aggregate spec, to handle common arguments remove_default_spec(aggregate_spec) argument_spec = dict(aggregate=dict(type='list', elements='dict', options=aggregate_spec), ) argument_spec.update(element_spec) argument_spec.update(junos_argument_spec) required_one_of = [['name', 'aggregate']] mutually_exclusive = [['name', 'aggregate']] module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True, required_one_of=required_one_of, mutually_exclusive=mutually_exclusive) warnings = list() result = {'changed': False} if warnings: result['warnings'] = warnings params = to_param_list(module) requests = list() for param in params: # if key doesn't exist in the item, get it from module.params for key in param: if param.get(key) is None: param[key] = module.params[key] item = param.copy() state = item.get('state') item['disable'] = True if state == 'down' else False if state in ('present', 'up', 'down'): item['state'] = 'present' else: item['disable'] = True mode = item.get('mode') if mode == 'off': item['mode'] = '' elif mode == 'on': item['mode'] = 'passive' configure_lag_params(module, requests, item) configure_member_params(module, requests, item) diff = None with locked_config(module): for req in requests: diff = load_config(module, tostring(req), warnings, action='merge') commit = not module.check_mode if diff: if commit: commit_configuration(module) else: discard_changes(module) result['changed'] = True if module._diff: result['diff'] = {'prepared': diff} module.exit_json(**result)
def main(): """main entry point for Ansible module """ argument_spec = dict( rpc=dict(required=True), args=dict(type='dict'), attrs=dict(type='dict'), output=dict(default='xml', choices=['xml', 'json', 'text']), ) argument_spec.update(junos_argument_spec) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=False) warnings = list() result = {'changed': False, 'warnings': warnings} 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 {} attrs = module.params['attrs'] or {} xattrs = {'format': module.params['output']} for key, value in iteritems(attrs): xattrs.update({key: value}) element = Element(module.params['rpc'], xattrs) for key, value in iteritems(args): key = str(key).replace('_', '-') if isinstance(value, list): for item in value: child = SubElement(element, key) if item is not True: child.text = item else: child = SubElement(element, key) if value is not True: child.text = value reply = exec_rpc(module, tostring(element), ignore_warning=False) result['xml'] = tostring(reply) if module.params['output'] == 'text': data = reply.find('.//output') result['output'] = data.text.strip() result['output_lines'] = result['output'].split('\n') elif module.params['output'] == 'json': result['output'] = module.from_json(reply.text.strip()) else: result['output'] = tostring(reply).split('\n') module.exit_json(**result)
def main(): """ main entry point for module execution """ neighbors_spec = dict( host=dict(), port=dict() ) element_spec = dict( name=dict(), description=dict(), enabled=dict(default=True, type='bool'), speed=dict(), mtu=dict(type='int'), duplex=dict(choices=['full', 'half', 'auto']), tx_rate=dict(), rx_rate=dict(), neighbors=dict(type='list', elements='dict', options=neighbors_spec), delay=dict(default=10, type='int'), state=dict(default='present', choices=['present', 'absent', 'up', 'down']), active=dict(default=True, type='bool') ) aggregate_spec = deepcopy(element_spec) aggregate_spec['name'] = dict(required=True) # remove default in aggregate spec, to handle common arguments remove_default_spec(aggregate_spec) argument_spec = dict( aggregate=dict(type='list', elements='dict', options=aggregate_spec), ) argument_spec.update(element_spec) argument_spec.update(junos_argument_spec) required_one_of = [['name', 'aggregate']] mutually_exclusive = [['name', 'aggregate']] module = AnsibleModule(argument_spec=argument_spec, required_one_of=required_one_of, mutually_exclusive=mutually_exclusive, supports_check_mode=True) warnings = list() result = {'changed': False} if warnings: result['warnings'] = warnings top = 'interfaces/interface' param_to_xpath_map = collections.OrderedDict() param_to_xpath_map.update([ ('name', {'xpath': 'name', 'is_key': True}), ('description', 'description'), ('speed', 'speed'), ('mtu', 'mtu'), ('duplex', 'link-mode'), ('disable', {'xpath': 'disable', 'tag_only': True}) ]) choice_to_value_map = { 'link-mode': {'full': 'full-duplex', 'half': 'half-duplex', 'auto': 'automatic'} } params = to_param_list(module) requests = list() for param in params: # if key doesn't exist in the item, get it from module.params for key in param: if param.get(key) is None: param[key] = module.params[key] item = param.copy() state = item.get('state') item['disable'] = True if not item.get('enabled') else False if state in ('present', 'up', 'down'): item['state'] = 'present' validate_param_values(module, param_to_xpath_map, param=item) want = map_params_to_obj(module, param_to_xpath_map, param=item) requests.append(map_obj_to_ele(module, want, top, value_map=choice_to_value_map, param=item)) diff = None with locked_config(module): for req in requests: diff = load_config(module, tostring(req), warnings, action='merge') # issue commit after last configuration change is done commit = not module.check_mode if diff: if commit: commit_configuration(module) else: discard_changes(module) result['changed'] = True if module._diff: result['diff'] = {'prepared': diff} failed_conditions = [] neighbors = None for item in params: state = item.get('state') tx_rate = item.get('tx_rate') rx_rate = item.get('rx_rate') want_neighbors = item.get('neighbors') if state not in ('up', 'down') and tx_rate is None and rx_rate is None and want_neighbors is None: continue element = Element('get-interface-information') intf_name = SubElement(element, 'interface-name') intf_name.text = item.get('name') if result['changed']: sleep(item.get('delay')) reply = exec_rpc(module, tostring(element), ignore_warning=False) if state in ('up', 'down'): admin_status = reply.xpath('interface-information/physical-interface/admin-status') if not admin_status or not conditional(state, admin_status[0].text.strip()): failed_conditions.append('state ' + 'eq(%s)' % state) if tx_rate: output_bps = reply.xpath('interface-information/physical-interface/traffic-statistics/output-bps') if not output_bps or not conditional(tx_rate, output_bps[0].text.strip(), cast=int): failed_conditions.append('tx_rate ' + tx_rate) if rx_rate: input_bps = reply.xpath('interface-information/physical-interface/traffic-statistics/input-bps') if not input_bps or not conditional(rx_rate, input_bps[0].text.strip(), cast=int): failed_conditions.append('rx_rate ' + rx_rate) if want_neighbors: if neighbors is None: element = Element('get-lldp-interface-neighbors') intf_name = SubElement(element, 'interface-device') intf_name.text = item.get('name') reply = exec_rpc(module, tostring(element), ignore_warning=False) have_host = [item.text for item in reply.xpath('lldp-neighbors-information/lldp-neighbor-information/lldp-remote-system-name')] have_port = [item.text for item in reply.xpath('lldp-neighbors-information/lldp-neighbor-information/lldp-remote-port-id')] for neighbor in want_neighbors: host = neighbor.get('host') port = neighbor.get('port') if host and host not in have_host: failed_conditions.append('host ' + host) if port and port not in have_port: failed_conditions.append('port ' + port) if failed_conditions: msg = 'One or more conditional statements have not been satisfied' module.fail_json(msg=msg, failed_conditions=failed_conditions) module.exit_json(**result)
def rpc(module, items): responses = list() for item in items: name = item['name'] xattrs = item['xattrs'] fetch_config = False args = item.get('args') text = item.get('text') name = str(name).replace('_', '-') if all((module.check_mode, not name.startswith('get'))): module.fail_json(msg='invalid rpc for running in check_mode') if name == 'command' and text.startswith( 'show configuration') or name == 'get-configuration': fetch_config = True element = Element(name, xattrs) if text: element.text = text elif args: for key, value in iteritems(args): key = str(key).replace('_', '-') if isinstance(value, list): for item in value: child = SubElement(element, key) if item is not True: child.text = item else: child = SubElement(element, key) if value is not True: child.text = value if fetch_config: reply = get_configuration(module, format=xattrs['format']) else: reply = exec_rpc(module, tostring(element), ignore_warning=False) if xattrs['format'] == 'text': if fetch_config: data = reply.find('.//configuration-text') else: data = reply.find('.//output') if data is None: module.fail_json(msg=tostring(reply)) responses.append(data.text.strip()) elif xattrs['format'] == 'json': responses.append(module.from_json(reply.text.strip())) elif xattrs['format'] == 'set': data = reply.find('.//configuration-set') if data is None: module.fail_json( msg= "Display format 'set' is not supported by remote device.") responses.append(data.text.strip()) else: responses.append(tostring(reply)) return responses
def main(): """ main entry point for module execution """ element_spec = dict( name=dict(), vlan_id=dict(type='int'), description=dict(), interfaces=dict(), state=dict(default='present', choices=['present', 'absent']), active=dict(default=True, type='bool') ) aggregate_spec = deepcopy(element_spec) aggregate_spec['name'] = dict(required=True) # remove default in aggregate spec, to handle common arguments remove_default_spec(aggregate_spec) argument_spec = dict( aggregate=dict(type='list', elements='dict', options=aggregate_spec) ) argument_spec.update(element_spec) argument_spec.update(junos_argument_spec) required_one_of = [['aggregate', 'name']] mutually_exclusive = [['aggregate', 'name']] module = AnsibleModule(argument_spec=argument_spec, required_one_of=required_one_of, mutually_exclusive=mutually_exclusive, supports_check_mode=True) warnings = list() result = {'changed': False} if warnings: result['warnings'] = warnings top = 'vlans/vlan' param_to_xpath_map = collections.OrderedDict() param_to_xpath_map.update([ ('name', {'xpath': 'name', 'is_key': True}), ('vlan_id', 'vlan-id'), ('description', 'description') ]) params = to_param_list(module) requests = list() for param in params: # if key doesn't exist in the item, get it from module.params for key in param: if param.get(key) is None: param[key] = module.params[key] item = param.copy() validate_param_values(module, param_to_xpath_map, param=item) want = map_params_to_obj(module, param_to_xpath_map, param=item) requests.append(map_obj_to_ele(module, want, top, param=item)) diff = None with locked_config(module): for req in requests: diff = load_config(module, tostring(req), warnings, action='merge') commit = not module.check_mode if diff: if commit: commit_configuration(module) else: discard_changes(module) result['changed'] = True if module._diff: result['diff'] = {'prepared': diff} module.exit_json(**result)
def zeroize(module): return exec_rpc(module, tostring(Element('request-system-zeroize')), ignore_warning=False)
def main(): """ main entry point for module execution """ element_spec = dict( dest=dict(choices=['console', 'host', 'file', 'user']), name=dict(), facility=dict(), level=dict(), rotate_frequency=dict(type='int'), size=dict(type='int'), files=dict(type='int'), src_addr=dict(), state=dict(default='present', choices=['present', 'absent']), active=dict(default=True, type='bool') ) aggregate_spec = deepcopy(element_spec) # remove default in aggregate spec, to handle common arguments remove_default_spec(aggregate_spec) argument_spec = dict( aggregate=dict(type='list', elements='dict', options=aggregate_spec), ) argument_spec.update(element_spec) argument_spec.update(junos_argument_spec) required_if = [('dest', 'host', ['name', 'facility', 'level']), ('dest', 'file', ['name', 'facility', 'level']), ('dest', 'user', ['name', 'facility', 'level']), ('dest', 'console', ['facility', 'level'])] module = AnsibleModule(argument_spec=argument_spec, required_if=required_if, supports_check_mode=True) warnings = list() result = {'changed': False} if warnings: result['warnings'] = warnings params = to_param_list(module) requests = list() for param in params: # if key doesn't exist in the item, get it from module.params for key in param: if param.get(key) is None: param[key] = module.params[key] module._check_required_if(required_if, param) item = param.copy() dest = item.get('dest') if dest == 'console' and item.get('name'): module.fail_json(msg="%s and %s are mutually exclusive" % ('console', 'name')) top = 'system/syslog' is_facility_key = False field_top = None if dest: if dest == 'console': field_top = dest is_facility_key = True else: field_top = dest + '/contents' is_facility_key = False param_to_xpath_map = collections.OrderedDict() param_to_xpath_map.update([ ('name', {'xpath': 'name', 'is_key': True, 'top': dest}), ('facility', {'xpath': 'name', 'is_key': is_facility_key, 'top': field_top}), ('size', {'xpath': 'size', 'leaf_only': True, 'is_key': True, 'top': 'archive'}), ('files', {'xpath': 'files', 'leaf_only': True, 'is_key': True, 'top': 'archive'}), ('rotate_frequency', {'xpath': 'log-rotate-frequency', 'leaf_only': True}), ]) if item.get('level'): param_to_xpath_map['level'] = {'xpath': item.get('level'), 'tag_only': True, 'top': field_top} validate_param_values(module, param_to_xpath_map, param=item) want = map_params_to_obj(module, param_to_xpath_map, param=item) requests.append(map_obj_to_ele(module, want, top, param=item)) diff = None with locked_config(module): for req in requests: diff = load_config(module, tostring(req), warnings, action='merge') commit = not module.check_mode if diff: if commit: commit_configuration(module) else: discard_changes(module) result['changed'] = True if module._diff: result['diff'] = {'prepared': diff} module.exit_json(**result)
def populate(self): self.facts['all_ipv4_addresses'] = list() self.facts['all_ipv6_addresses'] = list() ele = Element('get-interface-information') SubElement(ele, 'detail') reply = exec_rpc(self.module, tostring(ele)) interfaces = {} for item in reply[0]: name = self.get_text(item, 'name') mac = self.get_text(item, 'hardware-physical-address') obj = { 'oper-status': self.get_text(item, 'oper-status'), 'admin-status': self.get_text(item, 'admin-status'), 'speed': self.get_text(item, 'speed'), 'macaddress': mac, 'mtu': self.get_text(item, 'mtu'), 'type': self.get_text(item, 'if-type'), } if mac != 'Unspecified': interfaces[name] = obj logint = item.findall('logical-interface') for log in logint: name = self.get_text(log, 'name') obj = { 'description': self.get_text(log, 'description'), 'encapsulation': self.get_text(log, 'encapsulation'), } try: addr = str(log.find('address-family').find('interface-address').find('ifa-local').text).strip() net = str(log.find('address-family').find('interface-address').find('ifa-destination').text).strip() if net == 'Unspecified': masklen = '32' else: ip = IPNetwork(net) masklen = ip.prefixlen if addr != '127.0.0.1': if str(log.find('address-family').find('address-family-name').text).strip() == 'inet': self.facts['all_ipv4_addresses'].append(addr) obj.update({'ipv4': [{'address': addr, 'masklen': masklen}]}) if str(log.find('address-family').find('address-family-name').text).strip() == 'inet6': self.facts['all_ipv6_addresses'].append(addr) obj.update({'ipv6': [{'address': addr, 'masklen': masklen}]}) except AttributeError: addr = '' masklen = '' try: mtu = str(log.find('address-family').find('mtu').text).strip() obj.update({'mtu': mtu}) except AttributeError: mtu = '' try: vlan = str(log.find('link-address').text) obj.update({'vlan': vlan.split('.')[1][:-2].strip()}) except AttributeError: vlan = '' if name.find('local') == -1: interfaces[name] = obj rele = Element('get-instance-information') SubElement(rele, 'detail') instances = exec_rpc(self.module, tostring(rele)) for instance in instances[0]: vrfname = self.get_text(instance, 'instance-name') rint = instance.findall('instance-interface') for r in rint: intname = self.get_text(r, 'interface-name') interfaces[intname].update({'vrf': vrfname}) self.facts['interfaces'] = interfaces