コード例 #1
0
ファイル: bgp_af.py プロジェクト: hyposcaler/dellemc.sonic
    def execute_module(self):
        """ Execute the module

        :rtype: A dictionary
        :returns: The result from module execution
        """
        result = {'changed': False}
        warnings = list()
        existing_bgp_af_facts = self.get_bgp_af_facts()
        commands, requests = self.set_config(existing_bgp_af_facts)
        if commands and len(requests) > 0:
            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_bgp_af_facts = self.get_bgp_af_facts()

        result['before'] = existing_bgp_af_facts
        if result['changed']:
            result['after'] = changed_bgp_af_facts

        result['warnings'] = warnings
        return result
コード例 #2
0
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_bgp_extcommunities(self):
        url = "data/openconfig-routing-policy:routing-policy/defined-sets/openconfig-bgp-policy:bgp-defined-sets/ext-community-sets"
        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)

        bgp_extcommunities = []
        if "openconfig-bgp-policy:ext-community-sets" in response[0][1]:
            temp = response[0][1].get(
                "openconfig-bgp-policy:ext-community-sets", {})
            if "ext-community-set" in temp:
                bgp_extcommunities = temp["ext-community-set"]

        bgp_extcommunities_configs = []
        for bgp_extcommunity in bgp_extcommunities:
            result = dict()
            name = bgp_extcommunity["ext-community-set-name"]
            member_config = bgp_extcommunity['config']
            match = member_config['match-set-options']
            permit_str = member_config.get('openconfig-bgp-policy-ext:action',
                                           None)
            members = member_config.get("ext-community-member", [])
            result['name'] = name
            result['match'] = match.lower()

            if permit_str and permit_str == 'PERMIT':
                result['permit'] = True
            else:
                result['permit'] = False

            result['members'] = dict()
            rt = list()
            soo = list()
            regex = list()
            for member in members:
                if member.startswith('route-target'):
                    rt.append(':'.join(member.split(':')[1:]))
                elif member.startswith('route-origin'):
                    soo.append(':'.join(member.split(':')[1:]))
                elif member.startswith('REGEX'):
                    regex.append(':'.join(member.split(':')[1:]))

            result['type'] = 'standard'
            if regex and len(regex) > 0:
                result['type'] = 'expanded'
                result['members']['regex'] = regex
            if rt and len(rt) > 0:
                result['members']['route_target'] = rt
            if soo and len(soo) > 0:
                result['members']['route_origin'] = soo

            bgp_extcommunities_configs.append(result)
        # with open('/root/ansible_log.log', 'a+') as fp:
        #     fp.write('facts bgp_extcommunities: ' + str(bgp_extcommunities_configs) + '\n')
        return bgp_extcommunities_configs
コード例 #4
0
    def get_bgp_communities(self):
        url = "data/openconfig-routing-policy:routing-policy/defined-sets/openconfig-bgp-policy:bgp-defined-sets/community-sets"
        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)

        bgp_communities = []
        if "openconfig-bgp-policy:community-sets" in response[0][1]:
            temp = response[0][1].get("openconfig-bgp-policy:community-sets",
                                      {})
            if "community-set" in temp:
                bgp_communities = temp["community-set"]

        bgp_communities_configs = []
        for bgp_community in bgp_communities:
            result = dict()
            name = bgp_community["community-set-name"]
            member_config = bgp_community['config']
            match = member_config['match-set-options']
            permit_str = member_config.get('openconfig-bgp-policy-ext:action',
                                           None)
            members = member_config.get("community-member", [])
            result['name'] = name
            result['match'] = match
            if permit_str and permit_str == 'PERMIT':
                result['permit'] = True
            else:
                result['permit'] = False
            if members:
                result['type'] = 'expanded' if 'REGEX' in members[
                    0] else 'standard'
            else:
                result['type'] = ''
            if result['type'] == 'expanded':
                members = [':'.join(i.split(':')[1:]) for i in members]
            result[
                'local_as'] = True if "NO_EXPORT_SUBCONFED" in members else False
            result[
                'no_advertise'] = True if "NO_ADVERTISE" in members else False
            result['no_export'] = True if "NO_EXPORT" in members else False
            result['no_peer'] = True if "NOPEER" in members else False
            result['members'] = {'regex': members}
            bgp_communities_configs.append(result)
        # with open('/root/ansible_log.log', 'a+') as fp:
        #     fp.write('bgp_communities: ' + str(bgp_communities_configs) + '\n')
        return bgp_communities_configs
コード例 #5
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']
コード例 #6
0
 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 []
コード例 #7
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
コード例 #8
0
def main():

    backup_spec = dict(
        filename=dict(),
        dir_path=dict(type='path')
    )

    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),
        match=dict(default='line',
                   choices=['line', 'strict', 'exact', 'none']),
        replace=dict(default='line', choices=['line', 'block']),

        update=dict(choices=['merge', 'check'], default='merge'),
        config=dict(),
        backup=dict(type='bool', default=False),
        backup_options=dict(type='dict', options=backup_spec)

    )

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

    module = AnsibleModule(argument_spec=argument_spec,
                           mutually_exclusive=mutually_exclusive,
                           supports_check_mode=True)
    parents = module.params['parents'] or list()
    match = module.params['match']
    replace = module.params['replace']

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

    result = dict(changed=False, saved=False, warnings=warnings)
    if module.params['backup']:
        if not module.check_mode:
            result['__backup__'] = get_config(module)

    commands = list()
    candidate = get_candidate(module)
    if any((module.params['lines'], module.params['src'])):
        if match != 'none':
            config = get_running_config(module)
            if parents:
                contents = get_sublevel_config(config, module)
                config = NetworkConfig(contents=contents, indent=1)
            else:
                config = NetworkConfig(contents=config, indent=1)
            configobjs = candidate.difference(config, match=match, replace=replace)
        else:

            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 and module.params['update'] == 'merge':
                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)
コード例 #9
0
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)