def main():
    argument_spec = mso_argument_spec()
    argument_spec.update(
        schema=dict(type='str', required=True),
        template=dict(type='str', required=True, aliases=['name']),
        site=dict(type='str'),
        state=dict(type='str',
                   default='deploy',
                   choices=['deploy', 'status', 'undeploy']),
    )

    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
        required_if=[
            ['state', 'undeploy', ['site']],
        ],
    )

    schema = module.params['schema']
    template = module.params['template']
    site = module.params['site']
    state = module.params['state']

    mso = MSOModule(module)

    # Get schema
    schema_id = mso.lookup_schema(schema)

    payload = dict(
        schemaId=schema_id,
        templateName=template,
    )

    qs = None
    if state == 'deploy':
        path = 'execute/schema/{0}/template/{1}'.format(schema_id, template)
    elif state == 'status':
        path = 'status/schema/{0}/template/{1}'.format(schema_id, template)
    elif state == 'undeploy':
        path = 'execute/schema/{0}/template/{1}'.format(schema_id, template)
        site_id = mso.lookup_site(site)
        qs = dict(undeploy=site_id)

    if not module.check_mode:
        status = mso.request(path, method='GET', data=payload, qs=qs)

    mso.exit_json(**status)
def main():
    argument_spec = mso_argument_spec()
    argument_spec.update(
        schema=dict(type='str', required=True),
        site=dict(type='str', required=True),
        template=dict(type='str', required=True),
        anp=dict(type='str', required=True),
        epg=dict(type='str', required=True),
        domain_association_type=dict(type='str',
                                     choices=[
                                         'vmmDomain', 'l3ExtDomain',
                                         'l2ExtDomain', 'physicalDomain',
                                         'fibreChannel'
                                     ]),
        domain_profile=dict(type='str'),
        deployment_immediacy=dict(type='str', choices=['immediate', 'lazy']),
        resolution_immediacy=dict(
            type='str', choices=['immediate', 'lazy', 'pre-provision']),
        state=dict(type='str',
                   default='present',
                   choices=['absent', 'present', 'query']),
        micro_seg_vlan_type=dict(type='str'),
        micro_seg_vlan=dict(type='int'),
        port_encap_vlan_type=dict(type='str'),
        port_encap_vlan=dict(type='int'),
        vlan_encap_mode=dict(type='str', choices=['static', 'dynamic']),
        allow_micro_segmentation=dict(type='bool'),
        switch_type=dict(type='str'),
        switching_mode=dict(type='str'),
        enhanced_lagpolicy_name=dict(type='str'),
        enhanced_lagpolicy_dn=dict(type='str'),
    )

    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
        required_if=[
            [
                'state', 'absent',
                [
                    'domain_association_type', 'domain_profile',
                    'deployment_immediacy', 'resolution_immediacy'
                ]
            ],
            [
                'state', 'present',
                [
                    'domain_association_type', 'domain_profile',
                    'deployment_immediacy', 'resolution_immediacy'
                ]
            ],
        ],
    )

    schema = module.params['schema']
    site = module.params['site']
    template = module.params['template']
    anp = module.params['anp']
    epg = module.params['epg']
    domain_association_type = module.params['domain_association_type']
    domain_profile = module.params['domain_profile']
    deployment_immediacy = module.params['deployment_immediacy']
    resolution_immediacy = module.params['resolution_immediacy']
    state = module.params['state']
    micro_seg_vlan_type = module.params['micro_seg_vlan_type']
    micro_seg_vlan = module.params['micro_seg_vlan']
    port_encap_vlan_type = module.params['port_encap_vlan_type']
    port_encap_vlan = module.params['port_encap_vlan']
    vlan_encap_mode = module.params['vlan_encap_mode']
    allow_micro_segmentation = module.params['allow_micro_segmentation']
    switch_type = module.params['switch_type']
    switching_mode = module.params['switching_mode']
    enhanced_lagpolicy_name = module.params['enhanced_lagpolicy_name']
    enhanced_lagpolicy_dn = module.params['enhanced_lagpolicy_dn']

    mso = MSOModule(module)

    # Get schema_id
    schema_obj = mso.get_obj('schemas', displayName=schema)
    if not schema_obj:
        mso.fail_json(
            msg="Provided schema '{0}' does not exist".format(schema))

    schema_path = 'schemas/{id}'.format(**schema_obj)
    schema_id = schema_obj['id']

    # Get site
    site_id = mso.lookup_site(site)

    # Get site_idx
    sites = [(s['siteId'], s['templateName']) for s in schema_obj['sites']]
    if (site_id, template) not in sites:
        mso.fail_json(
            msg=
            "Provided site/template '{0}-{1}' does not exist. Existing sites/templates: {2}"
            .format(site, template, ', '.join(sites)))

    # Schema-access uses indexes
    site_idx = sites.index((site_id, template))
    # Path-based access uses site_id-template
    site_template = '{0}-{1}'.format(site_id, template)

    # Get ANP
    anp_ref = mso.anp_ref(schema_id=schema_id, template=template, anp=anp)
    anps = [a['anpRef'] for a in schema_obj['sites'][site_idx]['anps']]
    if anp_ref not in anps:
        mso.fail_json(
            msg="Provided anp '{0}' does not exist. Existing anps: {1}".format(
                anp, ', '.join(anps)))
    anp_idx = anps.index(anp_ref)

    # Get EPG
    epg_ref = mso.epg_ref(schema_id=schema_id,
                          template=template,
                          anp=anp,
                          epg=epg)
    print(epg_ref)
    epgs = [
        e['epgRef']
        for e in schema_obj['sites'][site_idx]['anps'][anp_idx]['epgs']
    ]
    if epg_ref not in epgs:
        mso.fail_json(
            msg=
            "Provided epg '{0}' does not exist. Existing epgs: {1} epgref {2}".
            format(epg, str(schema_obj['sites'][site_idx]), epg_ref))
    epg_idx = epgs.index(epg_ref)

    if domain_association_type == 'vmmDomain':
        domain_dn = 'uni/vmmp-VMware/dom-{0}'.format(domain_profile)
    elif domain_association_type == 'l3ExtDomain':
        domain_dn = 'uni/l3dom-{0}'.format(domain_profile)
    elif domain_association_type == 'l2ExtDomain':
        domain_dn = 'uni/l2dom-{0}'.format(domain_profile)
    elif domain_association_type == 'physicalDomain':
        domain_dn = 'uni/phys-{0}'.format(domain_profile)
    elif domain_association_type == 'fibreChannel':
        domain_dn = 'uni/fc-{0}'.format(domain_profile)
    else:
        domain_dn = ''

    # Get Domains
    domains = [
        dom['dn'] for dom in schema_obj['sites'][site_idx]['anps'][anp_idx]
        ['epgs'][epg_idx]['domainAssociations']
    ]
    if domain_dn in domains:
        domain_idx = domains.index(domain_dn)
        domain_path = '/sites/{0}/anps/{1}/epgs/{2}/domainAssociations/{3}'.format(
            site_template, anp, epg, domain_idx)
        mso.existing = schema_obj['sites'][site_idx]['anps'][anp_idx]['epgs'][
            epg_idx]['domainAssociations'][domain_idx]

    if state == 'query':
        if domain_association_type is None or domain_profile is None:
            mso.existing = schema_obj['sites'][site_idx]['anps'][anp_idx][
                'epgs'][epg_idx]['domainAssociations']
        elif not mso.existing:
            mso.fail_json(
                msg=
                "Domain association '{domain_association_type}/{domain_profile}' not found"
                .format(domain_association_type=domain_association_type,
                        domain_profile=domain_profile))
        mso.exit_json()

    domains_path = '/sites/{0}/anps/{1}/epgs/{2}/domainAssociations'.format(
        site_template, anp, epg)
    ops = []
    if domain_association_type == 'vmmDomain':
        vmmDomainProperties = {}
        if micro_seg_vlan_type and micro_seg_vlan:
            microSegVlan = dict(vlanType=micro_seg_vlan_type,
                                vlan=micro_seg_vlan)
            vmmDomainProperties['microSegVlan'] = microSegVlan
        elif not micro_seg_vlan_type and micro_seg_vlan:
            mso.fail_json(
                msg=
                "micro_seg_vlan_type is required when micro_seg_vlan is provied."
            )
        elif micro_seg_vlan_type and not micro_seg_vlan:
            mso.fail_json(
                msg=
                "micro_seg_vlan is required when micro_seg_vlan_type is provided."
            )

        if micro_seg_vlan_type and micro_seg_vlan:
            portEncapVlan = dict(vlanType=port_encap_vlan_type,
                                 vlan=port_encap_vlan)
            vmmDomainProperties['portEncapVlan'] = portEncapVlan
        elif not port_encap_vlan_type and port_encap_vlan:
            mso.fail_json(
                msg=
                "port_encap_vlan_type is required when port_encap_vlan is provied."
            )
        elif port_encap_vlan_type and not port_encap_vlan:
            mso.fail_json(
                msg=
                "port_encap_vlan is required when port_encap_vlan_type is provided."
            )

        if vlan_encap_mode:
            vmmDomainProperties['vlanEncapMode'] = vlan_encap_mode

        if allow_micro_segmentation:
            vmmDomainProperties[
                'allowMicroSegmentation'] = allow_micro_segmentation
        if switch_type:
            vmmDomainProperties['switchType'] = switch_type
        if switching_mode:
            vmmDomainProperties['switchingMode'] = switching_mode

        if enhanced_lagpolicy_name and enhanced_lagpolicy_dn:
            enhancedLagPol = dict(name=enhanced_lagpolicy_name,
                                  dn=enhanced_lagpolicy_dn)
            epgLagPol = dict(enhancedLagPol=enhancedLagPol)
            vmmDomainProperties['epgLagPol'] = epgLagPol
        elif not enhanced_lagpolicy_name and enhanced_lagpolicy_dn:
            mso.fail_json(
                msg=
                "enhanced_lagpolicy_name is required when enhanced_lagpolicy_dn is provied."
            )
        elif enhanced_lagpolicy_name and not enhanced_lagpolicy_dn:
            mso.fail_json(
                msg=
                "enhanced_lagpolicy_dn is required when enhanced_lagpolicy_name is provied."
            )

        payload = dict(
            dn=domain_dn,
            domainType=domain_association_type,
            deploymentImmediacy=deployment_immediacy,
            resolutionImmediacy=resolution_immediacy,
        )

        if vmmDomainProperties:
            payload['vmmDomainProperties'] = vmmDomainProperties
    else:
        payload = dict(
            dn=domain_dn,
            domainType=domain_association_type,
            deploymentImmediacy=deployment_immediacy,
            resolutionImmediacy=resolution_immediacy,
        )

    mso.previous = mso.existing
    if state == 'absent':
        if mso.existing:
            mso.sent = mso.existing = {}
            ops.append(dict(op='remove', path=domains_path))
    elif state == 'present':
        mso.sanitize(payload, collate=True)

        if mso.existing:
            ops.append(dict(op='replace', path=domain_path, value=mso.sent))
        else:
            ops.append(dict(op='add', path=domains_path + '/-',
                            value=mso.sent))

        mso.existing = mso.proposed

    if not module.check_mode:
        mso.request(schema_path, method='PATCH', data=ops)

    mso.exit_json()
