コード例 #1
0
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()
コード例 #3
0
def main():
    argument_spec = mso_argument_spec()
    argument_spec.update(
        tenant=dict(type='str', required=True),
        schema=dict(type='str', required=True),
        template=dict(type='str', aliases=['name']),
        display_name=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', ['template']],
            ['state', 'present', ['template']],
        ],
    )

    tenant = module.params.get('tenant')
    schema = module.params.get('schema')
    template = module.params.get('template')
    display_name = module.params.get('display_name')
    state = module.params.get('state')

    mso = MSOModule(module)

    # Get schema
    schema_obj = mso.get_obj('schemas', displayName=schema)

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

        # Get template
        templates = [t.get('name') for t in schema_obj.get('templates')]
        if template:
            if template in templates:
                template_idx = templates.index(template)
                mso.existing = schema_obj.get('templates')[template_idx]
        else:
            mso.existing = schema_obj.get('templates')
    else:
        schema_path = 'schemas'

    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()

    template_path = '/templates/{0}'.format(template)
    ops = []

    mso.previous = mso.existing
    if state == 'absent':
        mso.proposed = mso.sent = {}

        if not schema_obj:
            # There was no schema to begin with
            pass
        elif len(templates) == 1:
            # There is only one tenant, remove schema
            mso.existing = {}
            if not module.check_mode:
                mso.request(schema_path, method='DELETE')
        elif mso.existing:
            # Remove existing template
            mso.existing = {}
            ops.append(dict(op='remove', path=template_path))
        else:
            # There was no template to begin with
            pass

    elif state == 'present':
        tenant_id = mso.lookup_tenant(tenant)

        if display_name is None:
            display_name = mso.existing.get('displayName', template)

        if not schema_obj:
            # Schema does not exist, so we have to create it
            payload = dict(
                displayName=schema,
                templates=[
                    dict(
                        name=template,
                        displayName=display_name,
                        tenantId=tenant_id,
                    )
                ],
                sites=[],
            )

            mso.existing = payload.get('templates')[0]

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

        elif mso.existing:
            # Template exists, so we have to update it
            payload = dict(
                name=template,
                displayName=display_name,
                tenantId=tenant_id,
            )

            mso.sanitize(payload, collate=True)

            ops.append(
                dict(op='replace',
                     path=template_path + '/displayName',
                     value=display_name))
            ops.append(
                dict(op='replace',
                     path=template_path + '/tenantId',
                     value=tenant_id))

            mso.existing = mso.proposed
        else:
            # Template does not exist, so we have to add it
            payload = dict(
                name=template,
                displayName=display_name,
                tenantId=tenant_id,
            )

            mso.sanitize(payload, collate=True)

            ops.append(dict(op='add', path='/templates/-', value=payload))

            mso.existing = mso.proposed

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

    mso.exit_json()
コード例 #4
0
def main():
    argument_spec = mso_argument_spec()
    argument_spec.update(
        role=dict(type='str', required=False, aliases=['name', 'role_name']),
        role_id=dict(type='str', required=False),
        display_name=dict(type='str'),
        description=dict(type='str'),
        permissions=dict(type='list',
                         choices=[
                             'backup-db',
                             'manage-audit-records',
                             'manage-labels',
                             'manage-roles',
                             'manage-schemas',
                             'manage-sites',
                             'manage-tenants',
                             'manage-tenant-schemas',
                             'manage-users',
                             'platform-logs',
                             'view-all-audit-records',
                             'view-labels',
                             'view-roles',
                             'view-schemas',
                             'view-sites',
                             'view-tenants',
                             'view-tenant-schemas',
                             'view-users',
                         ]),
        state=dict(type='str',
                   default='present',
                   choices=['absent', 'present', 'query']),
    )

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

    role = module.params['role']
    role_id = module.params['role_id']
    description = module.params['description']
    permissions = module.params['permissions']
    state = module.params['state']

    mso = MSOModule(module)

    path = 'roles'

    # Query for existing object(s)
    if role_id is None and role is None:
        mso.existing = mso.query_objs(path)
    elif role_id is None:
        mso.existing = mso.get_obj(path, name=role)
        if mso.existing:
            role_id = mso.existing['id']
    elif role is None:
        mso.existing = mso.get_obj(path, id=role_id)
    else:
        mso.existing = mso.get_obj(path, id=role_id)
        existing_by_name = mso.get_obj(path, name=role)
        if existing_by_name and role_id != existing_by_name['id']:
            mso.fail_json(
                msg=
                "Provided role '{0}' with id '{1}' does not match existing id '{2}'."
                .format(role, role_id, existing_by_name['id']))

    # If we found an existing object, continue with it
    if role_id:
        path = 'roles/{id}'.format(id=role_id)

    if state == 'query':
        pass

    elif state == 'absent':
        mso.previous = mso.existing
        if mso.existing:
            if module.check_mode:
                mso.existing = {}
            else:
                mso.existing = mso.request(path, method='DELETE')

    elif state == 'present':
        mso.previous = mso.existing

        payload = dict(
            id=role_id,
            name=role,
            displayName=role,
            description=description,
            permissions=permissions,
        )

        mso.sanitize(payload, collate=True)

        if mso.existing:
            if not issubset(mso.sent, mso.existing):
                if module.check_mode:
                    mso.existing = mso.proposed
                else:
                    mso.existing = mso.request(path,
                                               method='PUT',
                                               data=mso.sent)
        else:
            if module.check_mode:
                mso.existing = mso.proposed
            else:
                mso.existing = mso.request(path, method='POST', data=mso.sent)

    mso.exit_json()
コード例 #5
0
ファイル: mso_label.py プロジェクト: zealot00/ansible
def main():
    argument_spec = mso_argument_spec()
    argument_spec.update(
        label=dict(type='str', aliases=['name']),
        type=dict(type='str', default='site', choices=['site']),
        state=dict(type='str',
                   default='present',
                   choices=['absent', 'present', 'query']),
    )

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

    label = module.params.get('label')
    label_type = module.params.get('type')
    state = module.params.get('state')

    mso = MSOModule(module)

    label_id = None
    path = 'labels'

    # Query for existing object(s)
    if label:
        mso.existing = mso.get_obj(path, displayName=label)
        if mso.existing:
            label_id = mso.existing.get('id')
            # If we found an existing object, continue with it
            path = 'labels/{id}'.format(id=label_id)
    else:
        mso.existing = mso.query_objs(path)

    if state == 'query':
        pass

    elif state == 'absent':
        mso.previous = mso.existing
        if mso.existing:
            if module.check_mode:
                mso.existing = {}
            else:
                mso.existing = mso.request(path, method='DELETE')

    elif state == 'present':
        mso.previous = mso.existing

        payload = dict(
            id=label_id,
            displayName=label,
            type=label_type,
        )

        mso.sanitize(payload, collate=True)

        if mso.existing:
            if not issubset(mso.sent, mso.existing):
                if module.check_mode:
                    mso.existing = mso.proposed
                else:
                    mso.existing = mso.request(path,
                                               method='PUT',
                                               data=mso.sent)
        else:
            if module.check_mode:
                mso.existing = mso.proposed
            else:
                mso.existing = mso.request(path, method='POST', data=mso.sent)

    mso.exit_json()
