def create_pc_interface_policy_group(parent_mo, group_name, **args):
    """Create a PC Interface Policy Group"""
    args = args['optional_args'] if 'optional_args' in args.keys() else args

    # Create mo
    infra_accbndlgrp = AccBndlGrp(parent_mo, group_name)

    if is_valid_key(args, 'link_level'):
        infra_rshifpol = RsHIfPol(infra_accbndlgrp, tnFabricHIfPolName=args['link_level'])
    if is_valid_key(args, 'cdp'):
        infra_rscdpifpol = RsCdpIfPol(infra_accbndlgrp, tnCdpIfPolName=args['cdp'])
    if is_valid_key(args, 'lldp'):
        infra_rslldpifpol = RsLldpIfPol(infra_accbndlgrp, tnLldpIfPolName=args['lldp'])
    if is_valid_key(args, 'stp_interface'):
        infra_rsstpifpol = RsStpIfPol(infra_accbndlgrp, tnStpIfPolName=args['stp_interface'])
    if is_valid_key(args, 'lacp'):
        infra_rsmonifinfrapol = RsLacpPol(infra_accbndlgrp, tnLacpLagPolName=args['lacp'])
    if is_valid_key(args, 'monitoring'):
        infra_rsmonifinfrapol = RsMonIfInfraPol(infra_accbndlgrp, tnMonInfraPolName=args['monitoring'])
    if is_valid_key(args, 'entity_profile'):
        infra_rsattentp = RsAttEntP(infra_accbndlgrp, tDn='uni/infra/attentp-'+args['entity_profile'])
        def add_connectivity_filter(index, filter):
            infra_connnodes = ConnNodeS(infra_rsattentp, 'selector'+str(filter['switch_id']))
            infra_hconnports = HConnPortS(infra_rsattentp, 'selector'+str(filter['switch_id'])+'LeafPorts', 'range')
            infra_connnodeblk = ConnNodeBlk(infra_connnodes, 'block'+str(index), from_=str(filter['switch_id']), to_=str(filter['switch_id']))
            infra_rsconnports = RsConnPortS(infra_connnodes, 'uni/infra/funcprof/accbundle-'+group_name+'/rsattEntP/hports-selector'+str(filter['switch_id'])+'LeafPorts-typ-range')
            id = 0
            for interface in filter['interfaces']:
                id += 1
                card, fromPort, toPort = input_ports(interface)
                infra_connportblk = ConnPortBlk(infra_hconnports, 'block'+str(id), fromPort=fromPort, toPort=toPort)

        if is_valid_key(args, 'connectivity_filters'):
            idx = 0
            for connectivity_filter in args['connectivity_filters']:
                idx += 1
                add_connectivity_filter(idx, connectivity_filter)

    if is_valid_key(args, 'vsource_groups'):
        for vsource_group in args['vsource_groups']:
            infra_rsspanvsrcggrp = RsSpanVSrcGrp(infra_accbndlgrp, vsource_group)

    if is_valid_key(args, 'vdestination_groups'):
        for vdestination_group in args['vdestination_groups']:
            infra_rsspanvdestgrp = RsSpanVDestGrp(infra_accbndlgrp, vdestination_group)

    if is_valid_key(args, 'override_policy_groups'):
        for override_policy_group in args['override_policy_groups']:
            infra_accbndlsubgrp = AccBndlSubgrp(infra_accbndlgrp, override_policy_group['name'])
            if is_valid_key(override_policy_group, 'lacp_member'):
                infra_rslacpifpol = RsLacpIfPol(infra_accbndlsubgrp, tnLacpIfPolName=override_policy_group['lacp_member'])

    return infra_accbndlgrp