Exemplo n.º 3
0
def main():
    argument_spec = mso_argument_spec()
    argument_spec.update(
        schema=dict(type='str', required=True),
        site=dict(type='str', required=True),
        template=dict(type='str', required=True),
        anp=dict(type='str', required=True),
        epg=dict(type='str', aliases=['name']),  # This parameter is not required for querying all objects
        state=dict(type='str', default='present', choices=['absent', 'present', 'query']),
    )

    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
        required_if=[
            ['state', 'absent', ['epg']],
            ['state', 'present', ['epg']],
        ],
    )

    schema = module.params.get('schema')
    site = module.params.get('site')
    template = module.params.get('template')
    anp = module.params.get('anp')
    epg = module.params.get('epg')
    state = module.params.get('state')

    mso = MSOModule(module)

    # Get schema_id
    schema_obj = mso.get_obj('schemas', displayName=schema)
    if not schema_obj:
        mso.fail_json(msg="Provided schema '{0}' does not exist".format(schema))

    schema_path = 'schemas/{id}'.format(**schema_obj)
    schema_id = schema_obj.get('id')

    # Get site
    site_id = mso.lookup_site(site)
    sites = [(s.get('siteId'), s.get('templateName')) for s in schema_obj.get('sites')]
    if (site_id, template) not in sites:
        mso.fail_json(msg="Provided site/template '{0}-{1}' does not exist. Existing sites/templates: {2}".format(site, template, ', '.join(sites)))

    # Schema-access uses indexes
    site_idx = sites.index((site_id, template))
    # Path-based access uses site_id-template
    site_template = '{0}-{1}'.format(site_id, template)

    # Get ANP
    anp_ref = mso.anp_ref(schema_id=schema_id, template=template, anp=anp)
    anps = [a.get('anpRef') for a in schema_obj.get('sites')[site_idx]['anps']]
    if anp_ref not in anps:
        mso.fail_json(msg="Provided anp '{0}' does not exist. Existing anps: {1}".format(anp, ', '.join(anps)))
    anp_idx = anps.index(anp_ref)

    # Get EPG
    epg_ref = mso.epg_ref(schema_id=schema_id, template=template, anp=anp, epg=epg)
    epgs = [e.get('epgRef') for e in schema_obj.get('sites')[site_idx]['anps'][anp_idx]['epgs']]
    if epg is not None and epg_ref in epgs:
        epg_idx = epgs.index(epg_ref)
        epg_path = '/sites/{0}/anps/{1}/epgs/{2}'.format(site_template, anp, epg)
        mso.existing = schema_obj.get('sites')[site_idx]['anps'][anp_idx]['epgs'][epg_idx]

    if state == 'query':
        if epg is None:
            mso.existing = schema_obj.get('sites')[site_idx]['anps'][anp_idx]['epgs']
        elif not mso.existing:
            mso.fail_json(msg="EPG '{epg}' not found".format(epg=epg))
        mso.exit_json()

    epgs_path = '/sites/{0}/anps/{1}/epgs'.format(site_template, anp)
    ops = []

    mso.previous = mso.existing
    if state == 'absent':
        if mso.existing:
            mso.sent = mso.existing = {}
            ops.append(dict(op='remove', path=epg_path))

    elif state == 'present':

        payload = dict(
            epgRef=dict(
                schemaId=schema_id,
                templateName=template,
                anpName=anp,
                epgName=epg,
            ),
        )

        mso.sanitize(payload, collate=True)

        if not mso.existing:
            ops.append(dict(op='add', path=epgs_path + '/-', value=mso.sent))

        mso.existing = mso.proposed

    if not module.check_mode:
        mso.request(schema_path, method='PATCH', data=ops)

    mso.exit_json()