コード例 #6
0
ファイル: mso_schema_site.py プロジェクト: zealot00/ansible
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()
コード例 #7
0
def main():
    argument_spec = mso_argument_spec()
    argument_spec.update(
        schema=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
        bd=dict(type='dict', options=mso_reference_spec()),
        display_name=dict(type='str'),
        useg_epg=dict(type='bool'),
        intra_epg_isolation=dict(type='str', choices=['enforced', 'unenforced']),
        intersite_multicaste_source=dict(type='bool'),
        subnets=dict(type='list', options=mso_subnet_spec()),
        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['schema']
    template = module.params['template']
    anp = module.params['anp']
    epg = module.params['epg']
    display_name = module.params['display_name']
    bd = module.params['bd']
    useg_epg = module.params['useg_epg']
    intra_epg_isolation = module.params['intra_epg_isolation']
    intersite_multicaste_source = module.params['intersite_multicaste_source']
    subnets = module.params['subnets']
    state = module.params['state']

    mso = MSOModule(module)

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

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

    # Get template
    templates = [t['name'] for t in schema_obj['templates']]
    if template not in templates:
        mso.fail_json(msg="Provided template '{0}' does not exist. Existing templates: {1}".format(template, ', '.join(templates)))
    template_idx = templates.index(template)

    # Get ANP
    anps = [a['name'] for a in schema_obj['templates'][template_idx]['anps']]
    if anp 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)

    # Get EPG
    epgs = [e['name'] for e in schema_obj['templates'][template_idx]['anps'][anp_idx]['epgs']]
    if epg is not None and epg in epgs:
        epg_idx = epgs.index(epg)
        mso.existing = schema_obj['templates'][template_idx]['anps'][anp_idx]['epgs'][epg_idx]

    if state == 'query':
        if epg is None:
            mso.existing = schema_obj['templates'][template_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 = '/templates/{0}/anps/{1}/epgs'.format(template, anp)
    epg_path = '/templates/{0}/anps/{1}/epgs/{2}'.format(template, anp, epg)
    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':
        bd_ref = mso.make_reference(bd, 'bd', schema_id, template)
        subnets = mso.make_subnets(subnets)

        if display_name is None and not mso.existing:
            display_name = epg

        payload = dict(
            name=epg,
            displayName=display_name,
            uSegEpg=useg_epg,
            intraEpg=intra_epg_isolation,
            proxyArp=intersite_multicaste_source,
            # FIXME: Missing functionality
            # uSegAttrs=[],
            contractRelationships=[],
            subnets=subnets,
            bdRef=bd_ref,
        )

        mso.sanitize(payload, collate=True)

        if mso.existing:
            ops.append(dict(op='replace', path=epg_path, value=mso.sent))
        else:
            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()
コード例 #8
0
def main():
    argument_spec = mso_argument_spec()
    argument_spec.update(
        schema=dict(type='str', required=True),
        template=dict(type='str', required=True),
        bd=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', ['ip']],
            ['state', 'present', ['ip']],
        ],
    )

    schema = module.params['schema']
    template = module.params['template']
    bd = module.params['bd']
    ip = module.params['ip']
    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
    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)

    # Get template
    templates = [t['name'] for t in schema_obj['templates']]
    if template not in templates:
        mso.fail_json(
            msg="Provided template '{0}' does not exist. Existing templates: {1}"
            .format(template, ', '.join(templates)))
    template_idx = templates.index(template)

    # Get EPG
    bds = [b['name'] for b in schema_obj['templates'][template_idx]['bds']]
    if bd 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)

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

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

    subnets_path = '/templates/{0}/bds/{1}/subnets'.format(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 description is None and not mso.existing:
            description = ip
        if scope is None and not mso.existing:
            scope = 'private'
        if shared is None and not mso.existing:
            shared = False
        if no_default_gateway is None and not mso.existing:
            no_default_gateway = False

        payload = dict(
            ip=ip,
            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()
コード例 #9
0
def main():
    argument_spec = mso_argument_spec()
    argument_spec.update(
        schema=dict(type='str', required=True),
        template=dict(type='str', required=True),
        contract=dict(
            type='str', required=False
        ),  # This parameter is not required for querying all objects
        contract_display_name=dict(type='str'),
        contract_scope=dict(
            type='str',
            required=True,
            choices=['application-profile', 'global', 'tenant', 'vrf']),
        filter=dict(type='str', aliases=['name']),
        filter_template=dict(type='str'),
        filter_schema=dict(type='str'),
        filter_type=dict(type='str',
                         default='both-directions',
                         choices=FILTER_KEYS.keys(),
                         aliases=['type']),
        state=dict(type='str',
                   default='present',
                   choices=['absent', 'present', 'query']),
    )

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

    schema = module.params['schema']
    template = module.params['template']
    contract = module.params['contract']
    contract_display_name = module.params['contract_display_name']
    contract_scope = module.params['contract_scope']
    filter_name = module.params['filter']
    filter_template = module.params['filter_template']
    filter_schema = module.params['filter_schema']
    filter_type = module.params['filter_type']
    state = module.params['state']

    if filter_template is None:
        filter_template = template

    if filter_schema is None:
        filter_schema = schema

    filter_key = FILTER_KEYS[filter_type]

    mso = MSOModule(module)

    filter_schema_id = mso.lookup_schema(filter_schema)

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

    path = 'schemas/{id}'.format(id=schema_id)

    # Get template
    templates = [t['name'] for t in schema_obj['templates']]
    if template not in templates:
        mso.fail_json(
            msg="Provided template '{0}' does not exist. Existing templates: {1}"
            .format(template, ', '.join(templates)))
    template_idx = templates.index(template)

    # Get contracts
    mso.existing = {}
    contract_idx = None
    entry_idx = None
    contracts = [
        c['name'] for c in schema_obj['templates'][template_idx]['contracts']
    ]

    if contract in contracts:
        contract_idx = contracts.index(contract)

        filters = [
            f['filterRef'] for f in schema_obj['templates'][template_idx]
            ['contracts'][contract_idx][filter_key]
        ]
        filter_ref = mso.filter_ref(filter_schema_id, filter_template,
                                    filter_name)
        if filter_ref in filters:
            filter_idx = filters.index(filter_ref)
            mso.existing = schema_obj['templates'][template_idx]['contracts'][
                contract_idx][filter_key][filter_idx]

    if state == 'query':
        if filter_name is None:
            mso.existing = schema_obj['templates'][template_idx]['contractss'][
                contract_idx][filter_key]
        elif not mso.existing:
            mso.fail_json(msg="FilterRef '{filter_ref}' not found".format(
                filter_ref=filter_ref))
        mso.exit_json()

    mso.previous = mso.existing
    if state == 'absent':
        mso.proposed = mso.sent = {}

        if contract_idx is None:
            # There was no contract to begin with
            pass
        elif filter_idx is None:
            # There was no filter to begin with
            pass
        elif len(filters) == 1:
            # There is only one filter, remove contract
            mso.existing = {}
            operations = [
                dict(op='remove',
                     path='/templates/{template}/contracts/{contract}'.format(
                         template=template, contract=contract)),
            ]
            if not module.check_mode:
                mso.request(path, method='PATCH', data=operations)
        else:
            # FIXME: Removing based on index is DANGEROUS
            # Remove filter
            mso.existing = {}
            operations = [
                dict(
                    op='remove',
                    path=
                    '/templates/{template}/contracts/{contract}/{filter_key}/{filter_idx}'
                    .format(
                        template=template,
                        contract=contract,
                        filter_key=filter_key,
                        filter_idx=filter_idx,
                    ),
                ),
            ]
            if not module.check_mode:
                mso.request(path, method='PATCH', data=operations)

    elif state == 'present':

        payload = dict(
            filterRef=dict(
                filterName=filter_name,
                templateName=filter_template,
                schemaId=filter_schema_id,
            ),
            directives=[],
        )

        mso.sanitize(payload, collate=True)
        mso.existing = mso.sent

        if contract_idx is None:
            # COntract does not exist, so we have to create it
            if contract_display_name is None:
                contract_display_name = contract

            payload = {
                'name': contract,
                'displayName': contract_display_name,
                'scope': contract_scope,
                filter_key: [mso.sent],
            }

            operations = [
                dict(op='add',
                     path='/templates/{template}/contracts/-'.format(
                         template=template),
                     value=payload),
            ]

        elif filter_idx is None:
            # Filter does not exist, so we have to add it
            operations = [
                dict(
                    op='add',
                    path=
                    '/templates/{template}/contracts/{contract}/{filter_key}/-'
                    .format(
                        template=template,
                        contract=contract,
                        filter_key=filter_key,
                    ),
                    value=mso.sent,
                ),
            ]

        else:
            # FIXME: Updating based on index is DANGEROUS
            # Filter exists, we have to update it
            operations = [
                dict(
                    op='replace',
                    path=
                    '/templates/{template}/contracts/{contract}/{filter_key}/{filter_idx}'
                    .format(
                        template=template,
                        contract=contract,
                        filter_key=filter_key,
                        filter_idx=filter_idx,
                    ),
                    value=mso.sent,
                ),
            ]

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

    mso.exit_json()
コード例 #10
0
def main():
    argument_spec = mso_argument_spec()
    argument_spec.update(
        schema=dict(type='str', aliases=['name']),
        templates=dict(type='list'),
        sites=dict(type='list'),
        # messages=dict(type='dict'),
        # associations=dict(type='list'),
        # health_faults=dict(type='list'),
        # references=dict(type='dict'),
        # policy_states=dict(type='list'),
        state=dict(type='str',
                   default='present',
                   choices=['absent', 'present', 'query']),
    )

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

    schema = module.params['schema']
    templates = module.params['templates']
    sites = module.params['sites']
    state = module.params['state']

    mso = MSOModule(module)

    schema_id = None
    path = 'schemas'

    # Query for existing object(s)
    if schema:
        mso.existing = mso.get_obj(path, displayName=schema)
        if mso.existing:
            schema_id = mso.existing['id']
            path = 'schemas/{id}'.format(id=schema_id)
    else:
        mso.existing = mso.query_objs(path)

    if state == 'query':
        pass

    elif state == 'absent':
        mso.previous = mso.existing
        if mso.existing:
            if module.check_mode:
                mso.existing = {}
            else:
                mso.existing = mso.request(path, method='DELETE')

    elif state == 'present':
        mso.previous = mso.existing

        payload = dict(
            id=schema_id,
            displayName=schema,
            templates=templates,
            sites=sites,
        )

        mso.sanitize(payload, collate=True)

        if mso.existing:
            if not issubset(mso.sent, mso.existing):
                if module.check_mode:
                    mso.existing = mso.proposed
                else:
                    mso.existing = mso.request(path,
                                               method='PUT',
                                               data=mso.sent)
        else:
            if module.check_mode:
                mso.existing = mso.proposed
            else:
                mso.existing = mso.request(path, method='POST', data=mso.sent)

    mso.exit_json()
コード例 #11
0
def main():
    argument_spec = mso_argument_spec()
    argument_spec.update(
        schema=dict(type='str', required=True),
        template=dict(type='str', required=True),
        l3out=dict(type='str', required=False, aliases=[
            'name'
        ]),  # This parameter is not required for querying all objects
        display_name=dict(type='str'),
        vrf=dict(type='dict', options=mso_reference_spec()),
        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', 'vrf']],
        ],
    )

    schema = module.params['schema']
    template = module.params['template']
    l3out = module.params['l3out']
    display_name = module.params['display_name']
    vrf = module.params['vrf']
    state = module.params['state']

    mso = MSOModule(module)

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

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

    # Get template
    templates = [t['name'] for t in schema_obj['templates']]
    if template not in templates:
        mso.fail_json(
            msg="Provided template '{0}' does not exist. Existing templates: {1}"
            .format(template, ', '.join(templates)))
    template_idx = templates.index(template)

    # Get L3out
    l3outs = [
        l['name']
        for l in schema_obj['templates'][template_idx]['intersiteL3outs']
    ]

    if l3out is not None and l3out in l3outs:
        l3out_idx = l3outs.index(l3out)
        mso.existing = schema_obj['templates'][template_idx][
            'intersiteL3outs'][l3out_idx]

    if state == 'query':
        if l3out is None:
            mso.existing = schema_obj['templates'][template_idx][
                'intersiteL3outs']
        elif not mso.existing:
            mso.fail_json(msg="L3out '{l3out}' not found".format(l3out=l3out))
        mso.exit_json()

    l3outs_path = '/templates/{0}/intersiteL3outs'.format(template)
    l3out_path = '/templates/{0}/intersiteL3outs/{1}'.format(template, l3out)
    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':
        vrf_ref = mso.make_reference(vrf, 'vrf', schema_id, template)

        if display_name is None and not mso.existing:
            display_name = l3out

        payload = dict(
            name=l3out,
            displayName=display_name,
            vrfRef=vrf_ref,
        )

        mso.sanitize(payload, collate=True)

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

        mso.existing = mso.proposed

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

    mso.exit_json()
コード例 #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),
        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()
コード例 #13
0
def main():
    argument_spec = mso_argument_spec()
    argument_spec.update(
        schema=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['schema']
    template = module.params['template']
    anp = module.params['anp']
    epg = module.params['epg']
    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
    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)

    # Get template
    templates = [t['name'] for t in schema_obj['templates']]
    if template not in templates:
        mso.fail_json(
            msg=
            "Provided template '{template}' does not exist. Existing templates: {templates}"
            .format(template=template, templates=', '.join(templates)))
    template_idx = templates.index(template)

    # Get ANP
    anps = [a['name'] for a in schema_obj['templates'][template_idx]['anps']]
    if anp not in anps:
        mso.fail_json(
            msg="Provided anp '{anp}' does not exist. Existing anps: {anps}".
            format(anp=anp, anps=', '.join(anps)))
    anp_idx = anps.index(anp)

    # Get EPG
    epgs = [
        e['name']
        for e in schema_obj['templates'][template_idx]['anps'][anp_idx]['epgs']
    ]
    if epg not in epgs:
        mso.fail_json(
            msg="Provided epg '{epg}' does not exist. Existing epgs: {epgs}".
            format(epg=epg, epgs=', '.join(epgs)))
    epg_idx = epgs.index(epg)

    # Get Subnet
    subnets = [
        s['ip'] for s in schema_obj['templates'][template_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 = '/templates/{0}/anps/{1}/epgs/{2}/subnets/{3}'.format(
            template, anp, epg, subnet_idx)
        mso.existing = schema_obj['templates'][template_idx]['anps'][anp_idx][
            'epgs'][epg_idx]['subnets'][subnet_idx]

    if state == 'query':
        if subnet is None:
            mso.existing = schema_obj['templates'][template_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 = '/templates/{0}/anps/{1}/epgs/{2}/subnets'.format(
        template, anp, epg)
    ops = []

    mso.previous = mso.existing
    if state == 'absent':
        if mso.existing:
            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()
コード例 #14
0
def main():
    argument_spec = mso_argument_spec()
    argument_spec.update(
        label=dict(type='str', aliases=['name']),
        label_id=dict(type='str'),
        type=dict(type='str', default='site', choices=['site']),
        state=dict(type='str', default='present', choices=['absent', 'present', 'query']),
    )

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

    label = module.params['label']
    label_id = module.params['label_id']
    label_type = module.params['type']
    state = module.params['state']

    mso = MSOModule(module)

    path = 'labels'

    # Query for existing object(s)
    if label_id is None and label is None:
        mso.existing = mso.query_objs(path)
    elif label_id is None:
        mso.existing = mso.get_obj(path, displayName=label)
        if mso.existing:
            label_id = mso.existing['id']
    elif label is None:
        mso.existing = mso.get_obj(path, id=label_id)
    else:
        mso.existing = mso.get_obj(path, id=label_id)
        existing_by_name = mso.get_obj(path, displayName=label)
        if existing_by_name and label_id != existing_by_name['id']:
            mso.fail_json(msg="Provided label '{0}' with id '{1}' does not match existing id '{2}'.".format(label, label_id, existing_by_name['id']))

    # If we found an existing object, continue with it
    if label_id:
        path = 'labels/{id}'.format(id=label_id)

    if state == 'query':
        pass

    elif state == 'absent':
        mso.previous = mso.existing
        if mso.existing:
            if module.check_mode:
                mso.existing = {}
            else:
                mso.existing = mso.request(path, method='DELETE')

    elif state == 'present':
        mso.previous = mso.existing

        payload = dict(
            id=label_id,
            displayName=label,
            type=label_type,
        )

        mso.sanitize(payload, collate=True)

        if mso.existing:
            if not issubset(mso.sent, mso.existing):
                if module.check_mode:
                    mso.existing = mso.proposed
                else:
                    mso.existing = mso.request(path, method='PUT', data=mso.sent)
        else:
            if module.check_mode:
                mso.existing = mso.proposed
            else:
                mso.existing = mso.request(path, method='POST', data=mso.sent)

    mso.exit_json()
コード例 #15
0
ファイル: mso_schema_site_anp.py プロジェクト: ydd171/public
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()
コード例 #16
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),
        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()
コード例 #17
0
def main():
    argument_spec = mso_argument_spec()
    argument_spec.update(
        description=dict(type='str'),
        display_name=dict(type='str'),
        tenant=dict(type='str', aliases=['name']),
        users=dict(type='list'),
        sites=dict(type='list'),
        state=dict(type='str',
                   default='present',
                   choices=['absent', 'present', 'query']),
    )

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

    description = module.params['description']
    display_name = module.params['display_name']
    tenant = module.params['tenant']
    state = module.params['state']

    mso = MSOModule(module)

    # Convert sites and users
    sites = mso.lookup_sites(module.params['sites'])
    users = mso.lookup_users(module.params['users'])

    tenant_id = None
    path = 'tenants'

    # Query for existing object(s)
    if tenant:
        mso.existing = mso.get_obj(path, name=tenant)
        if mso.existing:
            tenant_id = mso.existing['id']
            # If we found an existing object, continue with it
            path = 'tenants/{id}'.format(id=tenant_id)
    else:
        mso.existing = mso.query_objs(path)

    if state == 'query':
        pass

    elif state == 'absent':
        mso.previous = mso.existing
        if mso.existing:
            if module.check_mode:
                mso.existing = {}
            else:
                mso.existing = mso.request(path, method='DELETE')

    elif state == 'present':
        mso.previous = mso.existing

        payload = dict(
            description=description,
            id=tenant_id,
            name=tenant,
            displayName=display_name,
            siteAssociations=sites,
            userAssociations=users,
        )

        mso.sanitize(payload, collate=True)

        # Ensure displayName is not undefined
        if mso.sent.get('displayName') is None:
            mso.sent['displayName'] = tenant

        # Ensure tenant has at least admin user
        if mso.sent.get('userAssociations') is None:
            mso.sent['userAssociations'] = [
                dict(userId="0000ffff0000000000000020")
            ]

        if mso.existing:
            if not issubset(mso.sent, mso.existing):
                if module.check_mode:
                    mso.existing = mso.proposed
                else:
                    mso.existing = mso.request(path,
                                               method='PUT',
                                               data=mso.sent)
        else:
            if module.check_mode:
                mso.existing = mso.proposed
            else:
                mso.existing = mso.request(path, method='POST', data=mso.sent)

    mso.exit_json()
コード例 #18
0
def main():
    argument_spec = mso_argument_spec()
    argument_spec.update(
        schema=dict(type='str', required=True),
        template=dict(type='str', required=True),
        anp=dict(type='str', required=True),
        epg=dict(type='str', required=True),
        contract=dict(type='dict', options=mso_contractref_spec()),
        state=dict(type='str',
                   default='present',
                   choices=['absent', 'present', 'query']),
    )

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

    schema = module.params['schema']
    template = module.params['template']
    anp = module.params['anp']
    epg = module.params['epg']
    contract = module.params['contract']
    state = module.params['state']

    mso = MSOModule(module)

    if contract:
        if contract.get('schema') is None:
            contract['schema'] = schema
        contract['schema_id'] = mso.lookup_schema(contract['schema'])
        if contract.get('template') is None:
            contract['template'] = template

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

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

    # Get template
    templates = [t['name'] for t in schema_obj['templates']]
    if template not in templates:
        mso.fail_json(
            msg="Provided template '{0}' does not exist. Existing templates: {1}"
            .format(template, ', '.join(templates)))
    template_idx = templates.index(template)

    # Get ANP
    anps = [a['name'] for a in schema_obj['templates'][template_idx]['anps']]
    if anp 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)

    # Get EPG
    epgs = [
        e['name']
        for e in schema_obj['templates'][template_idx]['anps'][anp_idx]['epgs']
    ]
    if epg not in epgs:
        mso.fail_json(
            msg="Provided epg '{epg}' does not exist. Existing epgs: {epgs}".
            format(epg=epg, epgs=', '.join(epgs)))
    epg_idx = epgs.index(epg)

    # Get Contract
    if contract:
        contracts = [(c['contractRef'], c['relationshipType'])
                     for c in schema_obj['templates'][template_idx]['anps']
                     [anp_idx]['epgs'][epg_idx]['contractRelationships']]
        contract_ref = mso.contract_ref(contract)
        if (contract_ref, contract['type']) in contracts:
            contract_idx = contracts.index((contract_ref, contract['type']))
            # FIXME: Changes based on index are DANGEROUS
            contract_path = '/templates/{0}/anps/{1}/epgs/{2}/contractRelationships/{3}'.format(
                template, anp, epg, contract_idx)
            mso.existing = schema_obj['templates'][template_idx]['anps'][
                anp_idx]['epgs'][epg_idx]['contractRelationships'][
                    contract_idx]

    if state == 'query':
        if not contract:
            mso.existing = schema_obj['templates'][template_idx]['anps'][
                anp_idx]['epgs'][epg_idx]['contractRelationships']
        elif not mso.existing:
            mso.fail_json(msg="Contract '{0}' not found".format(contract_ref))
        mso.exit_json()

    contracts_path = '/templates/{0}/anps/{1}/epgs/{2}/contractRelationships'.format(
        template, anp, epg)
    ops = []

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

    elif state == 'present':
        payload = dict(
            relationshipType=contract['type'],
            contractRef=dict(
                contractName=contract['name'],
                templateName=contract['template'],
                schemaId=contract['schema_id'],
            ),
        )

        mso.sanitize(payload, collate=True)

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

        mso.existing = mso.proposed

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

    mso.exit_json()
コード例 #19
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()
コード例 #20
0
def main():
    argument_spec = mso_argument_spec()
    argument_spec.update(
        schema=dict(type='str', required=True),
        template=dict(type='str', required=True),
        contract=dict(type='str', required=True),
        contract_display_name=dict(type='str'),
        contract_scope=dict(
            type='str',
            choices=['application-profile', 'global', 'tenant', 'vrf']),
        contract_filter_type=dict(type='str', choices=['both-way', 'one-way']),
        filter=dict(type='str', aliases=[
            'name'
        ]),  # This parameter is not required for querying all objects
        filter_directives=dict(type='list', choices=['log', 'none']),
        filter_template=dict(type='str'),
        filter_schema=dict(type='str'),
        filter_type=dict(type='str',
                         default='both-way',
                         choices=FILTER_KEYS.keys(),
                         aliases=['type']),
        state=dict(type='str',
                   default='present',
                   choices=['absent', 'present', 'query']),
    )

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

    schema = module.params['schema']
    template = module.params['template']
    contract = module.params['contract']
    contract_display_name = module.params['contract_display_name']
    contract_filter_type = module.params['contract_filter_type']
    contract_scope = module.params['contract_scope']
    filter_name = module.params['filter']
    filter_directives = module.params['filter_directives']
    filter_template = module.params['filter_template']
    filter_schema = module.params['filter_schema']
    filter_type = module.params['filter_type']
    state = module.params['state']

    contract_ftype = 'bothWay' if contract_filter_type == 'both-way' else 'oneWay'

    if contract_filter_type == 'both-way' and filter_type != 'both-way':
        module.warn(
            "You are adding 'one-way' filters to a 'both-way' contract")
    elif contract_filter_type != 'both-way' and filter_type == 'both-way':
        module.warn(
            "You are adding 'both-way' filters to a 'one-way' contract")

    if filter_template is None:
        filter_template = template

    if filter_schema is None:
        filter_schema = schema

    filter_key = FILTER_KEYS[filter_type]

    mso = MSOModule(module)

    filter_schema_id = mso.lookup_schema(filter_schema)

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

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

    # Get template
    templates = [t['name'] for t in schema_obj['templates']]
    if template not in templates:
        mso.fail_json(
            msg="Provided template '{0}' does not exist. Existing templates: {1}"
            .format(template, ', '.join(templates)))
    template_idx = templates.index(template)

    # Get contracts
    mso.existing = {}
    contract_idx = None
    filter_idx = None
    contracts = [
        c['name'] for c in schema_obj['templates'][template_idx]['contracts']
    ]

    if contract in contracts:
        contract_idx = contracts.index(contract)

        filters = [
            f['filterRef'] for f in schema_obj['templates'][template_idx]
            ['contracts'][contract_idx][filter_key]
        ]
        filter_ref = mso.filter_ref(schema_id=filter_schema_id,
                                    template=filter_template,
                                    filter=filter_name)
        if filter_ref in filters:
            filter_idx = filters.index(filter_ref)
            filter_path = '/templates/{0}/contracts/{1}/{2}/{3}'.format(
                template, contract, filter_key, filter_name)
            mso.existing = schema_obj['templates'][template_idx]['contracts'][
                contract_idx][filter_key][filter_idx]

    if state == 'query':
        if contract_idx is None:
            mso.fail_json(
                msg=
                "Provided contract '{0}' does not exist. Existing contracts: {1}"
                .format(contract, ', '.join(contracts)))

        if filter_name is None:
            mso.existing = schema_obj['templates'][template_idx]['contracts'][
                contract_idx][filter_key]
        elif not mso.existing:
            mso.fail_json(msg="FilterRef '{filter_ref}' not found".format(
                filter_ref=filter_ref))
        mso.exit_json()

    ops = []
    contract_path = '/templates/{0}/contracts/{1}'.format(template, contract)
    filters_path = '/templates/{0}/contracts/{1}/{2}'.format(
        template, contract, filter_key)

    mso.previous = mso.existing
    if state == 'absent':
        mso.proposed = mso.sent = {}

        if contract_idx is None:
            # There was no contract to begin with
            pass
        elif filter_idx is None:
            # There was no filter to begin with
            pass
        elif len(filters) == 1:
            # There is only one filter, remove contract
            mso.existing = {}
            ops.append(dict(op='remove', path=contract_path))
        else:
            # Remove filter
            mso.existing = {}
            ops.append(dict(op='remove', path=filter_path))

    elif state == 'present':
        if filter_directives is None:
            filter_directives = ['none']

        payload = dict(
            filterRef=dict(
                filterName=filter_name,
                templateName=filter_template,
                schemaId=filter_schema_id,
            ),
            directives=filter_directives,
        )

        mso.sanitize(payload, collate=True)
        mso.existing = mso.sent

        if contract_idx is None:
            # Contract does not exist, so we have to create it
            if contract_display_name is None:
                contract_display_name = contract
            if contract_filter_type is None:
                contract_ftype = 'bothWay'
            if contract_scope is None:
                contract_scope = 'context'

            payload = {
                'name': contract,
                'displayName': contract_display_name,
                'filterType': contract_ftype,
                'scope': contract_scope,
            }

            ops.append(
                dict(op='add',
                     path='/templates/{0}/contracts/-'.format(template),
                     value=payload))
        else:
            # Contract exists, but may require an update
            if contract_display_name is not None:
                ops.append(
                    dict(op='replace',
                         path=contract_path + '/displayName',
                         value=contract_display_name))
            if contract_filter_type is not None:
                ops.append(
                    dict(op='replace',
                         path=contract_path + '/filterType',
                         value=contract_ftype))
            if contract_scope is not None:
                ops.append(
                    dict(op='replace',
                         path=contract_path + '/scope',
                         value=contract_scope))

        if filter_idx is None:
            # Filter does not exist, so we have to add it
            ops.append(dict(op='add', path=filters_path + '/-',
                            value=mso.sent))

        else:
            # Filter exists, we have to update it
            ops.append(dict(op='replace', path=filter_path, value=mso.sent))

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

    mso.exit_json()
コード例 #21
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()
コード例 #22
0
def main():
    argument_spec = mso_argument_spec()
    argument_spec.update(
        schema=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
        display_name=dict(type='str'),
        intersite_bum_traffic=dict(type='bool'),
        optimize_wan_bandwidth=dict(type='bool'),
        layer2_stretch=dict(type='bool'),
        layer2_unknown_unicast=dict(type='str', choices=['flood', 'proxy']),
        layer3_multicast=dict(type='bool'),
        vrf=dict(type='dict', options=mso_reference_spec()),
        subnets=dict(type='list', options=mso_subnet_spec()),
        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', 'vrf']],
        ],
    )

    schema = module.params['schema']
    template = module.params['template']
    bd = module.params['bd']
    display_name = module.params['display_name']
    intersite_bum_traffic = module.params['intersite_bum_traffic']
    optimize_wan_bandwidth = module.params['optimize_wan_bandwidth']
    layer2_stretch = module.params['layer2_stretch']
    layer2_unknown_unicast = module.params['layer2_unknown_unicast']
    layer3_multicast = module.params['layer3_multicast']
    vrf = module.params['vrf']
    subnets = module.params['subnets']
    state = module.params['state']

    mso = MSOModule(module)

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

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

    # Get template
    templates = [t['name'] for t in schema_obj['templates']]
    if template not in templates:
        mso.fail_json(
            msg="Provided template '{0}' does not exist. Existing templates: {1}"
            .format(template, ', '.join(templates)))
    template_idx = templates.index(template)

    # Get ANP
    bds = [b['name'] for b in schema_obj['templates'][template_idx]['bds']]

    if bd is not None and bd in bds:
        bd_idx = bds.index(bd)
        mso.existing = schema_obj['templates'][template_idx]['bds'][bd_idx]

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

    bds_path = '/templates/{0}/bds'.format(template)
    bd_path = '/templates/{0}/bds/{1}'.format(template, bd)
    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':
        vrf_ref = mso.make_reference(vrf, 'vrf', schema_id, template)
        subnets = mso.make_subnets(subnets)

        if display_name is None and not mso.existing:
            display_name = bd
        if subnets is None and not mso.existing:
            subnets = []

        payload = dict(
            name=bd,
            displayName=display_name,
            intersiteBumTrafficAllow=intersite_bum_traffic,
            optimizeWanBandwidth=optimize_wan_bandwidth,
            l2UnknownUnicast=layer2_unknown_unicast,
            l2Stretch=layer2_stretch,
            l3MCast=layer3_multicast,
            subnets=subnets,
            vrfRef=vrf_ref,
        )

        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()
コード例 #23
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()
コード例 #24
0
ファイル: mso_site.py プロジェクト: Vemulashiva/Ansible
def main():
    location_arg_spec = dict(
        latitude=dict(type='float'),
        longitude=dict(type='float'),
    )

    argument_spec = mso_argument_spec()
    argument_spec.update(
        apic_password=dict(type='str', no_log=True),
        apic_site_id=dict(type='str'),
        apic_username=dict(type='str', default='admin'),
        labels=dict(type='list'),
        location=dict(type='dict', options=location_arg_spec),
        site=dict(type='str', aliases=['name']),
        state=dict(type='str',
                   default='present',
                   choices=['absent', 'present', 'query']),
        urls=dict(type='list'),
    )

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

    apic_username = module.params['apic_username']
    apic_password = module.params['apic_password']
    apic_site_id = module.params['apic_site_id']
    site = module.params['site']
    location = module.params['location']
    if location is not None:
        latitude = module.params['location']['latitude']
        longitude = module.params['location']['longitude']
    state = module.params['state']
    urls = module.params['urls']

    mso = MSOModule(module)

    site_id = None
    path = 'sites'

    # Convert labels
    labels = mso.lookup_labels(module.params['labels'], 'site')

    # Query for mso.existing object(s)
    if site:
        mso.existing = mso.get_obj(path, name=site)
        if mso.existing:
            site_id = mso.existing['id']
            # If we found an existing object, continue with it
            path = 'sites/{id}'.format(id=site_id)
    else:
        mso.existing = mso.query_objs(path)

    if state == 'query':
        pass

    elif state == 'absent':
        mso.previous = mso.existing
        if mso.existing:
            if module.check_mode:
                mso.existing = {}
            else:
                mso.existing = mso.request(path,
                                           method='DELETE',
                                           qs=dict(force='true'))

    elif state == 'present':
        mso.previous = mso.existing

        payload = dict(
            apicSiteId=apic_site_id,
            id=site_id,
            name=site,
            urls=urls,
            labels=labels,
            username=apic_username,
            password=apic_password,
        )

        if location is not None:
            payload['location'] = dict(
                lat=latitude,
                long=longitude,
            )

        mso.sanitize(payload, collate=True)

        if mso.existing:
            if not issubset(mso.sent, mso.existing):
                if module.check_mode:
                    mso.existing = mso.proposed
                else:
                    mso.existing = mso.request(path,
                                               method='PUT',
                                               data=mso.sent)
        else:
            if module.check_mode:
                mso.existing = mso.proposed
            else:
                mso.existing = mso.request(path, method='POST', data=mso.sent)

    if 'password' in mso.existing:
        mso.existing['password'] = '******'

    mso.exit_json()
コード例 #25
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()
コード例 #26
0
def main():
    argument_spec = mso_argument_spec()
    argument_spec.update(
        schema=dict(type='str', required=True),
        template=dict(type='str', required=True),
        anp=dict(type='str', required=False, aliases=[
            'name'
        ]),  # This parameter is not required for querying all objects
        display_name=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', ['anp']],
            ['state', 'present', ['anp']],
        ],
    )

    schema = module.params['schema']
    template = module.params['template']
    anp = module.params['anp']
    display_name = module.params['display_name']
    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)

    # Get template
    templates = [t['name'] for t in schema_obj['templates']]
    if template not in templates:
        mso.fail_json(
            msg="Provided template '{0}' does not exist. Existing templates: {1}"
            .format(template, ', '.join(templates)))
    template_idx = templates.index(template)

    # Get ANP
    anps = [a['name'] for a in schema_obj['templates'][template_idx]['anps']]

    if anp is not None and anp in anps:
        anp_idx = anps.index(anp)
        mso.existing = schema_obj['templates'][template_idx]['anps'][anp_idx]

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

    anps_path = '/templates/{0}/anps'.format(template)
    anp_path = '/templates/{0}/anps/{1}'.format(template, anp)
    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':

        if display_name is None and not mso.existing:
            display_name = anp

        epgs = []
        if mso.existing:
            epgs = None

        payload = dict(
            name=anp,
            displayName=display_name,
            epgs=epgs,
        )

        mso.sanitize(payload, collate=True)

        if mso.existing:
            if display_name is not None:
                ops.append(
                    dict(op='replace',
                         path=anp_path + '/displayName',
                         value=display_name))
        else:
            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()