Example #2
0
def if_policyG(host, user, password):
    print('[BEG] Interface Policy Group Creation')
    moDir = apic_login(host, user, password)

    polUni = Uni('')
    infraInfra = Infra(polUni)
    infraFuncP = FuncP(infraInfra)

    ifPG_Name = 'ASA-Port-Policy-VPC-Cobra'
    lldp_pol = 'LLDP-Enabled-Cobra'
    cdp_pol = 'CDP-Enabled-Cobra'
    mcp_pol = 'MCP-Enabled-Cobra'
    if_pol = '1GE-SFP-Cobra'
    lag_pol = 'LACP-Active-Cobra'

    print('--- Creating Policy Group Name: ' + ifPG_Name)
    infraAccBndlGrp = AccBndlGrp(infraFuncP, name=ifPG_Name, lagT=u'node')

    print('	Applying LLDP Policy: ' + lldp_pol)
    infraRsLldpIfPol = RsLldpIfPol(infraAccBndlGrp, tnLldpIfPolName=lldp_pol)

    print('	Applying CDP Policy: ' + cdp_pol)
    infraRsCdpIfPol = RsCdpIfPol(infraAccBndlGrp, tnCdpIfPolName=cdp_pol)

    print('	Applying MCP Policy: ' + mcp_pol)
    infraRsMcpIfPol = RsMcpIfPol(infraAccBndlGrp, tnMcpIfPolName=mcp_pol)

    print('	Applying Link Policy: ' + if_pol)
    infraRsHIfPol = RsHIfPol(infraAccBndlGrp, tnFabricHIfPolName=if_pol)

    print('	Applying LAG Policy: ' + lag_pol)
    infraRsLacpPol = RsLacpPol(infraAccBndlGrp,
                               tnLacpLagPolName=u'LACP-Active-Cobra')

    cfg_commit(moDir, infraFuncP)
    print('[END] Interface Policy Group Creation \n')
    return ifPG_Name
def create_access_port_port_policy_group(infra_funcprof, group_name, **args):
    """Create an Access Port Policy Group. The interface policy group. This enables you to specify the interface policies you want to use. """
    args = args['optional_args'] if 'optional_args' in args.keys() else args

    infra_accportgrp = AccPortGrp(infra_funcprof, group_name)
    if is_valid_key(args, 'link_level'):
        infra_rshifpol = RsHIfPol(infra_accportgrp,
                                  tnFabricHIfPolName=args['link_level'])
    if is_valid_key(args, 'cdp'):
        infra_rscdpifpol = RsCdpIfPol(infra_accportgrp,
                                      tnCdpIfPolName=args['cdp'])
    if is_valid_key(args, 'lldp'):
        infra_rslldpifpol = RsLldpIfPol(infra_accportgrp,
                                        tnLldpIfPolName=args['lldp'])
    if is_valid_key(args, 'stp_interface'):
        infra_rsstpifpol = RsStpIfPol(infra_accportgrp,
                                      tnStpIfPolName=args['stp_interface'])
    if is_valid_key(args, 'monitoring'):
        infra_rsmonifinfrapol = RsMonIfInfraPol(
            infra_accportgrp, tnMonInfraPolName=args['monitoring'])

    if is_valid_key(args, 'entity_profile'):
        infra_rsattentp = RsAttEntP(infra_accportgrp,
                                    tDn='uni/infra/attentp-' +
                                    args['entity_profile'])

        def add_connectivity_filter(index, filter):
            infra_connnodes = ConnNodeS(infra_rsattentp,
                                        'selector' + str(filter['switch_id']))
            infra_hconnports = HConnPortS(
                infra_rsattentp,
                'selector' + str(filter['switch_id']) + 'LeafPorts', 'range')
            infra_connnodeblk = ConnNodeBlk(infra_connnodes,
                                            'block' + str(index),
                                            from_=str(filter['switch_id']),
                                            to_=str(filter['switch_id']))
            infra_rsconnports = RsConnPortS(
                infra_connnodes, 'uni/infra/funcprof/accportgrp-' +
                group_name + '/rsattEntP/hports-selector' +
                str(filter['switch_id']) + 'LeafPorts-typ-range')
            id = 0
            for interface in filter['interfaces']:
                id += 1
                card, fromPort, toPort = input_ports(interface)
                infra_connportblk = ConnPortBlk(infra_hconnports,
                                                'block' + str(id),
                                                fromCard=card,
                                                toCard=card,
                                                fromPort=fromPort,
                                                toPort=toPort)

        # mode 2 and 3
        if is_valid_key(args, 'connectivity_filters'):
            index = 0
            for filter in args['connectivity_filters']:
                index += 1
                add_connectivity_filter(index, filter)

        # mode 1
        elif is_valid_key(args, 'switch_id') and is_valid_key(
                args, 'interfaces'):
            add_connectivity_filter(1, {
                'switch_id': args['switch_id'],
                'interfaces': [args['interfaces']]
            })