Exemplo n.º 4
0
def main():
    argument_spec = mso_argument_spec()
    argument_spec.update(
        schema=dict(type='str', required=True),
        site=dict(type='str', required=True),
        template=dict(type='str', required=True),
        anp=dict(type='str', required=True),
        epg=dict(type='str', required=True),
        leaf=dict(type='str', aliases=['name']),
        vlan=dict(type='int'),
        state=dict(type='str',
                   default='present',
                   choices=['absent', 'present', 'query']),
    )

    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
        required_if=[
            ['state', 'absent', ['leaf', 'vlan']],
            ['state', 'present', ['leaf', 'vlan']],
        ],
    )

    schema = module.params['schema']
    site = module.params['site']
    template = module.params['template']
    anp = module.params['anp']
    epg = module.params['epg']
    leaf = module.params['leaf']
    vlan = module.params['vlan']
    state = module.params['state']

    mso = MSOModule(module)

    # Get schema_id
    schema_obj = mso.get_obj('schemas', displayName=schema)
    if not schema_obj:
        mso.fail_json(
            msg="Provided schema '{0}' does not exist".format(schema))

    schema_path = 'schemas/{id}'.format(**schema_obj)
    schema_id = schema_obj['id']

    # Get site
    site_id = mso.lookup_site(site)

    # Get site_idx
    sites = [(s['siteId'], s['templateName']) for s in schema_obj['sites']]
    if (site_id, template) not in sites:
        mso.fail_json(
            msg=
            "Provided site/template '{0}-{1}' does not exist. Existing sites/templates: {2}"
            .format(site, template, ', '.join(sites)))

    # Schema-access uses indexes
    site_idx = sites.index((site_id, template))
    # Path-based access uses site_id-template
    site_template = '{0}-{1}'.format(site_id, template)

    # Get ANP
    anp_ref = mso.anp_ref(schema_id=schema_id, template=template, anp=anp)
    anps = [a['anpRef'] for a in schema_obj['sites'][site_idx]['anps']]
    if anp_ref not in anps:
        mso.fail_json(
            msg="Provided anp '{0}' does not exist. Existing anps: {1}".format(
                anp, ', '.join(anps)))
    anp_idx = anps.index(anp_ref)

    # Get EPG
    epg_ref = mso.epg_ref(schema_id=schema_id,
                          template=template,
                          anp=anp,
                          epg=epg)
    epgs = [
        e['epgRef']
        for e in schema_obj['sites'][site_idx]['anps'][anp_idx]['epgs']
    ]
    if epg_ref not in epgs:
        mso.fail_json(
            msg="Provided epg '{0}' does not exist. Existing epgs: {1}".format(
                epg, ', '.join(epgs)))
    epg_idx = epgs.index(epg_ref)

    # Get Leaf
    leafs = [(l['path'], l['portEncapVlan']) for l in schema_obj['sites']
             [site_idx]['anps'][anp_idx]['epgs'][epg_idx]['staticLeafs']]
    if (leaf, vlan) in leafs:
        leaf_idx = leafs.index((leaf, vlan))
        # FIXME: Changes based on index are DANGEROUS
        leaf_path = '/sites/{0}/anps/{1}/epgs/{2}/staticLeafs/{3}'.format(
            site_template, anp, epg, leaf_idx)
        mso.existing = schema_obj['sites'][site_idx]['anps'][anp_idx]['epgs'][
            epg_idx]['staticLeafs'][leaf_idx]

    if state == 'query':
        if leaf is None or vlan is None:
            mso.existing = schema_obj['sites'][site_idx]['anps'][anp_idx][
                'epgs'][epg_idx]['staticLeafs']
        elif not mso.existing:
            mso.fail_json(msg="Static leaf '{leaf}/{vlan}' not found".format(
                leaf=leaf, vlan=vlan))
        mso.exit_json()

    leafs_path = '/sites/{0}/anps/{1}/epgs/{2}/staticLeafs'.format(
        site_template, anp_idx, epg_idx)
    ops = []

    mso.previous = mso.existing
    if state == 'absent':
        if mso.existing:
            mso.sent = mso.existing = {}
            ops.append(dict(op='remove', path=leaf_path))

    elif state == 'present':
        payload = dict(
            path=leaf,
            portEncapVlan=vlan,
        )

        mso.sanitize(payload, collate=True)

        if mso.existing:
            ops.append(dict(op='replace', path=leaf_path, value=mso.sent))
        else:
            ops.append(dict(op='add', path=leafs_path + '/-', value=mso.sent))

        mso.existing = mso.proposed

    if not module.check_mode:
        mso.request(schema_path, method='PATCH', data=ops)

    mso.exit_json()
Exemplo n.º 5
0
def main():
    argument_spec = mso_argument_spec()
    argument_spec.update(
        schema=dict(type='str', required=True),
        site=dict(type='str', required=True),
        template=dict(type='str', required=True),
        vrf=dict(type='str', aliases=[
            'name'
        ]),  # This parameter is not required for querying all objects
        state=dict(type='str',
                   default='present',
                   choices=['absent', 'present', 'query']),
    )

    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
        required_if=[
            ['state', 'absent', ['vrf']],
            ['state', 'present', ['vrf']],
        ],
    )

    schema = module.params['schema']
    site = module.params['site']
    template = module.params['template']
    vrf = module.params['vrf']
    state = module.params['state']

    mso = MSOModule(module)

    # Get schema_id
    schema_obj = mso.get_obj('schemas', displayName=schema)
    if not schema_obj:
        mso.fail_json(
            msg="Provided schema '{0}' does not exist".format(schema))

    schema_path = 'schemas/{id}'.format(**schema_obj)
    schema_id = schema_obj['id']

    # Get site
    site_id = mso.lookup_site(site)

    # Get site_idx
    sites = [(s['siteId'], s['templateName']) for s in schema_obj['sites']]
    if (site_id, template) not in sites:
        mso.fail_json(
            msg=
            "Provided site/template '{0}-{1}' does not exist. Existing sites/templates: {2}"
            .format(site, template, ', '.join(sites)))

    # Schema-access uses indexes
    site_idx = sites.index((site_id, template))
    # Path-based access uses site_id-template
    site_template = '{0}-{1}'.format(site_id, template)

    # Get VRF
    vrf_ref = mso.vrf_ref(schema_id=schema_id, template=template, vrf=vrf)
    vrfs = [v['vrfRef'] for v in schema_obj['sites'][site_idx]['vrfs']]
    if vrf is not None and vrf_ref in vrfs:
        vrf_idx = vrfs.index(vrf_ref)
        vrf_path = '/sites/{0}/vrfs/{1}'.format(site_template, vrf)
        mso.existing = schema_obj['sites'][site_idx]['vrfs'][vrf_idx]

    if state == 'query':
        if vrf is None:
            mso.existing = schema_obj['sites'][site_idx]['vrfs']
        elif not mso.existing:
            mso.fail_json(msg="VRF '{vrf}' not found".format(vrf=vrf))
        mso.exit_json()

    vrfs_path = '/sites/{0}/vrfs'.format(site_template)
    ops = []

    mso.previous = mso.existing
    if state == 'absent':
        if mso.existing:
            mso.sent = mso.existing = {}
            ops.append(dict(op='remove', path=vrf_path))

    elif state == 'present':
        payload = dict(vrfRef=dict(
            schemaId=schema_id,
            templateName=template,
            vrfName=vrf,
        ), )

        mso.sanitize(payload, collate=True)

        if mso.existing:
            ops.append(dict(op='replace', path=vrf_path, value=mso.sent))
        else:
            ops.append(dict(op='add', path=vrfs_path + '/-', value=mso.sent))

        mso.existing = mso.proposed

    if not module.check_mode:
        mso.request(schema_path, method='PATCH', data=ops)

    mso.exit_json()