コード例 #27
0
def main():
    argument_spec = mso_argument_spec()
    argument_spec.update(
        schema=dict(type='str', required=True),
        template=dict(type='str', required=True),
        externalepg=dict(type='str', aliases=['name']),  # This parameter is not required for querying all objects
        display_name=dict(type='str'),
        vrf=dict(type='dict', options=mso_reference_spec()),
        state=dict(type='str', default='present', choices=['absent', 'present', 'query']),
    )

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

    schema = module.params['schema']
    template = module.params['template']
    externalepg = module.params['externalepg']
    display_name = module.params['display_name']
    vrf = module.params['vrf']
    state = module.params['state']

    mso = MSOModule(module)

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

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

    # Get template
    templates = [t['name'] for t in schema_obj['templates']]
    if template not in templates:
        mso.fail_json(msg="Provided template '{0}' does not exist. Existing templates: {1}".format(template, ', '.join(templates)))
    template_idx = templates.index(template)

    # Get external EPGs
    externalepgs = [e['name'] for e in schema_obj['templates'][template_idx]['externalEpgs']]

    if externalepg is not None and externalepg in externalepgs:
        externalepg_idx = externalepgs.index(externalepg)
        mso.existing = schema_obj['templates'][template_idx]['externalEpgs'][externalepg_idx]

    if state == 'query':
        if externalepg is None:
            mso.existing = schema_obj['templates'][template_idx]['externalEpgs']
        elif not mso.existing:
            mso.fail_json(msg="External EPG '{externalepg}' not found".format(externalepg=externalepg))
        mso.exit_json()

    eepgs_path = '/templates/{0}/externalEpgs'.format(template)
    eepg_path = '/templates/{0}/externalEpgs/{1}'.format(template, externalepg)
    ops = []

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

    elif state == 'present':
        vrf_ref = mso.make_reference(vrf, 'vrf', schema_id, template)

        if display_name is None and not mso.existing:
            display_name = externalepg

        payload = dict(
            name=externalepg,
            displayName=display_name,
            vrfRef=vrf_ref,
            # FIXME
            subnets=[],
            contractRelationships=[],
        )

        mso.sanitize(payload, collate=True)

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

        mso.existing = mso.proposed

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

    mso.exit_json()