def main():

    module = AnsibleModule(
        argument_spec=dict(
            host=dict(required=True),
            username=dict(type='str', default=''),
            password=dict(type='str', default=''),
            protocol=dict(choices=['http', 'https'], default='https'),
            state=dict(choices=['present', 'absent'], default='present'),
            group_name=dict(type='str',required=True),
            group_type=dict(choices=['individual', 'pc', 'vpc'], default='individual'),
            group_linklevel=dict(type='str', default=''),
            group_cdp=dict(type='str', default=''),
            group_lldp=dict(type='str', default=''),
            group_stp=dict(type='str', default=''),
            group_pc=dict(type='str', default=''),
            group_aep=dict(type='str', default=''),
            group_overwrite=dict(type='bool', default=False),
            group_monitoring=dict(type='str', default='default')
        ),
        supports_check_mode=True
    )
    if not HAS_COBRA:
        module.fail_json(msg='Ensure you have the ACI Cobra SDK installed',
                         error=str(ie))
    
    # local variables from module parameters
    username = module.params['username']
    password = module.params['password']
    host = module.params['host']
    
    state = module.params['state'].lower()

    group_name = module.params['group_name']
    group_type = module.params['group_type'].lower()
    group_linklevel = module.params['group_linklevel']
    group_cdp = module.params['group_cdp']
    group_lldp = module.params['group_lldp']
    group_stp = module.params['group_stp']
    group_pc = module.params['group_pc']
    group_aep = module.params['group_aep']
    group_monitoring = module.params['group_monitoring']
    group_overwrite = module.params['group_overwrite']
    
    # log into the fabric
    moDir = apic_login(host, username, password)
    groupMo = moDir.lookupByDn('uni/infra/funcprof/')
    
    infra_acc = None
    
    if state == 'present':
        # create port group based on type
        if group_type != 'individual':
            moClass = AccBndlGrp
            if not check_if_mo_exist(moDir,'uni/infra/funcprof/accbundle-', group_name, moClass, 'Interface Policy Group', return_false=True, set_mo=False) or group_overwrite:
                if group_type == 'vpc':
                    infra_acc = AccBndlGrp(groupMo, group_name, lagT='node')
                    infra_rsmonifinfrapol = RsLacpPol(infra_acc, tnLacpLagPolName=group_pc)
                else:
                    infra_acc = AccBndlGrp(groupMo, group_name)
                    infra_rsmonifinfrapol = RsLacpPol(infra_acc, tnLacpLagPolName=group_pc)
            else:
                module.fail_json(changed=True, msg='Interface Policy Group ' + group_name + ' exists.  Look under Fabric -> Access Policies -> Interface Policies -> Policy Groups')
        else:
            moClass = AccPortGrp
            if not check_if_mo_exist(moDir,'uni/infra/funcprof/accportgrp-', group_name, moClass, 'Interface Policy Group', return_false=True, set_mo=False) or group_overwrite:
                infra_acc = AccPortGrp(groupMo, group_name)
            else:
                module.fail_json(changed=True, msg='Interface Policy Group ' + group_name + ' exists.  Look under Fabric -> Access Policies -> Interface Policies -> Policy Groups')
        
        # Verify and assign the Link level policy
        if group_linklevel:
            if check_if_mo_exist(moDir,'uni/infra/hintfpol-', group_linklevel, HIfPol, 'Link Level Policy', return_false=True, set_mo=False):
                infra_rshifpol = RsHIfPol(infra_acc, tnFabricHIfPolName=group_linklevel)
            else:
                module.fail_json(msg=' Link Level Policy ' + group_linklevel + ' does not exist. Check Fabric -> Access Policies -> Interface Policies -> Policies -> Link Level')
        # verify and assign cdp policy
        if group_cdp:
            if check_if_mo_exist(moDir,'uni/infra/cdpIfP-', group_cdp, cdpIfPol, 'CDP Policy', return_false=True, set_mo=False):
                infra_rscdpifpol = RsCdpIfPol(infra_acc, tnCdpIfPolName=group_cdp)
            else:
                module.fail_json(msg=' CDP Policy ' + group_cdp + ' does not exist. Check Fabric -> Access Policies -> Interface Policies -> Policies -> CDP Interface')
        # verify and assign lldp policy
        if group_lldp:
            if check_if_mo_exist(moDir,'uni/infra/lldpIfP-', group_lldp, lldpIfPol, 'LLDP Policy', return_false=True, set_mo=False):
                infra_rslldpifpol = RsLldpIfPol(infra_acc, tnLldpIfPolName=group_lldp)
            else:
                module.fail_json(msg=' LLDP Policy ' + group_lldp + ' does not exist. Check Fabric -> Access Policies -> Interface Policies -> Policies -> LLDP Interface')
        # verify and assign stp policy
        if group_stp:
            if check_if_mo_exist(moDir,'uni/infra/ifPol-', group_stp, stpIfPol, 'BPDU Policy', return_false=True, set_mo=False):
                infra_rsstpifpol = RsStpIfPol(infra_acc, tnStpIfPolName=group_stp)
            else:
                module.fail_json(msg=' STP Policy ' + group_lldp + ' does not exist. Check Fabric -> Access Policies -> Interface Policies -> Policies -> Spanning Tree Interface')
        # verify and assign monitoring policy
        if group_monitoring:
            if check_if_mo_exist(moDir,'uni/infra/moninfra-', group_monitoring, InfraPol, 'Monitoring Policy', return_false=True, set_mo=False):
                infra_rsmonifinfrapol = RsMonIfInfraPol(infra_acc, tnMonInfraPolName=group_monitoring)
            else:
                module.fail_json(msg=' Monitoring Policy ' + group_monitoring + ' does not exist. Check Fabric -> Access Policies -> Monitoring Policies')
        # verify and assign AEP
        if group_aep:
            if check_if_mo_exist(moDir,'uni/infra/attentp-', group_aep, AttEntityP, 'Attached Entity Profile', return_false=True, set_mo=False):
                infra_rsattentp = RsAttEntP(infra_acc, tDn='uni/infra/attentp-'+ group_aep)
            else:
                module.fail_json(msg=' Attached Entity Profile ' + group_aep + ' does not exist. Check Fabric -> Access Policies -> Global Policies -> Attachable Access Entity Profiles')
            
    elif state == "absent":
        if group_type == 'individual':
            uri = 'uni/infra/funcprof/accportgrp-' + group_name
            infra_acc = check_if_mo_exist(moDir,'uni/infra/funcprof/accportgrp-', group_name, AccPortGrp, 'Policy Group', return_false=True, set_mo=False)
        else:
            uri = 'uni/infra/funcprof/accbundle-' + group_name
            infra_acc = check_if_mo_exist(moDir,'uni/infra/funcprof/accbundle-', group_name, AccBndlGrp, 'Policy Group', return_false=True, set_mo=False)
        if infra_acc:
            ports = get_ports_in_group(moDir, uri)
            if len(ports) == 0:
                infra_acc.delete()
            else:
                module.fail_json(msg=' group name ' + group_name + ' as ' + group_type + ' has ports configured in it.')
        else:
            module.fail_json(msg=' group name ' + group_name + ' as ' + group_type + ' does not exist.')
    else:       
        module.fail_json(msg='Invalid group status.  Options are "present" or "absent"')
        
    results = {}
    xmldoc = ''
    changed = False
    factsdict = {}
    
    if infra_acc and state == 'present':
        xmldoc = print_query_xml(infra_acc)
        factsdict['configuration'] = xmldoc
        if module.check_mode:
            module.exit_json(changed=True, ansible_facts=factsdict)
        else:
            changed = True
            commit_change(moDir, infra_acc, print_xml=False)
    elif infra_acc and state == 'absent':
        xmldoc = print_query_xml(infra_acc)
        factsdict['configuration'] = xmldoc
        if module.check_mode:
            module.exit_json(changed=True, ansible_facts=factsdict)
        else:
            changed = True
            commit_change(moDir, infra_acc, print_xml=False)

    results['xmldoc'] = xmldoc
    results['state'] = state
    results['changed'] = changed

    module.exit_json(ansible_facts=factsdict,**results)