Exemplo n.º 6
0
def main():
    argument_spec = mso_argument_spec()
    argument_spec.update(
        schema=dict(type='str', required=True),
        site=dict(type='str', required=True),
        template=dict(type='str', required=True),
        bd=dict(type='str', aliases=['name']),  # This parameter is not required for querying all objects
        state=dict(type='str', default='present', choices=['absent', 'present', 'query']),
    )
    argument_spec.update(mso_subnet_spec())

    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
        required_if=[
            ['state', 'absent', ['bd']],
            ['state', 'present', ['bd']],
        ],
    )

    schema = module.params['schema']
    site = module.params['site']
    template = module.params['template']
    bd = module.params['bd']
    subnet = module.params['subnet']
    description = module.params['description']
    scope = module.params['scope']
    shared = module.params['shared']
    no_default_gateway = module.params['no_default_gateway']
    state = module.params['state']

    mso = MSOModule(module)

    # Get schema_id
    schema_obj = mso.get_obj('schemas', displayName=schema)
    if not schema_obj:
        mso.fail_json(msg="Provided schema '{0}' does not exist".format(schema))

    schema_path = 'schemas/{id}'.format(**schema_obj)
    schema_id = schema_obj['id']

    # Get site
    site_id = mso.lookup_site(site)

    # Get site_idx
    sites = [(s['siteId'], s['templateName']) for s in schema_obj['sites']]
    if (site_id, template) not in sites:
        mso.fail_json(msg="Provided site/template '{0}-{1}' does not exist. Existing sites/templates: {2}".format(site, template, ', '.join(sites)))

    # Schema-access uses indexes
    site_idx = sites.index((site_id, template))
    # Path-based access uses site_id-template
    site_template = '{0}-{1}'.format(site_id, template)

    # Get BD
    bd_ref = mso.bd_ref(schema_id=schema_id, template=template, bd=bd)
    bds = [v['bdRef'] for v in schema_obj['sites'][site_idx]['bds']]
    if bd_ref not in bds:
        mso.fail_json(msg="Provided BD '{0}' does not exist. Existing BDs: {1}".format(bd, ', '.join(bds)))
    bd_idx = bds.index(bd_ref)

    # Get Subnet
    subnets = [s['ip'] for s in schema_obj['sites'][site_idx]['bds'][bd_idx]['subnets']]
    if subnet in subnets:
        subnet_idx = subnets.index(subnet)
        # FIXME: Changes based on index are DANGEROUS
        subnet_path = '/sites/{0}/bds/{1}/subnets/{2}'.format(site_template, bd, subnet_idx)
        mso.existing = schema_obj['sites'][site_idx]['bds'][bd_idx]['subnets'][subnet_idx]

    if state == 'query':
        if subnet is None:
            mso.existing = schema_obj['sites'][site_idx]['bds'][bd_idx]['subnets']
        elif not mso.existing:
            mso.fail_json(msg="Subnet IP '{subnet}' not found".format(subnet=subnet))
        mso.exit_json()

    subnets_path = '/sites/{0}/bds/{1}/subnets'.format(site_template, bd)
    ops = []

    mso.previous = mso.existing
    if state == 'absent':
        if mso.existing:
            mso.sent = mso.existing = {}
            ops.append(dict(op='remove', path=subnet_path))

    elif state == 'present':
        if not mso.existing:
            if description is None:
                description = subnet
            if scope is None:
                scope = 'private'
            if shared is None:
                shared = False
            if no_default_gateway is None:
                no_default_gateway = False

        payload = dict(
            ip=subnet,
            description=description,
            scope=scope,
            shared=shared,
            noDefaultGateway=no_default_gateway,
        )

        mso.sanitize(payload, collate=True)

        if mso.existing:
            ops.append(dict(op='replace', path=subnet_path, value=mso.sent))
        else:
            ops.append(dict(op='add', path=subnets_path + '/-', value=mso.sent))

        mso.existing = mso.proposed

    if not module.check_mode:
        mso.request(schema_path, method='PATCH', data=ops)

    mso.exit_json()
Exemplo n.º 7
0
def main():
    argument_spec = mso_argument_spec()
    argument_spec.update(
        schema=dict(type='str', required=True),
        site=dict(type='str', aliases=['name']),
        template=dict(type='str'),
        state=dict(type='str',
                   default='present',
                   choices=['absent', 'present', 'query']),
    )

    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
        required_if=[
            ['state', 'absent', ['site', 'template']],
            ['state', 'present', ['site', 'template']],
        ],
    )

    schema = module.params.get('schema')
    site = module.params.get('site')
    template = module.params.get('template')
    state = module.params.get('state')

    mso = MSOModule(module)

    # Get schema
    schema_obj = mso.get_obj('schemas', displayName=schema)
    if not schema_obj:
        mso.fail_json(
            msg="Provided schema '{0}' does not exist".format(schema))

    # Schema exists
    schema_path = 'schemas/{id}'.format(**schema_obj)

    # Get site
    site_id = mso.lookup_site(site)

    mso.existing = {}
    if 'sites' in schema_obj:
        sites = [(s.get('siteId'), s.get('templateName'))
                 for s in schema_obj.get('sites')]
        if template:
            if (site_id, template) in sites:
                site_idx = sites.index((site_id, template))
                mso.existing = schema_obj.get('sites')[site_idx]
        else:
            mso.existing = schema_obj.get('sites')

    if state == 'query':
        if not mso.existing:
            if template:
                mso.fail_json(msg="Template '{0}' not found".format(template))
            else:
                mso.existing = []
        mso.exit_json()

    sites_path = '/sites'
    site_path = '/sites/{0}'.format(site)
    ops = []

    mso.previous = mso.existing
    if state == 'absent':
        if mso.existing:
            # Remove existing site
            mso.sent = mso.existing = {}
            ops.append(dict(op='remove', path=site_path))

    elif state == 'present':
        if not mso.existing:
            # Add new site
            payload = dict(
                siteId=site_id,
                templateName=template,
                anps=[],
                bds=[],
                contracts=[],
                externalEpgs=[],
                intersiteL3outs=[],
                serviceGraphs=[],
                vrfs=[],
            )

            mso.sanitize(payload, collate=True)

            ops.append(dict(op='add', path=sites_path + '/-', value=mso.sent))

            mso.existing = mso.proposed

    if not module.check_mode:
        mso.request(schema_path, method='PATCH', data=ops)

    mso.exit_json()