コード例 #28
0
def main():
    argument_spec = mso_argument_spec()
    argument_spec.update(
        schema=dict(type='str', required=True),
        template=dict(type='str', required=True),
        vrf=dict(type='str', required=False, aliases=[
            'name'
        ]),  # This parameter is not required for querying all objects
        display_name=dict(type='str'),
        layer3_multicast=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', ['vrf']],
            ['state', 'present', ['vrf']],
        ],
    )

    schema = module.params['schema']
    template = module.params['template']
    vrf = module.params['vrf']
    display_name = module.params['display_name']
    layer3_multicast = module.params['layer3_multicast']
    state = module.params['state']

    mso = MSOModule(module)

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

    path = 'schemas/{id}'.format(id=schema_id)

    # Get template
    templates = [t['name'] for t in schema_obj['templates']]
    if template not in templates:
        mso.fail_json(
            msg="Provided template '{0}' does not exist. Existing templates: {1}"
            .format(template, ', '.join(templates)))
    template_idx = templates.index(template)

    # Get ANP
    vrfs = [v['name'] for v in schema_obj['templates'][template_idx]['vrfs']]

    if vrf is not None and vrf in vrfs:
        vrf_idx = vrfs.index(vrf)
        mso.existing = schema_obj['templates'][template_idx]['vrfs'][vrf_idx]

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

    mso.previous = mso.existing
    if state == 'absent':
        if mso.existing:
            mso.sent = mso.existing = {}
            operation = [
                dict(
                    op='remove',
                    path='/templates/{template}/vrfs/{vrf}'.format(
                        template=template, vrf=vrf),
                )
            ]
            if not module.check_mode:
                mso.request(path, method='PATCH', data=operation)

    elif state == 'present':
        if display_name is None and not mso.existing:
            display_name = vrf

        payload = dict(
            name=vrf,
            displayName=display_name,
            l3MCast=layer3_multicast,
            # FIXME
            regions=[],
        )

        mso.sanitize(payload, collate=True)

        if mso.existing:
            operation = [
                dict(
                    op='replace',
                    path='/templates/{template}/vrfs/{vrf}'.format(
                        template=template, vrf=vrf),
                    value=mso.sent,
                )
            ]

        else:
            operation = [
                dict(
                    op='add',
                    path='/templates/{template}/vrfs/-'.format(
                        template=template),
                    value=mso.sent,
                )
            ]

        mso.existing = mso.proposed
        if not module.check_mode:
            mso.request(path, method='PATCH', data=operation)

    mso.exit_json()
