def execute_module(self):
        """ Execute the module

        :rtype: A dictionary
        :returns: The result from module execution
        """
        result = {'changed': False}
        warnings = list()

        existing_l2_interfaces_facts = self.get_l2_interfaces_facts()
        commands, requests = self.set_config(existing_l2_interfaces_facts)

        if commands:
            if not self._module.check_mode:
                try:
                    edit_config(self._module,
                                to_request(self._module, requests))
                except ConnectionError as exc:
                    self._module.fail_json(msg=str(exc), code=exc.code)
            result['changed'] = True
        result['commands'] = commands

        changed_l2_interfaces_facts = self.get_l2_interfaces_facts()

        result['before'] = existing_l2_interfaces_facts
        if result['changed']:
            result['after'] = changed_l2_interfaces_facts

        result['warnings'] = warnings
        return result
def initiate_request(module):
    """Get all the data available in chassis"""
    url = module.params['url']
    body = module.params['body']
    method = module.params['method']
    if method == "GET" or method == "DELETE":
        request = to_request(module, [{"path": url, "method": method}])
        response = edit_config(module, request)
    elif method == "PATCH" or method == "PUT" or method == "POST":
        request = to_request(module, [{
            "path": url,
            "method": method,
            "data": body
        }])
        response = edit_config(module, request)
    return response
예제 #3
0
    def get_all_interfaces(self):
        """Get all the interfaces available in chassis"""
        all_interfaces = {}
        request = [{
            "path": "data/openconfig-interfaces:interfaces",
            "method": GET
        }]
        try:
            response = edit_config(self._module,
                                   to_request(self._module, request))
        except ConnectionError as exc:
            self._module.fail_json(msg=str(exc), code=exc.code)

        if "openconfig-interfaces:interfaces" in response[0][1]:
            all_interfaces = response[0][1].get(
                "openconfig-interfaces:interfaces", {})
        return all_interfaces['interface']
 def get_all_portchannels(self):
     """Get all the interfaces available in chassis"""
     request = [{
         "path": "data/sonic-portchannel:sonic-portchannel",
         "method": GET
     }]
     try:
         response = edit_config(self._module,
                                to_request(self._module, request))
     except ConnectionError as exc:
         self._module.fail_json(msg=str(exc), code=exc.code)
     if response[0][1]:
         data = response[0][1]['sonic-portchannel:sonic-portchannel']
     else:
         data = []
     if data is not None:
         if "PORTCHANNEL_MEMBER" in data:
             portchannel_members_list = data["PORTCHANNEL_MEMBER"][
                 "PORTCHANNEL_MEMBER_LIST"]
         else:
             portchannel_members_list = []
         if "PORTCHANNEL" in data:
             portchannel_list = data["PORTCHANNEL"]["PORTCHANNEL_LIST"]
         else:
             portchannel_list = []
         if portchannel_list:
             for i in portchannel_list:
                 if not any(d["name"] == i["name"]
                            for d in portchannel_members_list):
                     portchannel_members_list.append({
                         'ifname': None,
                         'name': i['name']
                     })
     if data:
         return portchannel_members_list
     else:
         return []
예제 #5
0
    def get_l3_interfaces(self):
        url = "data/openconfig-interfaces:interfaces/interface"
        method = "GET"
        request = [{"path": url, "method": method}]

        try:
            response = edit_config(self._module,
                                   to_request(self._module, request))
        except ConnectionError as exc:
            self._module.fail_json(msg=str(exc), code=exc.code)

        l3_lists = []
        if "openconfig-interfaces:interface" in response[0][1]:
            l3_lists = response[0][1].get("openconfig-interfaces:interface",
                                          [])
        l3_configs = []
        for l3 in l3_lists:
            l3_dict = dict()
            l3_name = l3["name"]
            if l3_name == "eth0":
                continue

            if l3.get('subinterfaces'):
                l3_subinterfaces = l3['subinterfaces']
                if l3_subinterfaces.get('subinterface'):
                    l3_subinterface = l3_subinterfaces['subinterface']

            ip = l3_subinterface[0]

            l3_ipv4 = list()
            if 'openconfig-if-ip:ipv4' in ip and 'addresses' in ip[
                    'openconfig-if-ip:ipv4'] and 'address' in ip[
                        'openconfig-if-ip:ipv4']['addresses']:
                for ipv4 in ip['openconfig-if-ip:ipv4']['addresses'][
                        'address']:
                    if ipv4.get('config') and ipv4.get('config').get('ip'):
                        temp = dict()
                        temp['address'] = str(
                            ipv4['config']['ip']) + '/' + str(
                                ipv4['config']['prefix-length'])
                        l3_ipv4.append(temp)

            l3_ipv6 = list()
            if 'openconfig-if-ip:ipv6' in ip and 'addresses' in ip[
                    'openconfig-if-ip:ipv6'] and 'address' in ip[
                        'openconfig-if-ip:ipv6']['addresses']:
                for ipv6 in ip['openconfig-if-ip:ipv6']['addresses'][
                        'address']:
                    if ipv6.get('config') and ipv6.get('config').get('ip'):
                        temp = dict()
                        temp['address'] = str(
                            ipv6['config']['ip']) + '/' + str(
                                ipv6['config']['prefix-length'])
                        l3_ipv6.append(temp)

            l3_dict['name'] = l3_name
            l3_dict['ipv4'] = l3_ipv4
            l3_dict['ipv6'] = l3_ipv6
            l3_configs.append(l3_dict)
        # with open('/root/ansible_log.log', 'a+') as fp:
        #     fp.write('l3_configs: ' + str(l3_configs) + '\n')
        return l3_configs
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'),
        save=dict(type='bool', default=False),
    )

    mutually_exclusive = [('lines', 'src')]

    module = AnsibleModule(argument_spec=argument_spec,
                           mutually_exclusive=mutually_exclusive,
                           supports_check_mode=True)

    warnings = list()
    #    check_args(module, warnings)

    result = dict(changed=False, saved=False, warnings=warnings)

    commands = list()
    candidate = get_candidate(module)

    if any((module.params['lines'], module.params['src'])):
        configobjs = candidate.items

        if configobjs:
            commands = dumps(configobjs, 'commands')
            if ((isinstance((module.params['lines']), list)) and (isinstance(
                (module.params['lines'][0]), dict))
                    and (set(['prompt', 'answer']).issubset(
                        module.params['lines'][0]))):

                cmd = {
                    'command': commands,
                    'prompt': module.params['lines'][0]['prompt'],
                    'answer': module.params['lines'][0]['answer']
                }
                commands = [cmd]
            else:
                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:
                edit_config(module, commands)

            result['changed'] = True
            result['commands'] = commands
            result['updates'] = commands

    if module.params['save']:
        result['changed'] = True
        if not module.check_mode:
            cmd = {r'command': ' write memory'}
            run_commands(module, [cmd])
            result['saved'] = True

    module.exit_json(**result)