Exemplo n.º 8
0
def main():
    argument_spec = mso_argument_spec()
    argument_spec.update(
        schema=dict(type='str', required=True),
        site=dict(type='str', required=True),
        template=dict(type='str', required=True),
        anp=dict(type='str', aliases=[
            'name'
        ]),  # This parameter is not required for querying all objects
        state=dict(type='str',
                   default='present',
                   choices=['absent', 'present', 'query']),
    )

    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
        required_if=[
            ['state', 'absent', ['anp']],
            ['state', 'present', ['anp']],
        ],
    )

    schema = module.params['schema']
    site = module.params['site']
    template = module.params['template']
    anp = module.params['anp']
    state = module.params['state']

    mso = MSOModule(module)

    # Get schema_id
    schema_obj = mso.get_obj('schemas', displayName=schema)
    if not schema_obj:
        mso.fail_json(
            msg="Provided schema '{0}' does not exist".format(schema))

    schema_path = 'schemas/{id}'.format(**schema_obj)
    schema_id = schema_obj['id']

    # Get site
    site_id = mso.lookup_site(site)

    # Get site_idx
    sites = [(s['siteId'], s['templateName']) for s in schema_obj['sites']]
    if (site_id, template) not in sites:
        mso.fail_json(
            msg=
            "Provided site/template '{0}-{1}' does not exist. Existing sites/templates: {2}"
            .format(site, template, ', '.join(sites)))

    # Schema-access uses indexes
    site_idx = sites.index((site_id, template))
    # Path-based access uses site_id-template
    site_template = '{0}-{1}'.format(site_id, template)

    # Get ANP
    anp_ref = mso.anp_ref(schema_id=schema_id, template=template, anp=anp)
    anps = [a['anpRef'] for a in schema_obj['sites'][site_idx]['anps']]

    if anp is not None and anp_ref in anps:
        anp_idx = anps.index(anp_ref)
        # FIXME: Changes based on index are DANGEROUS
        anp_path = '/sites/{0}/anps/{1}'.format(site_template, anp_idx)
        mso.existing = schema_obj['sites'][site_idx]['anps'][anp_idx]

    if state == 'query':
        if anp is None:
            mso.existing = schema_obj['sites'][site_idx]['anps']
        elif not mso.existing:
            mso.fail_json(msg="ANP '{anp}' not found".format(anp=anp))
        mso.exit_json()

    anps_path = '/sites/{0}/anps'.format(site_template)
    ops = []

    mso.previous = mso.existing
    if state == 'absent':
        if mso.existing:
            mso.sent = mso.existing = {}
            ops.append(dict(op='remove', path=anp_path))

    elif state == 'present':

        payload = dict(anpRef=dict(
            schemaId=schema_id,
            templateName=template,
            anpName=anp,
        ), )

        mso.sanitize(payload, collate=True)

        if not mso.existing:
            ops.append(dict(op='add', path=anps_path + '/-', value=mso.sent))

        mso.existing = mso.proposed

    if not module.check_mode:
        mso.request(schema_path, method='PATCH', data=ops)

    mso.exit_json()
def main():
    argument_spec = mso_argument_spec()
    argument_spec.update(
        schema=dict(type='str', required=True),
        site=dict(type='str', required=True),
        template=dict(type='str', required=True),
        anp=dict(type='str', required=True),
        epg=dict(type='str', required=True),
        type=dict(type='str', default='port', choices=['port']),
        pod=dict(type='str'
                 ),  # This parameter is not required for querying all objects
        leaf=dict(type='str'
                  ),  # This parameter is not required for querying all objects
        path=dict(type='str'
                  ),  # This parameter is not required for querying all objects
        vlan=dict(type='int'
                  ),  # This parameter is not required for querying all objects
        deployment_immediacy=dict(type='str', choices=['immediate', 'lazy']),
        mode=dict(type='str', choices=['native', 'regular', 'untagged']),
        state=dict(type='str',
                   default='present',
                   choices=['absent', 'present', 'query']),
    )

    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
        required_if=[
            ['state', 'absent', ['type', 'pod', 'leaf', 'path', 'vlan']],
            ['state', 'present', ['type', 'pod', 'leaf', 'path', 'vlan']],
        ],
    )

    schema = module.params['schema']
    site = module.params['site']
    template = module.params['template']
    anp = module.params['anp']
    epg = module.params['epg']
    path_type = module.params['type']
    pod = module.params['pod']
    leaf = module.params['leaf']
    path = module.params['path']
    vlan = module.params['vlan']
    deployment_immediacy = module.params['deployment_immediacy']
    mode = module.params['mode']
    state = module.params['state']

    if path_type == 'port':
        portpath = 'topology/{0}/paths-{1}/pathep-[{2}]'.format(
            pod, leaf, path)

    mso = MSOModule(module)

    # Get schema_id
    schema_obj = mso.get_obj('schemas', displayName=schema)
    if not schema_obj:
        mso.fail_json(
            msg="Provided schema '{0}' does not exist".format(schema))

    schema_path = 'schemas/{id}'.format(**schema_obj)
    schema_id = schema_obj['id']

    # Get site
    site_id = mso.lookup_site(site)

    # Get site_idx
    sites = [(s['siteId'], s['templateName']) for s in schema_obj['sites']]
    if (site_id, template) not in sites:
        mso.fail_json(
            msg=
            "Provided site/template '{0}-{1}' does not exist. Existing sites/templates: {2}"
            .format(site, template, ', '.join(sites)))

    # Schema-access uses indexes
    site_idx = sites.index((site_id, template))
    # Path-based access uses site_id-template
    site_template = '{0}-{1}'.format(site_id, template)

    # Get ANP
    anp_ref = mso.anp_ref(schema_id=schema_id, template=template, anp=anp)
    anps = [a['anpRef'] for a in schema_obj['sites'][site_idx]['anps']]
    if anp_ref not in anps:
        mso.fail_json(
            msg="Provided anp '{0}' does not exist. Existing anps: {1}".format(
                anp, ', '.join(anps)))
    anp_idx = anps.index(anp_ref)

    # Get EPG
    epg_ref = mso.epg_ref(schema_id=schema_id,
                          template=template,
                          anp=anp,
                          epg=epg)
    epgs = [
        e['epgRef']
        for e in schema_obj['sites'][site_idx]['anps'][anp_idx]['epgs']
    ]
    if epg_ref not in epgs:
        mso.fail_json(
            msg="Provided epg '{0}' does not exist. Existing epgs: {1}".format(
                epg, ', '.join(epgs)))
    epg_idx = epgs.index(epg_ref)

    # Get Leaf
    portpaths = [
        p['path'] for p in schema_obj['sites'][site_idx]['anps'][anp_idx]
        ['epgs'][epg_idx]['staticPorts']
    ]
    if portpath in portpaths:
        portpath_idx = portpaths.index(portpath)
        # FIXME: Changes based on index are DANGEROUS
        port_path = '/sites/{0}/anps/{1}/epgs/{2}/staticPorts/{3}'.format(
            site_template, anp, epg, portpath_idx)
        mso.existing = schema_obj['sites'][site_idx]['anps'][anp_idx]['epgs'][
            epg_idx]['staticPorts'][portpath_idx]

    if state == 'query':
        if leaf is None or vlan is None:
            mso.existing = schema_obj['sites'][site_idx]['anps'][anp_idx][
                'epgs'][epg_idx]['staticPorts']
        elif not mso.existing:
            mso.fail_json(msg="Static port '{portpath}' not found".format(
                portpath=portpath))
        mso.exit_json()

    ports_path = '/sites/{0}/anps/{1}/epgs/{2}/staticPorts'.format(
        site_template, anp, epg)
    ops = []

    mso.previous = mso.existing
    if state == 'absent':
        if mso.existing:
            mso.sent = mso.existing = {}
            ops.append(dict(op='remove', path=port_path))

    elif state == 'present':
        if not mso.existing:
            if deployment_immediacy is None:
                deployment_immediacy = 'lazy'
            if mode is None:
                mode = 'untagged'

        payload = dict(
            deploymentImmediacy=deployment_immediacy,
            mode=mode,
            path=portpath,
            portEncapVlan=vlan,
            type=path_type,
        )

        mso.sanitize(payload, collate=True)

        if mso.existing:
            ops.append(dict(op='replace', path=port_path, value=mso.sent))
        else:
            ops.append(dict(op='add', path=ports_path + '/-', value=mso.sent))

        mso.existing = mso.proposed

    if not module.check_mode:
        mso.request(schema_path, method='PATCH', data=ops)

    mso.exit_json()