コード例 #29
0
def main():
    argument_spec = mso_argument_spec()
    argument_spec.update(
        schema=dict(type='str', required=True),
        template=dict(type='str', required=True),
        filter=dict(
            type='str', required=True
        ),  # This parameter is not required for querying all objects
        filter_display_name=dict(type='str', aliases=['filter_display_name']),
        entry=dict(type='str', required=True, aliases=['name']),
        description=dict(type='str', aliases=['entry_description']),
        display_name=dict(type='str', aliases=['entry_display_name']),
        ethertype=dict(type='str',
                       choices=[
                           'arp', 'fcoe', 'ip', 'ipv4', 'ipv6', 'mac-security',
                           'mpls-unicast', 'trill', 'unspecified'
                       ]),
        ip_protocol=dict(type='str',
                         choices=[
                             'eigrp', 'egp', 'icmp', 'icmpv6', 'igmp', 'igp',
                             'l2tp', 'ospfigp', 'pim', 'tcp', 'udp',
                             'unspecified'
                         ]),
        tcp_session_rules=dict(type='list',
                               choices=[
                                   'acknowledgement', 'established', 'finish',
                                   'synchronize', 'reset', 'unspecified'
                               ]),
        source_from=dict(type='str'),
        source_to=dict(type='str'),
        destination_from=dict(type='str'),
        destination_to=dict(type='str'),
        arp_flag=dict(type='str', choices=['reply', 'request', 'unspecified']),
        stateful=dict(type='bool'),
        fragments_only=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', ['entry']],
            ['state', 'present', ['entry']],
        ],
    )

    schema = module.params['schema']
    template = module.params['template']
    filter_name = module.params['filter']
    filter_display_name = module.params['filter_display_name']
    entry = module.params['entry']
    display_name = module.params['display_name']
    description = module.params['description']
    ethertype = module.params['ethertype']
    ip_protocol = module.params['ip_protocol']
    tcp_session_rules = module.params['tcp_session_rules']
    source_from = module.params['source_from']
    source_to = module.params['source_to']
    destination_from = module.params['destination_from']
    destination_to = module.params['destination_to']
    arp_flag = module.params['arp_flag']
    stateful = module.params['stateful']
    fragments_only = module.params['fragments_only']
    state = module.params['state']

    mso = MSOModule(module)

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

    path = 'schemas/{id}'.format(id=schema_id)

    # Get template
    templates = [t['name'] for t in schema_obj['templates']]
    if template not in templates:
        mso.fail_json(
            msg=
            "Provided template '{template}' does not exist. Existing templates: {templates}"
            .format(template=template, templates=', '.join(templates)))
    template_idx = templates.index(template)

    # Get filters
    mso.existing = {}
    filter_idx = None
    entry_idx = None
    filters = [
        f['name'] for f in schema_obj['templates'][template_idx]['filters']
    ]
    if filter_name in filters:
        filter_idx = filters.index(filter_name)

        entries = [
            f['name'] for f in schema_obj['templates'][template_idx]['filters']
            [filter_idx]['entries']
        ]
        if entry in entries:
            entry_idx = entries.index(entry)
            mso.existing = schema_obj['templates'][template_idx]['filters'][
                filter_idx]['entries'][entry_idx]

    if state == 'query':
        if entry is None:
            mso.existing = schema_obj['templates'][template_idx]['filters'][
                filter_idx]['entries']
        elif not mso.existing:
            mso.fail_json(msg="Entry '{entry}' not found".format(entry=entry))
        mso.exit_json()

    mso.previous = mso.existing
    if state == 'absent':
        mso.proposed = mso.sent = {}

        if filter_idx is None:
            # There was no filter to begin with
            pass
        elif entry_idx is None:
            # There was no entry to begin with
            pass
        elif len(entries) == 1:
            # There is only one entry, remove filter
            mso.existing = {}
            operations = [
                dict(op='remove',
                     path='/templates/{template}/filters/{filter}'.format(
                         template=template, filter=filter_name)),
            ]
            if not module.check_mode:
                mso.request(path, method='PATCH', data=operations)
        else:
            mso.existing = {}
            operations = [
                dict(
                    op='remove',
                    path='/templates/{template}/filters/{filter}/entries/{entry}'
                    .format(template=template, filter=filter_name,
                            entry=entry)),
            ]
            if not module.check_mode:
                mso.request(path, method='PATCH', data=operations)

    elif state == 'present':

        if display_name is None:
            display_name = mso.existing.get('displayName', entry)
        if description is None:
            description = mso.existing.get('description', '')
        if ethertype is None:
            ethertype = mso.existing.get('etherType', 'unspecified')
        if ip_protocol is None:
            ip_protocol = mso.existing.get('ipProtocol', 'unspecified')
        if tcp_session_rules is None:
            tcp_session_rules = mso.existing.get('tcpSessionRules',
                                                 ['unspecified'])
        if source_from is None:
            source_from = mso.existing.get('sourceFrom', 'unspecified')
        if source_to is None:
            source_to = mso.existing.get('sourceTo', 'unspecified')
        if destination_from is None:
            destination_from = mso.existing.get('destinationFrom',
                                                'unspecified')
        if destination_to is None:
            destination_to = mso.existing.get('destinationTo', 'unspecified')
        if arp_flag is None:
            arp_flag = mso.existing.get('arpFlag', 'unspecified')
        if stateful is None:
            stateful = mso.existing.get('stateful', False)
        if fragments_only is None:
            fragments_only = mso.existing.get('matchOnlyFragments', False)

        payload = dict(
            name=entry,
            displayName=display_name,
            description=description,
            etherType=ethertype,
            ipProtocol=ip_protocol,
            tcpSessionRules=tcp_session_rules,
            sourceFrom=source_from,
            sourceTo=source_to,
            destinationFrom=destination_from,
            destinationTo=destination_to,
            arpFlag=arp_flag,
            stateful=stateful,
            matchOnlyFragments=fragments_only,
        )

        mso.sanitize(payload, collate=True)
        mso.existing = mso.sent

        if filter_idx is None:
            # Filter does not exist, so we have to create it
            if filter_display_name is None:
                filter_display_name = filter_name

            payload = dict(
                name=filter_name,
                displayName=filter_display_name,
                entries=[mso.sent],
            )

            operations = [
                dict(op='add',
                     path='/templates/{template}/filters/-'.format(
                         template=template),
                     value=payload),
            ]

        elif entry_idx is None:
            # Entry does not exist, so we have to add it
            operations = [
                dict(op='add',
                     path='/templates/{template}/filters/{filter}/entries/-'.
                     format(template=template, filter=filter_name),
                     value=mso.sent)
            ]

        else:
            # Entry exists, we have to update it
            alias = '/templates/{template}/filters/{filter}/entries/{entry}'.format(
                template=template, filter=filter_name, entry=entry)
            operations = [
                dict(op='replace',
                     path='{alias}/name'.format(alias=alias),
                     value=entry),
                dict(op='replace',
                     path='{alias}/displayName'.format(alias=alias),
                     value=display_name),
                dict(op='replace',
                     path='{alias}/description'.format(alias=alias),
                     value=description),
                dict(op='replace',
                     path='{alias}/etherType'.format(alias=alias),
                     value=ethertype),
                dict(op='replace',
                     path='{alias}/ipProtocol'.format(alias=alias),
                     value=ip_protocol),
                dict(op='replace',
                     path='{alias}/tcpSessionRules'.format(alias=alias),
                     value=tcp_session_rules),
                dict(op='replace',
                     path='{alias}/sourceFrom'.format(alias=alias),
                     value=source_from),
                dict(op='replace',
                     path='{alias}/sourceTo'.format(alias=alias),
                     value=source_to),
                dict(op='replace',
                     path='{alias}/destinationFrom'.format(alias=alias),
                     value=destination_from),
                dict(op='replace',
                     path='{alias}/destinationTo'.format(alias=alias),
                     value=destination_to),
                dict(op='replace',
                     path='{alias}/arpFlag'.format(alias=alias),
                     value=arp_flag),
                dict(op='replace',
                     path='{alias}/stateful'.format(alias=alias),
                     value=stateful),
                dict(op='replace',
                     path='{alias}/matchOnlyFragments'.format(alias=alias),
                     value=fragments_only),
            ]

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

    mso.exit_json()