def create_access_port_port_policy_group(modir, group_name, **args):

    args = args['args_from_CLI'] if 'args_from_CLI' in args.keys() else args
    # Query a parent
    infra_funcprof = modir.lookupByDn('uni/infra/funcprof/')
    infra_accportgrp = AccPortGrp(infra_funcprof, group_name)

    if check_if_key_existed(args, 'link_level'):
        infra_rshifpol = RsHIfPol(infra_accportgrp,
                                  tnFabricHIfPolName=args['link_level'])
    if check_if_key_existed(args, 'cdp'):
        infra_rscdpifpol = RsCdpIfPol(infra_accportgrp,
                                      tnCdpIfPolName=args['cdp'])
    if check_if_key_existed(args, 'lldp'):
        infra_rslldpifpol = RsLldpIfPol(infra_accportgrp,
                                        tnLldpIfPolName=args['lldp'])
    if check_if_key_existed(args, 'stp_interface'):
        infra_rsstpifpol = RsStpIfPol(infra_accportgrp,
                                      tnStpIfPolName=args['stp_interface'])
    if check_if_key_existed(args, 'monitoring'):
        infra_rsmonifinfrapol = RsMonIfInfraPol(
            infra_accportgrp, tnMonInfraPolName=args['monitoring'])

    if check_if_key_existed(args, 'entity_profile'):
        infra_rsattentp = RsAttEntP(infra_accportgrp,
                                    tDn='uni/infra/attentp-' +
                                    args['entity_profile'])

        def add_connectivity_filter(index, filter):
            infra_connnodes = ConnNodeS(infra_rsattentp,
                                        'selector' + str(filter['switch_id']))
            infra_hconnports = HConnPortS(
                infra_rsattentp,
                'selector' + str(filter['switch_id']) + 'LeafPorts', 'range')
            infra_connnodeblk = ConnNodeBlk(infra_connnodes,
                                            'block' + str(index),
                                            from_=str(filter['switch_id']),
                                            to_=str(filter['switch_id']))
            infra_rsconnports = RsConnPortS(
                infra_connnodes, 'uni/infra/funcprof/accportgrp-' +
                group_name + '/rsattEntP/hports-selector' +
                str(filter['switch_id']) + 'LeafPorts-typ-range')
            id = 0
            for interface in filter['interfaces']:
                id += 1
                card, fromPort, toPort = get_numbers(interface)
                infra_connportblk = ConnPortBlk(infra_hconnports,
                                                'block' + str(id),
                                                fromCard=card,
                                                toCard=card,
                                                fromPort=fromPort,
                                                toPort=toPort)

        # mode 2 and 3
        if check_if_key_existed(args, 'connectivity_filters'):
            index = 0
            for filter in args['connectivity_filters']:
                index += 1
                add_connectivity_filter(index, filter)

        # mode 1
        elif check_if_key_existed(args, 'switch_id') and check_if_key_existed(
                args, 'interfaces'):
            add_connectivity_filter(1, {
                'switch_id': args['switch_id'],
                'interfaces': [args['interfaces']]
            })

    print_query_xml(infra_funcprof)
    commit_change(modir, infra_funcprof)