Exemplo n.º 10
0
def main():
    argument_spec = mso_argument_spec()
    argument_spec.update(
        schema=dict(type='str', required=True),
        site=dict(type='str', required=True),
        template=dict(type='str', required=True),
        vrf=dict(type='str', required=True),
        region=dict(type='str', required=True),
        cidr=dict(type='str', required=True),
        subnet=dict(type='str', aliases=[
            'ip'
        ]),  # This parameter is not required for querying all objects
        zone=dict(type='str', aliases=['name']),
        state=dict(type='str',
                   default='present',
                   choices=['absent', 'present', 'query']),
    )

    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
        required_if=[
            ['state', 'absent', ['subnet']],
            ['state', 'present', ['subnet', 'zone']],
        ],
    )

    schema = module.params.get('schema')
    site = module.params.get('site')
    template = module.params.get('template')
    vrf = module.params.get('vrf')
    region = module.params.get('region')
    cidr = module.params.get('cidr')
    subnet = module.params.get('subnet')
    zone = module.params.get('zone')
    state = module.params.get('state')

    mso = MSOModule(module)

    # Get schema_id
    schema_obj = mso.get_obj('schemas', displayName=schema)
    if not schema_obj:
        mso.fail_json(
            msg="Provided schema '{0}' does not exist".format(schema))

    schema_path = 'schemas/{id}'.format(**schema_obj)
    schema_id = schema_obj.get('id')

    # Get site
    site_id = mso.lookup_site(site)

    # Get site_idx
    sites = [(s.get('siteId'), s.get('templateName'))
             for s in schema_obj.get('sites')]
    if (site_id, template) not in sites:
        mso.fail_json(
            msg=
            "Provided site/template '{0}-{1}' does not exist. Existing sites/templates: {2}"
            .format(site, template, ', '.join(sites)))

    # Schema-access uses indexes
    site_idx = sites.index((site_id, template))
    # Path-based access uses site_id-template
    site_template = '{0}-{1}'.format(site_id, template)

    # Get VRF
    vrf_ref = mso.vrf_ref(schema_id=schema_id, template=template, vrf=vrf)
    vrfs = [v.get('vrfRef') for v in schema_obj.get('sites')[site_idx]['vrfs']]
    if vrf_ref not in vrfs:
        mso.fail_json(
            msg="Provided vrf '{0}' does not exist. Existing vrfs: {1}".format(
                vrf, ', '.join(vrfs)))
    vrf_idx = vrfs.index(vrf_ref)

    # Get Region
    regions = [
        r.get('name')
        for r in schema_obj.get('sites')[site_idx]['vrfs'][vrf_idx]['regions']
    ]
    if region not in regions:
        mso.fail_json(
            msg="Provided region '{0}' does not exist. Existing regions: {1}".
            format(region, ', '.join(regions)))
    region_idx = regions.index(region)

    # Get CIDR
    cidrs = [
        c.get('ip') for c in schema_obj.get('sites')[site_idx]['vrfs'][vrf_idx]
        ['regions'][region_idx]['cidrs']
    ]
    if cidr not in cidrs:
        mso.fail_json(
            msg="Provided CIDR IP '{0}' does not exist. Existing CIDR IPs: {1}"
            .format(cidr, ', '.join(cidrs)))
    cidr_idx = cidrs.index(cidr)

    # Get Subnet
    subnets = [
        s.get('ip') for s in schema_obj.get('sites')[site_idx]['vrfs'][vrf_idx]
        ['regions'][region_idx]['cidrs'][cidr_idx]['subnets']
    ]
    if subnet is not None and subnet in subnets:
        subnet_idx = subnets.index(subnet)
        # FIXME: Changes based on index are DANGEROUS
        subnet_path = '/sites/{0}/vrfs/{1}/regions/{2}/cidrs/{3}/subnets/{4}'.format(
            site_template, vrf, region, cidr_idx, subnet_idx)
        mso.existing = schema_obj.get('sites')[site_idx]['vrfs'][vrf_idx][
            'regions'][region_idx]['cidrs'][cidr_idx]['subnets'][subnet_idx]

    if state == 'query':
        if subnet is None:
            mso.existing = schema_obj.get('sites')[site_idx]['vrfs'][vrf_idx][
                'regions'][region_idx]['cidrs'][cidr_idx]['subnets']
        elif not mso.existing:
            mso.fail_json(msg="Subnet IP '{subnet}' not found".format(
                subnet=subnet))
        mso.exit_json()

    subnets_path = '/sites/{0}/vrfs/{1}/regions/{2}/cidrs/{3}/subnets'.format(
        site_template, vrf, region, cidr_idx)
    ops = []

    mso.previous = mso.existing
    if state == 'absent':
        if mso.existing:
            mso.sent = mso.existing = {}
            ops.append(dict(op='remove', path=subnet_path))

    elif state == 'present':

        payload = dict(
            ip=subnet,
            zone=zone,
        )

        mso.sanitize(payload, collate=True)

        if mso.existing:
            ops.append(dict(op='replace', path=subnet_path, value=mso.sent))
        else:
            ops.append(dict(op='add', path=subnets_path + '/-',
                            value=mso.sent))

        mso.existing = mso.proposed

    if not module.check_mode:
        mso.request(schema_path, method='PATCH', data=ops)

    mso.exit_json()