コード例 #30
0
ファイル: mso_user.py プロジェクト: zship/ansible
def main():
    argument_spec = mso_argument_spec()
    argument_spec.update(
        user_id=dict(type='str', required=False),
        user=dict(type='str', required=False, aliases=['name', 'user_name']),
        user_password=dict(type='str', no_log=True),
        first_name=dict(type='str'),
        last_name=dict(type='str'),
        email=dict(type='str'),
        phone=dict(type='str'),
        # TODO: What possible options do we have ?
        account_status=dict(type='str', choices=['active']),
        domain=dict(type='str'),
        roles=dict(type='list'),
        state=dict(type='str',
                   default='present',
                   choices=['absent', 'present', 'query']),
    )

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

    user_id = module.params['user_id']
    user_name = module.params['user']
    user_password = module.params['user_password']
    first_name = module.params['first_name']
    last_name = module.params['last_name']
    email = module.params['email']
    phone = module.params['phone']
    account_status = module.params['account_status']
    state = module.params['state']

    mso = MSOModule(module)

    roles = mso.lookup_roles(module.params['roles'])
    domain = mso.lookup_domain(module.params['domain'])

    path = 'users'

    # Query for existing object(s)
    if user_id is None and user_name is None:
        mso.existing = mso.query_objs(path)
    elif user_id is None:
        mso.existing = mso.get_obj(path, username=user_name)
        if mso.existing:
            user_id = mso.existing['id']
    elif user_name is None:
        mso.existing = mso.get_obj(path, id=user_id)
    else:
        mso.existing = mso.get_obj(path, id=user_id)
        existing_by_name = mso.get_obj(path, username=user_name)
        if existing_by_name and user_id != existing_by_name['id']:
            mso.fail_json(
                msg=
                "Provided user '{0}' with id '{1}' does not match existing id '{2}'."
                .format(user_name, user_id, existing_by_name['id']))

    # If we found an existing object, continue with it
    if user_id:
        path = 'users/{id}'.format(id=user_id)

    if state == 'query':
        pass

    elif state == 'absent':
        mso.previous = mso.existing
        if mso.existing:
            if module.check_mode:
                mso.existing = {}
            else:
                mso.existing = mso.request(path, method='DELETE')

    elif state == 'present':
        mso.previous = mso.existing

        payload = dict(
            id=user_id,
            username=user_name,
            password=user_password,
            firstName=first_name,
            lastName=last_name,
            emailAddress=email,
            phoneNumber=phone,
            accountStatus=account_status,
            domainId=domain,
            roles=roles,
            # active=True,
            # remote=True,
        )

        mso.sanitize(payload, collate=True)

        if mso.sent.get('accountStatus') is None:
            mso.sent['accountStatus'] = 'active'

        if mso.existing:
            if not issubset(mso.sent, mso.existing):
                # NOTE: Since MSO always returns '******' as password, we need to assume a change
                if 'password' in mso.proposed:
                    mso.module.warn(
                        "A password change is assumed, as the MSO REST API does not return passwords we do not know."
                    )
                    mso.result['changed'] = True

                if module.check_mode:
                    mso.existing = mso.proposed
                else:
                    mso.existing = mso.request(path,
                                               method='PUT',
                                               data=mso.sent)
        else:
            if module.check_mode:
                mso.existing = mso.proposed
            else:
                mso.existing = mso.request(path, method='POST', data=mso.sent)

    mso.exit_json()