Exemplo n.º 11
0
def main():
    argument_spec = mso_argument_spec()
    argument_spec.update(
        schema=dict(type='str', required=True),
        site=dict(type='str', required=True),
        template=dict(type='str', required=True),
        bd=dict(type='str', aliases=['name']),  # This parameter is not required for querying all objects
        host_route=dict(type='bool'),
        state=dict(type='str', default='present', choices=['absent', 'present', 'query']),
    )

    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
        required_if=[
            ['state', 'absent', ['bd']],
            ['state', 'present', ['bd']],
        ],
    )

    schema = module.params.get('schema')
    site = module.params.get('site')
    template = module.params.get('template')
    bd = module.params.get('bd')
    host_route = module.params.get('host_route')
    state = module.params.get('state')

    mso = MSOModule(module)

    # Get schema_id
    schema_obj = mso.get_obj('schemas', displayName=schema)
    if not schema_obj:
        mso.fail_json(msg="Provided schema '{0}' does not exist".format(schema))

    schema_path = 'schemas/{id}'.format(**schema_obj)
    schema_id = schema_obj.get('id')

    # Get site
    site_id = mso.lookup_site(site)

    # Get site_idx
    sites = [(s.get('siteId'), s.get('templateName')) for s in schema_obj.get('sites')]
    if (site_id, template) not in sites:
        mso.fail_json(msg="Provided site/template '{0}-{1}' does not exist. Existing sites/templates: {2}".format(site, template, ', '.join(sites)))

    # Schema-access uses indexes
    site_idx = sites.index((site_id, template))
    # Path-based access uses site_id-template
    site_template = '{0}-{1}'.format(site_id, template)

    # Get BD
    bd_ref = mso.bd_ref(schema_id=schema_id, template=template, bd=bd)
    bds = [v.get('bdRef') for v in schema_obj.get('sites')[site_idx]['bds']]
    if bd is not None and bd_ref in bds:
        bd_idx = bds.index(bd_ref)
        bd_path = '/sites/{0}/bds/{1}'.format(site_template, bd)
        mso.existing = schema_obj.get('sites')[site_idx]['bds'][bd_idx]

    if state == 'query':
        if bd is None:
            mso.existing = schema_obj.get('sites')[site_idx]['bds']
        elif not mso.existing:
            mso.fail_json(msg="BD '{bd}' not found".format(bd=bd))
        mso.exit_json()

    bds_path = '/sites/{0}/bds'.format(site_template)
    ops = []

    mso.previous = mso.existing
    if state == 'absent':
        if mso.existing:
            mso.sent = mso.existing = {}
            ops.append(dict(op='remove', path=bd_path))

    elif state == 'present':
        if not mso.existing:
            if host_route is None:
                host_route = False

        payload = dict(
            bdRef=dict(
                schemaId=schema_id,
                templateName=template,
                bdName=bd,
            ),
            hostBasedRouting=host_route,
        )

        mso.sanitize(payload, collate=True)

        if mso.existing:
            ops.append(dict(op='replace', path=bd_path, value=mso.sent))
        else:
            ops.append(dict(op='add', path=bds_path + '/-', value=mso.sent))

        mso.existing = mso.proposed

    if not module.check_mode:
        mso.request(schema_path, method='PATCH', data=ops)

    mso.exit_json()
Exemplo n.º 12
0
def main():
    argument_spec = mso_argument_spec()
    argument_spec.update(
        schema=dict(type='str', required=True),
        site=dict(type='str', required=True),
        template=dict(type='str', required=True),
        bd=dict(type='str', required=True),
        l3out=dict(type='str', aliases=[
            'name'
        ]),  # This parameter is not required for querying all objects
        state=dict(type='str',
                   default='present',
                   choices=['absent', 'present', 'query']),
    )

    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
        required_if=[
            ['state', 'absent', ['l3out']],
            ['state', 'present', ['l3out']],
        ],
    )

    schema = module.params['schema']
    site = module.params['site']
    template = module.params['template']
    bd = module.params['bd']
    l3out = module.params['l3out']
    state = module.params['state']

    mso = MSOModule(module)

    # Get schema_id
    schema_obj = mso.get_obj('schemas', displayName=schema)
    if not schema_obj:
        mso.fail_json(
            msg="Provided schema '{0}' does not exist".format(schema))

    schema_path = 'schemas/{id}'.format(**schema_obj)
    schema_id = schema_obj['id']

    # Get site
    site_id = mso.lookup_site(site)

    # Get site_idx
    sites = [(s['siteId'], s['templateName']) for s in schema_obj['sites']]
    if (site_id, template) not in sites:
        mso.fail_json(
            msg=
            "Provided site/template '{0}-{1}' does not exist. Existing sites/templates: {2}"
            .format(site, template, ', '.join(sites)))

    # Schema-access uses indexes
    site_idx = sites.index((site_id, template))
    # Path-based access uses site_id-template
    site_template = '{0}-{1}'.format(site_id, template)

    # Get BD
    bd_ref = mso.bd_ref(schema_id=schema_id, template=template, bd=bd)
    bds = [v['bdRef'] for v in schema_obj['sites'][site_idx]['bds']]
    if bd_ref not in bds:
        mso.fail_json(
            msg="Provided BD '{0}' does not exist. Existing BDs: {1}".format(
                bd, ', '.join(bds)))
    bd_idx = bds.index(bd_ref)

    # Get L3out
    l3outs = schema_obj['sites'][site_idx]['bds'][bd_idx]['l3Outs']
    if l3out is not None and l3out in l3outs:
        l3out_idx = l3outs.index(l3out)
        l3out_path = '/sites/{0}/bds/{1}/l3Outs/{2}'.format(
            site_template, bd, l3out_idx)
        mso.existing = schema_obj['sites'][site_idx]['bds'][bd_idx]['l3Outs'][
            l3out_idx]

    if state == 'query':
        if l3out is None:
            mso.existing = schema_obj['sites'][site_idx]['bds'][bd_idx][
                'l3Outs']
        elif not mso.existing:
            mso.fail_json(msg="L3out '{l3out}' not found".format(l3out=l3out))
        mso.exit_json()

    l3outs_path = '/sites/{0}/bds/{1}/l3Outs'.format(site_template, bd)
    ops = []

    mso.previous = mso.existing
    if state == 'absent':
        if mso.existing:
            mso.sent = mso.existing = {}
            ops.append(dict(op='remove', path=l3out_path))

    elif state == 'present':
        mso.sent = l3out
        if not mso.existing:
            ops.append(dict(op='add', path=l3outs_path + '/-', value=l3out))

        mso.existing = mso.sent

    if not module.check_mode:
        mso.request(schema_path, method='PATCH', data=ops)

    mso.exit_json()
def main():
    argument_spec = mso_argument_spec()
    argument_spec.update(
        schema=dict(type='str', required=True),
        site=dict(type='str', required=True),
        template=dict(type='str', required=True),
        anp=dict(type='str', required=True),
        epg=dict(type='str', required=True),
        state=dict(type='str',
                   default='present',
                   choices=['absent', 'present', 'query']),
    )
    argument_spec.update(mso_subnet_spec())

    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
        required_if=[
            ['state', 'absent', ['subnet']],
            ['state', 'present', ['subnet']],
        ],
    )

    schema = module.params.get('schema')
    site = module.params.get('site')
    template = module.params.get('template')
    anp = module.params.get('anp')
    epg = module.params.get('epg')
    subnet = module.params.get('subnet')
    description = module.params.get('description')
    scope = module.params.get('scope')
    shared = module.params.get('shared')
    no_default_gateway = module.params.get('no_default_gateway')
    state = module.params.get('state')

    mso = MSOModule(module)

    # Get schema_id
    schema_obj = mso.get_obj('schemas', displayName=schema)
    if not schema_obj:
        mso.fail_json(
            msg="Provided schema '{0}' does not exist".format(schema))

    schema_path = 'schemas/{id}'.format(**schema_obj)
    schema_id = schema_obj.get('id')

    # Get site
    site_id = mso.lookup_site(site)

    # Get site_idx
    sites = [(s.get('siteId'), s.get('templateName'))
             for s in schema_obj.get('sites')]
    if (site_id, template) not in sites:
        mso.fail_json(
            msg=
            "Provided site/template '{0}-{1}' does not exist. Existing sites/templates: {2}"
            .format(site, template, ', '.join(sites)))

    # Schema-access uses indexes
    site_idx = sites.index((site_id, template))
    # Path-based access uses site_id-template
    site_template = '{0}-{1}'.format(site_id, template)

    # Get ANP
    anp_ref = mso.anp_ref(schema_id=schema_id, template=template, anp=anp)
    anps = [a.get('anpRef') for a in schema_obj.get('sites')[site_idx]['anps']]
    if anp_ref not in anps:
        mso.fail_json(
            msg="Provided anp '{0}' does not exist. Existing anps: {1}".format(
                anp, ', '.join(anps)))
    anp_idx = anps.index(anp_ref)

    # Get EPG
    epg_ref = mso.epg_ref(schema_id=schema_id,
                          template=template,
                          anp=anp,
                          epg=epg)
    epgs = [
        e.get('epgRef')
        for e in schema_obj.get('sites')[site_idx]['anps'][anp_idx]['epgs']
    ]
    if epg_ref not in epgs:
        mso.fail_json(
            msg="Provided epg '{0}' does not exist. Existing epgs: {1}".format(
                epg, ', '.join(epgs)))
    epg_idx = epgs.index(epg_ref)

    # Get Subnet
    subnets = [
        s.get('ip') for s in schema_obj.get('sites')[site_idx]['anps'][anp_idx]
        ['epgs'][epg_idx]['subnets']
    ]
    if subnet in subnets:
        subnet_idx = subnets.index(subnet)
        # FIXME: Changes based on index are DANGEROUS
        subnet_path = '/sites/{0}/anps/{1}/epgs/{2}/subnets/{3}'.format(
            site_template, anp, epg, subnet_idx)
        mso.existing = schema_obj.get('sites')[site_idx]['anps'][anp_idx][
            'epgs'][epg_idx]['subnets'][subnet_idx]

    if state == 'query':
        if subnet is None:
            mso.existing = schema_obj.get(
                'sites')[site_idx]['anps'][anp_idx]['epgs'][epg_idx]['subnets']
        elif not mso.existing:
            mso.fail_json(msg="Subnet '{subnet}' not found".format(
                subnet=subnet))
        mso.exit_json()

    subnets_path = '/sites/{0}/anps/{1}/epgs/{2}/subnets'.format(
        site_template, anp, epg)
    ops = []

    mso.previous = mso.existing
    if state == 'absent':
        if mso.existing:
            mso.sent = mso.existing = {}
            ops.append(dict(op='remove', path=subnet_path))

    elif state == 'present':
        if not mso.existing:
            if description is None:
                description = subnet
            if scope is None:
                scope = 'private'
            if shared is None:
                shared = False
            if no_default_gateway is None:
                no_default_gateway = False

        payload = dict(
            ip=subnet,
            description=description,
            scope=scope,
            shared=shared,
            noDefaultGateway=no_default_gateway,
        )

        mso.sanitize(payload, collate=True)

        if mso.existing:
            ops.append(dict(op='replace', path=subnet_path, value=mso.sent))
        else:
            ops.append(dict(op='add', path=subnets_path + '/-',
                            value=mso.sent))

        mso.existing = mso.proposed

    if not module.check_mode:
        mso.request(schema_path, method='PATCH', data=ops)

    mso.exit_json()
def main():
    argument_spec = mso_argument_spec()
    argument_spec.update(
        schema=dict(type='str', required=True),
        site=dict(type='str', required=True),
        template=dict(type='str', required=True),
        vrf=dict(type='str', required=True),
        region=dict(type='str', required=True),
        cidr=dict(type='str', aliases=[
            'ip'
        ]),  # This parameter is not required for querying all objects
        primary=dict(type='bool'),
        state=dict(type='str',
                   default='present',
                   choices=['absent', 'present', 'query']),
    )

    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
        required_if=[
            ['state', 'absent', ['cidr']],
            ['state', 'present', ['cidr']],
        ],
    )

    schema = module.params['schema']
    site = module.params['site']
    template = module.params['template']
    vrf = module.params['vrf']
    region = module.params['region']
    cidr = module.params['cidr']
    primary = module.params['primary']
    state = module.params['state']

    mso = MSOModule(module)

    # Get schema_id
    schema_obj = mso.get_obj('schemas', displayName=schema)
    if not schema_obj:
        mso.fail_json(
            msg="Provided schema '{0}' does not exist".format(schema))

    schema_path = 'schemas/{id}'.format(**schema_obj)
    schema_id = schema_obj['id']

    # Get site
    site_id = mso.lookup_site(site)

    # Get site_idx
    sites = [(s['siteId'], s['templateName']) for s in schema_obj['sites']]
    if (site_id, template) not in sites:
        mso.fail_json(
            msg=
            "Provided site/template '{0}-{1}' does not exist. Existing sites/templates: {2}"
            .format(site, template, ', '.join(sites)))

    # Schema-access uses indexes
    site_idx = sites.index((site_id, template))
    # Path-based access uses site_id-template
    site_template = '{0}-{1}'.format(site_id, template)

    # Get VRF
    vrf_ref = mso.vrf_ref(schema_id=schema_id, template=template, vrf=vrf)
    vrfs = [v['vrfRef'] for v in schema_obj['sites'][site_idx]['vrfs']]
    if vrf_ref not in vrfs:
        mso.fail_json(
            msg="Provided vrf '{0}' does not exist. Existing vrfs: {1}".format(
                vrf, ', '.join(vrfs)))
    vrf_idx = vrfs.index(vrf_ref)

    # Get Region
    regions = [
        r['name']
        for r in schema_obj['sites'][site_idx]['vrfs'][vrf_idx]['regions']
    ]
    if region not in regions:
        mso.fail_json(
            msg="Provided region '{0}' does not exist. Existing regions: {1}".
            format(region, ', '.join(regions)))
    region_idx = regions.index(region)

    # Get CIDR
    cidrs = [
        c['ip'] for c in schema_obj['sites'][site_idx]['vrfs'][vrf_idx]
        ['regions'][region_idx]['cidrs']
    ]
    if cidr is not None and cidr in cidrs:
        cidr_idx = cidrs.index(cidr)
        cidr_path = '/sites/{0}/vrfs/{1}/regions/{2}/cidrs/{3}'.format(
            site_template, vrf, region, cidr_idx)
        mso.existing = schema_obj['sites'][site_idx]['vrfs'][vrf_idx][
            'regions'][region_idx]['cidrs'][cidr_idx]

    if state == 'query':
        if cidr is None:
            mso.existing = schema_obj['sites'][site_idx]['vrfs'][vrf_idx][
                'regions'][region_idx]['cidrs']
        elif not mso.existing:
            mso.fail_json(msg="CIDR IP '{cidr}' not found".format(cidr=cidr))
        mso.exit_json()

    cidrs_path = '/sites/{0}/vrfs/{1}/regions/{2}/cidrs'.format(
        site_template, vrf, region)
    ops = []

    mso.previous = mso.existing
    if state == 'absent':
        if mso.existing:
            mso.sent = mso.existing = {}
            ops.append(dict(op='remove', path=cidr_path))

    elif state == 'present':
        if not mso.existing:
            if primary is None:
                primary = False

        payload = dict(
            ip=cidr,
            primary=primary,
        )

        mso.sanitize(payload, collate=True)

        if mso.existing:
            ops.append(dict(op='replace', path=cidr_path, value=mso.sent))
        else:
            ops.append(dict(op='add', path=cidrs_path + '/-', value=mso.sent))

        mso.existing = mso.proposed

    if not module.check_mode:
        mso.request(schema_path, method='PATCH', data=ops)

    mso.exit_json()