Esempio n. 1
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',
                                  default='both-way',
                                  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=list(FILTER_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.get('schema')
    template = module.params.get('template')
    contract = module.params.get('contract')
    contract_display_name = module.params.get('contract_display_name')
    contract_filter_type = module.params.get('contract_filter_type')
    contract_scope = module.params.get('contract_scope')
    filter_name = module.params.get('filter')
    filter_directives = module.params.get('filter_directives')
    filter_template = module.params.get('filter_template')
    filter_schema = module.params.get('filter_schema')
    filter_type = module.params.get('filter_type')
    state = module.params.get('state')

    mso = MSOModule(module)

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

    if contract_filter_type == 'both-way' and filter_type != 'both-way':
        mso.fail_json(
            msg="You are adding 'one-way' filters to a 'both-way' contract")
    elif contract_filter_type != 'both-way' and filter_type == 'both-way':
        mso.fail_json(
            msg="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.get(filter_type)

    # Get schema object
    schema_obj = mso.get_obj('schemas', displayName=schema)
    if schema_obj:
        schema_id = schema_obj.get('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.get('name') for t in schema_obj.get('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)

    filter_schema_id = mso.lookup_schema(filter_schema)
    # Get contracts

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

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

        filters = [
            f.get('filterRef') for f in schema_obj.get('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.get('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.get('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_scope is None or contract_scope == 'vrf':
            contract_scope = 'context'
        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,
                '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))
            ops.append(
                dict(op='replace',
                     path=contract_path + '/filterType',
                     value=contract_ftype))
            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 'filterRef' in mso.previous:
        mso.previous['filterRef'] = mso.dict_from_ref(
            mso.previous['filterRef'])

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

    mso.exit_json()
Esempio n. 2
0
def main():
    argument_spec = mso_argument_spec()
    argument_spec.update(
        schema=dict(type='str', required=True),
        template=dict(type='str', required=True),
        external_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.get('schema')
    template = module.params.get('template').replace(' ', '')
    external_epg = module.params.get('external_epg')
    contract = module.params.get('contract')
    if contract is not None and contract.get('template') is not None:
        contract['template'] = contract.get('template').replace(' ', '')
    state = module.params.get('state')

    mso = MSOModule(module)

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

    # Get schema
    schema_id, schema_path, schema_obj = mso.query_schema(schema)

    # Get template
    templates = [t.get('name') for t in schema_obj.get('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
    epgs = [e.get('name') for e in schema_obj.get('templates')[template_idx]['externalEpgs']]
    if external_epg not in epgs:
        mso.fail_json(msg="Provided epg '{epg}' does not exist. Existing epgs: {epgs}".format(epg=external_epg, epgs=', '.join(epgs)))
    epg_idx = epgs.index(external_epg)

    # Get Contract
    if contract:
        contracts = [(c.get('contractRef'),
                      c.get('relationshipType')) for c in schema_obj.get('templates')[template_idx]['externalEpgs'][epg_idx]['contractRelationships']]
        contract_ref = mso.contract_ref(**contract)
        if (contract_ref, contract.get('type')) in contracts:
            contract_idx = contracts.index((contract_ref, contract.get('type')))
            contract_path = '/templates/{0}/externalEpgs/{1}/contractRelationships/{2}'.format(template, external_epg, contract_idx)
            mso.existing = schema_obj.get('templates')[template_idx]['externalEpgs'][epg_idx]['contractRelationships'][contract_idx]

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

        if 'contractRef' in mso.existing:
            mso.existing['contractRef'] = mso.dict_from_ref(mso.existing.get('contractRef'))
        mso.exit_json()

    contracts_path = '/templates/{0}/externalEpgs/{1}/contractRelationships'.format(template, external_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.get('type'),
            contractRef=dict(
                contractName=contract.get('name'),
                templateName=contract.get('template'),
                schemaId=contract.get('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 'contractRef' in mso.previous:
        mso.previous['contractRef'] = mso.dict_from_ref(mso.previous.get('contractRef'))

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

    mso.exit_json()
Esempio n. 3
0
def main():
    argument_spec = mso_argument_spec()
    argument_spec.update(
        schema=dict(type='str', required=True),
        site=dict(type='str', required=True),
        template=dict(type='str', required=True),
        vrf=dict(type='str', required=True),
        region=dict(type='str', required=True),
        hub_network=dict(type='dict', options=mso_hub_network_spec()),
        state=dict(type='str',
                   default='present',
                   choices=['absent', 'present', 'query']),
    )

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

    schema = module.params.get('schema')
    site = module.params.get('site')
    template = module.params.get('template').replace(' ', '')
    vrf = module.params.get('vrf')
    region = module.params.get('region')
    hub_network = module.params.get('hub_network')
    state = module.params.get('state')

    mso = MSOModule(module)

    # Get schema objects
    schema_id, schema_path, schema_obj = mso.query_schema(schema)

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

    # Get site
    site_id = mso.lookup_site(site)

    # Get site_idx
    if 'sites' not in schema_obj:
        mso.fail_json(
            msg=
            "No site associated with template '{0}'. Associate the site with the template using mso_schema_site."
            .format(template))
    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 association '{0}-{1}' does not exist.".
            format(site, template))

    # 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']]
    vrfs_name = [mso.dict_from_ref(v).get('vrfName') for v in vrfs]
    if vrf_ref not in vrfs:
        mso.fail_json(
            msg="Provided vrf '{0}' does not exist. Existing vrfs: {1}".format(
                vrf, ', '.join(vrfs_name)))
    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 Region object
    region_obj = schema_obj.get(
        'sites')[site_idx]['vrfs'][vrf_idx]['regions'][region_idx]
    region_path = '/sites/{0}/vrfs/{1}/regions/{2}'.format(
        site_template, vrf, region)

    # Get hub network
    existing_hub_network = region_obj.get('cloudRsCtxProfileToGatewayRouterP')
    if existing_hub_network is not None:
        mso.existing = existing_hub_network

    if state == 'query':
        if not mso.existing:
            mso.fail_json(msg="Hub network not found")
        mso.exit_json()

    ops = []

    mso.previous = mso.existing
    if state == 'absent':
        if mso.existing:
            mso.sent = mso.existing = {}
            ops.append(
                dict(op='remove',
                     path=region_path + '/cloudRsCtxProfileToGatewayRouterP'))
            ops.append(
                dict(op='replace',
                     path=region_path + '/isTGWAttachment',
                     value=False))

    elif state == 'present':
        new_hub_network = dict(
            name=hub_network.get('name'),
            tenantName=hub_network.get('tenant'),
        )
        payload = region_obj
        payload.update(
            cloudRsCtxProfileToGatewayRouterP=new_hub_network,
            isTGWAttachment=True,
        )

        mso.sanitize(payload, collate=True)

        ops.append(dict(op='replace', path=region_path, value=mso.sent))

        mso.existing = new_hub_network

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

    mso.exit_json()
Esempio n. 4
0
def main():
    argument_spec = mso_argument_spec()
    argument_spec.update(
        schema=dict(type='str', required=True),
        template=dict(type='str', required=True),
        external_epg=dict(type='str', aliases=['name', 'externalepg']),  # This parameter is not required for querying all objects
        description=dict(type='str'),
        display_name=dict(type='str'),
        vrf=dict(type='dict', options=mso_reference_spec()),
        l3out=dict(type='dict', options=mso_reference_spec()),
        anp=dict(type='dict', options=mso_reference_spec()),
        preferred_group=dict(type='bool'),
        type=dict(type='str', default='on-premise', choices=['on-premise', 'cloud']),
        state=dict(type='str', default='present', choices=['absent', 'present', 'query']),
    )

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

    schema = module.params.get('schema')
    template = module.params.get('template').replace(' ', '')
    external_epg = module.params.get('external_epg')
    description = module.params.get('description')
    display_name = module.params.get('display_name')
    vrf = module.params.get('vrf')
    if vrf is not None and vrf.get('template') is not None:
        vrf['template'] = vrf.get('template').replace(' ', '')
    l3out = module.params.get('l3out')
    if l3out is not None and l3out.get('template') is not None:
        l3out['template'] = l3out.get('template').replace(' ', '')
    anp = module.params.get('anp')
    if anp is not None and anp.get('template') is not None:
        anp['template'] = anp.get('template').replace(' ', '')
    preferred_group = module.params.get('preferred_group')
    type_ext_epg = module.params.get('type')
    state = module.params.get('state')

    mso = MSOModule(module)

    # Get schema objects
    schema_id, schema_path, schema_obj = mso.query_schema(schema)

    # Get template
    templates = [t.get('name') for t in schema_obj.get('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
    external_epgs = [e.get('name') for e in schema_obj.get('templates')[template_idx]['externalEpgs']]

    if external_epg is not None and external_epg in external_epgs:
        external_epg_idx = external_epgs.index(external_epg)
        mso.existing = schema_obj.get('templates')[template_idx]['externalEpgs'][external_epg_idx]
        if 'externalEpgRef' in mso.existing:
            del mso.existing['externalEpgRef']
        if 'vrfRef' in mso.existing:
            mso.existing['vrfRef'] = mso.dict_from_ref(mso.existing.get('vrfRef'))
        if 'l3outRef' in mso.existing:
            mso.existing['l3outRef'] = mso.dict_from_ref(mso.existing.get('l3outRef'))
        if 'anpRef' in mso.existing:
            mso.existing['anpRef'] = mso.dict_from_ref(mso.existing.get('anpRef'))

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

    eepgs_path = '/templates/{0}/externalEpgs'.format(template)
    eepg_path = '/templates/{0}/externalEpgs/{1}'.format(template, external_epg)
    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)
        l3out_ref = mso.make_reference(l3out, 'l3out', schema_id, template)
        anp_ref = mso.make_reference(anp, 'anp', schema_id, template)
        if display_name is None and not mso.existing:
            display_name = external_epg

        payload = dict(
            name=external_epg,
            displayName=display_name,
            vrfRef=vrf_ref,
            preferredGroup=preferred_group,
        )

        if description is not None:
            payload.update(description=description)

        if type_ext_epg == 'cloud':
            payload['extEpgType'] = 'cloud'
            payload['anpRef'] = anp_ref
        else:
            payload['l3outRef'] = l3out_ref

        mso.sanitize(payload, collate=True)

        if mso.existing:
            # clean contractRef to fix api issue
            for contract in mso.sent.get('contractRelationships'):
                contract['contractRef'] = mso.dict_from_ref(contract.get('contractRef'))
            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()
Esempio n. 5
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=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.get('schema')
    template = module.params.get('template').replace(' ', '')
    vrf = module.params.get('vrf')
    contract = module.params.get('contract')
    if contract is not None and contract.get('template') is not None:
        contract['template'] = contract.get('template').replace(' ', '')
    state = module.params.get('state')

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

    # 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.get('name') for t in schema_obj.get('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 VRF
    vrfs = [
        e.get('name')
        for e in schema_obj.get('templates')[template_idx]['vrfs']
    ]
    if vrf not in vrfs:
        mso.fail_json(
            msg="Provided vrf '{vrf}' does not exist. Existing vrfs: {vrfs}".
            format(vrf=vrf, vrfs=', '.join(vrfs)))
    vrf_idx = vrfs.index(vrf)
    vrf_obj = schema_obj.get('templates')[template_idx]['vrfs'][vrf_idx]

    if not vrf_obj.get('vzAnyEnabled'):
        mso.fail_json(
            msg="vzAny attribute on vrf '{0}' is disabled.".format(vrf))

    # Get Contract
    if contract:
        provider_contracts = [
            c.get('contractRef') for c in schema_obj.get('templates')
            [template_idx]['vrfs'][vrf_idx]['vzAnyProviderContracts']
        ]
        consumer_contracts = [
            c.get('contractRef') for c in schema_obj.get('templates')
            [template_idx]['vrfs'][vrf_idx]['vzAnyConsumerContracts']
        ]
        contract_ref = mso.contract_ref(**contract)
        if contract_ref in provider_contracts and contract.get(
                'type') == 'provider':
            contract_idx = provider_contracts.index(contract_ref)
            contract_path = '/templates/{0}/vrfs/{1}/vzAnyProviderContracts/{2}'.format(
                template, vrf, contract_idx)
            mso.existing = schema_obj.get('templates')[template_idx]['vrfs'][
                vrf_idx]['vzAnyProviderContracts'][contract_idx]
        if contract_ref in consumer_contracts and contract.get(
                'type') == 'consumer':
            contract_idx = consumer_contracts.index(contract_ref)
            contract_path = '/templates/{0}/vrfs/{1}/vzAnyConsumerContracts/{2}'.format(
                template, vrf, contract_idx)
            mso.existing = schema_obj.get('templates')[template_idx]['vrfs'][
                vrf_idx]['vzAnyConsumerContracts'][contract_idx]
        if mso.existing.get('contractRef'):
            mso.existing['contractRef'] = mso.dict_from_ref(
                mso.existing.get('contractRef'))
            mso.existing['relationshipType'] = contract.get('type')

    if state == 'query':
        if not contract:
            provider_contracts = [
                dict(contractRef=mso.dict_from_ref(c.get('contractRef')),
                     relationshipType='provider')
                for c in schema_obj.get('templates')[template_idx]['vrfs']
                [vrf_idx]['vzAnyProviderContracts']
            ]
            consumer_contracts = [
                dict(contractRef=mso.dict_from_ref(c.get('contractRef')),
                     relationshipType='consumer')
                for c in schema_obj.get('templates')[template_idx]['vrfs']
                [vrf_idx]['vzAnyConsumerContracts']
            ]
            mso.existing = provider_contracts + consumer_contracts
        elif not mso.existing:
            mso.fail_json(
                msg="Contract '{0}' not found".format(contract.get('name')))

        mso.exit_json()

    if contract.get('type') == 'provider':
        contracts_path = '/templates/{0}/vrfs/{1}/vzAnyProviderContracts/-'.format(
            template, vrf)
    if contract.get('type') == 'consumer':
        contracts_path = '/templates/{0}/vrfs/{1}/vzAnyConsumerContracts/-'.format(
            template, vrf)
    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(contractRef=dict(
            contractName=contract.get('name'),
            templateName=contract.get('template'),
            schemaId=contract.get('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
        mso.existing['relationshipType'] = contract.get('type')

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

    mso.exit_json()
Esempio n. 6
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()),
        vrf=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_multicast_source=dict(type='bool'),
        proxy_arp=dict(type='bool'),
        subnets=dict(type='list', elements='dict', options=mso_subnet_spec()),
        state=dict(type='str',
                   default='present',
                   choices=['absent', 'present', 'query']),
        preferred_group=dict(type='bool'),
    )

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

    schema = module.params.get('schema')
    template = module.params.get('template').replace(' ', '')
    anp = module.params.get('anp')
    epg = module.params.get('epg')
    display_name = module.params.get('display_name')
    bd = module.params.get('bd')
    if bd is not None and bd.get('template') is not None:
        bd['template'] = bd.get('template').replace(' ', '')
    vrf = module.params.get('vrf')
    if vrf is not None and vrf.get('template') is not None:
        vrf['template'] = vrf.get('template').replace(' ', '')
    useg_epg = module.params.get('useg_epg')
    intra_epg_isolation = module.params.get('intra_epg_isolation')
    intersite_multicast_source = module.params.get(
        'intersite_multicast_source')
    proxy_arp = module.params.get('proxy_arp')
    subnets = module.params.get('subnets')
    state = module.params.get('state')
    preferred_group = module.params.get('preferred_group')

    mso = MSOModule(module)

    # Get schema_id
    schema_obj = mso.get_obj('schemas', displayName=schema)
    if schema_obj:
        schema_id = schema_obj.get('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.get('name') for t in schema_obj.get('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.get('name')
        for a in schema_obj.get('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.get('name') for e in schema_obj.get('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.get(
            'templates')[template_idx]['anps'][anp_idx]['epgs'][epg_idx]

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

        if 'bdRef' in mso.existing:
            mso.existing['bdRef'] = mso.dict_from_ref(mso.existing['bdRef'])
        if 'vrfRef' in mso.existing:
            mso.existing['vrfRef'] = mso.dict_from_ref(mso.existing['vrfRef'])
        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)
        vrf_ref = mso.make_reference(vrf, 'vrf', schema_id, template)
        mso.stdout = str(subnets)
        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,
            mCastSource=intersite_multicast_source,
            proxyArp=proxy_arp,
            # FIXME: Missing functionality
            # uSegAttrs=[],
            subnets=subnets,
            bdRef=bd_ref,
            preferredGroup=preferred_group,
            vrfRef=vrf_ref,
        )

        mso.sanitize(payload, collate=True)

        if mso.existing:
            # Clean contractRef to fix api issue
            for contract in mso.sent.get('contractRelationships'):
                contract['contractRef'] = mso.dict_from_ref(
                    contract.get('contractRef'))
            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 'epgRef' in mso.previous:
        del mso.previous['epgRef']
    if 'bdRef' in mso.previous and mso.previous['bdRef'] != '':
        mso.previous['bdRef'] = mso.dict_from_ref(mso.previous['bdRef'])
    if 'vrfRef' in mso.previous and mso.previous['bdRef'] != '':
        mso.previous['vrfRef'] = mso.dict_from_ref(mso.previous['vrfRef'])

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

    mso.exit_json()
Esempio n. 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
        description=dict(type='str'),
        bd=dict(type='dict', options=mso_reference_spec()),
        vrf=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_multicast_source=dict(type='bool'),
        proxy_arp=dict(type='bool'),
        subnets=dict(type='list', elements='dict', options=mso_epg_subnet_spec()),
        qos_level=dict(type='str'),
        epg_type=dict(type='str', choices=['application', 'service']),
        deployment_type=dict(type='str', choices=['cloud_native', 'cloud_native_managed', 'third_party']),
        service_type=dict(type='str'),
        access_type=dict(type='str', choices=['private', 'public', 'public_and_private']),
        state=dict(type='str', default='present', choices=['absent', 'present', 'query']),
        preferred_group=dict(type='bool'),
    )

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

    schema = module.params.get('schema')
    template = module.params.get('template').replace(' ', '')
    anp = module.params.get('anp')
    epg = module.params.get('epg')
    description = module.params.get('description')
    display_name = module.params.get('display_name')
    bd = module.params.get('bd')
    if bd is not None and bd.get('template') is not None:
        bd['template'] = bd.get('template').replace(' ', '')
    vrf = module.params.get('vrf')
    if vrf is not None and vrf.get('template') is not None:
        vrf['template'] = vrf.get('template').replace(' ', '')
    useg_epg = module.params.get('useg_epg')
    intra_epg_isolation = module.params.get('intra_epg_isolation')
    intersite_multicast_source = module.params.get('intersite_multicast_source')
    proxy_arp = module.params.get('proxy_arp')
    subnets = module.params.get('subnets')
    qos_level = module.params.get('qos_level')
    epg_type = module.params.get('epg_type')
    deployment_type = module.params.get('deployment_type')
    service_type = module.params.get('service_type')
    access_type = module.params.get('access_type')
    state = module.params.get('state')
    preferred_group = module.params.get('preferred_group')

    mso = MSOModule(module)

    # Get schema objects
    schema_id, schema_path, schema_obj = mso.query_schema(schema)

    # Get template
    templates = [t.get('name') for t in schema_obj.get('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.get('name') for a in schema_obj.get('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.get('name') for e in schema_obj.get('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.get('templates')[template_idx]['anps'][anp_idx]['epgs'][epg_idx]

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

        if 'bdRef' in mso.existing:
            mso.existing['bdRef'] = mso.dict_from_ref(mso.existing['bdRef'])
        if 'vrfRef' in mso.existing:
            mso.existing['vrfRef'] = mso.dict_from_ref(mso.existing['vrfRef'])
        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)
    service_path = '{0}/cloudServiceEpgConfig'.format(epg_path)
    ops = []
    cloud_service_epg_config = {}

    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)
        vrf_ref = mso.make_reference(vrf, 'vrf', schema_id, template)
        subnets = mso.make_subnets(subnets, is_bd_subnet=False)

        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,
            mCastSource=intersite_multicast_source,
            proxyArp=proxy_arp,
            # FIXME: Missing functionality
            # uSegAttrs=[],
            subnets=subnets,
            bdRef=bd_ref,
            preferredGroup=preferred_group,
            vrfRef=vrf_ref,
        )
        if description is not None:
            payload.update(description=description)
        if qos_level is not None:
            payload.update(prio=qos_level)
        if epg_type is not None:
            payload.update(epgType=epg_type)

        mso.sanitize(payload, collate=True)

        if mso.existing:
            # Clean contractRef to fix api issue
            for contract in mso.sent.get('contractRelationships'):
                contract['contractRef'] = mso.dict_from_ref(contract.get('contractRef'))
            ops.append(dict(op='replace', path=epg_path, value=mso.sent))
        else:
            ops.append(dict(op='add', path=epgs_path + '/-', value=mso.sent))

        if epg_type == 'service':
            access_type_map = {
                'private': 'Private',
                'public': 'Public',
                'public_and_private': 'PublicAndPrivate',
            }
            deployment_type_map = {
                'cloud_native': 'CloudNative',
                'cloud_native_managed': 'CloudNativeManaged',
                'third_party': 'Third-party',
            }
            if cloud_service_epg_config != {}:
                cloud_service_epg_config.update(dict(
                    deploymentType=deployment_type_map[deployment_type],
                    serviceType=service_type,
                    accessType=access_type_map[access_type]))
                ops.append(dict(op='replace', path=service_path, value=cloud_service_epg_config))
            else:
                cloud_service_epg_config.update(dict(
                    deploymentType=deployment_type_map[deployment_type],
                    serviceType=service_type,
                    accessType=access_type_map[access_type]))
                ops.append(dict(op='add', path=service_path, value=cloud_service_epg_config))

    mso.existing = mso.proposed

    if 'epgRef' in mso.previous:
        del mso.previous['epgRef']
    if 'bdRef' in mso.previous and mso.previous['bdRef'] != '':
        mso.previous['bdRef'] = mso.dict_from_ref(mso.previous['bdRef'])
    if 'vrfRef' in mso.previous and mso.previous['bdRef'] != '':
        mso.previous['vrfRef'] = mso.dict_from_ref(mso.previous['vrfRef'])

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

    mso.exit_json()
Esempio n. 8
0
def main():
    argument_spec = mso_argument_spec()
    argument_spec.update(
        schema=dict(type='str', required=True),
        site=dict(type='str', required=True),
        template=dict(type='str', required=True),
        bd=dict(type='str', aliases=[
            'name'
        ]),  # This parameter is not required for querying all objects
        host_route=dict(type='bool'),
        svi_mac=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', ['bd']],
            ['state', 'present', ['bd']],
        ],
    )

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

    mso = MSOModule(module)

    # Get schema objects
    schema_id, schema_path, schema_obj = mso.query_schema(schema)

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

    # Get site
    site_id = mso.lookup_site(site)

    # Get site_idx
    if 'sites' not in schema_obj:
        mso.fail_json(
            msg=
            "No site associated with template '{0}'. Associate the site with the template using mso_schema_site."
            .format(template))
    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 association '{0}-{1}' does not exist.".
            format(site, template))

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

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

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

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

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

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

        payload = dict(
            bdRef=dict(
                schemaId=schema_id,
                templateName=template,
                bdName=bd,
            ),
            hostBasedRouting=host_route,
        )
        if svi_mac is not None:
            payload.update(mac=svi_mac)

        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 and mso.existing != mso.previous:
        mso.request(schema_path, method='PATCH', data=ops)

    mso.exit_json()
Esempio n. 9
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', aliases=['name']),  # This parameter is not required for querying all objects
        vpn_gateway_router=dict(type='bool'),
        container_overlay=dict(type='bool'),
        underlay_context_profile=dict(type='dict', options=dict(
            vrf=dict(type='str', required=True),
            region=dict(type='str', required=True),
        )),
        state=dict(type='str', default='present', choices=['absent', 'present', 'query']),
    )

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

    schema = module.params.get('schema')
    site = module.params.get('site')
    template = module.params.get('template').replace(' ', '')
    vrf = module.params.get('vrf')
    region = module.params.get('region')
    vpn_gateway_router = module.params.get('vpn_gateway_router')
    container_overlay = module.params.get('container_overlay')
    underlay_context_profile = module.params.get('underlay_context_profile')
    state = module.params.get('state')

    mso = MSOModule(module)

    # Get schema objects
    schema_id, schema_path, schema_obj = mso.query_schema(schema)

    # Get site
    site_id = mso.lookup_site(site)

    # Get site_idx
    if 'sites' not in schema_obj:
        mso.fail_json(msg="No site associated with template '{0}'. Associate the site with the template using mso_schema_site.".format(template))
    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 association '{0}-{1}' does not exist.".format(site, template))

    # 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']]
    vrfs_name = [mso.dict_from_ref(v).get('vrfName') for v in vrfs]
    if vrf_ref not in vrfs:
        mso.fail_json(msg="Provided vrf '{0}' does not exist. Existing vrfs: {1}".format(vrf, ', '.join(vrfs_name)))
    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 is not None and region in regions:
        region_idx = regions.index(region)
        region_path = '/sites/{0}/vrfs/{1}/regions/{2}'.format(site_template, vrf, region)
        mso.existing = schema_obj.get('sites')[site_idx]['vrfs'][vrf_idx]['regions'][region_idx]

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

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

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

    elif state == 'present':

        payload = dict(
            name=region,
            isVpnGatewayRouter=vpn_gateway_router,
        )

        if container_overlay:
            payload['contextProfileType'] = 'container-overlay'
            if mso.existing:
                underlay_dict = dict(
                    vrfRef=dict(
                        schemaId=schema_id,
                        templateName=template,
                        vrfName=underlay_context_profile['vrf']
                    ),
                    regionName=underlay_context_profile['region']
                )
                payload['underlayCtxProfile'] = underlay_dict

        mso.sanitize(payload, collate=True)
        if mso.existing:
            ops.append(dict(op='replace', path=region_path, value=mso.sent))
        else:
            ops.append(dict(op='add', path=regions_path + '/-', value=mso.sent))

        mso.existing = mso.proposed

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

    mso.exit_json()
Esempio n. 10
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', aliases=[
            'name'
        ]),  # This parameter is not required for querying all objects
        display_name=dict(type='str'),
        layer3_multicast=dict(type='bool'),
        vzany=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.get('schema')
    template = module.params.get('template').replace(' ', '')
    vrf = module.params.get('vrf')
    display_name = module.params.get('display_name')
    layer3_multicast = module.params.get('layer3_multicast')
    vzany = module.params.get('vzany')
    state = module.params.get('state')

    mso = MSOModule(module)

    # Get schema
    schema_id, schema_path, schema_obj = mso.query_schema(schema)

    # Get template
    templates = [t.get('name') for t in schema_obj.get('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.get('name')
        for v in schema_obj.get('templates')[template_idx]['vrfs']
    ]

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

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

    vrfs_path = '/templates/{0}/vrfs'.format(template)
    vrf_path = '/templates/{0}/vrfs/{1}'.format(template, vrf)
    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':
        if display_name is None and not mso.existing:
            display_name = vrf

        payload = dict(name=vrf,
                       displayName=display_name,
                       l3MCast=layer3_multicast,
                       vzAnyEnabled=vzany)

        mso.sanitize(payload, collate=True)

        if mso.existing:
            # clean contractRef to fix api issue
            for contract in mso.sent.get('vzAnyConsumerContracts'):
                contract['contractRef'] = mso.dict_from_ref(
                    contract.get('contractRef'))
            for contract in mso.sent.get('vzAnyProviderContracts'):
                contract['contractRef'] = mso.dict_from_ref(
                    contract.get('contractRef'))
            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()
Esempio n. 11
0
def main():
    argument_spec = mso_argument_spec()
    argument_spec.update(
        schema=dict(type='str', required=True),
        site=dict(type='str', required=True),
        template=dict(type='str', required=True),
        vrf=dict(type='dict', options=mso_reference_spec()),
        l3out=dict(type='str', aliases=[
            'name'
        ]),  # This parameter is not required for querying all objects
        state=dict(type='str',
                   default='present',
                   choices=['absent', 'present', 'query']),
    )

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

    schema = module.params.get('schema')
    site = module.params.get('site')
    template = module.params.get('template').replace(' ', '')
    l3out = module.params.get('l3out')
    vrf = module.params.get('vrf')
    state = module.params.get('state')

    mso = MSOModule(module)

    # Get schema objects
    schema_id, schema_path, schema_obj = mso.query_schema(schema)

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

    # Get site
    site_id = mso.lookup_site(site)

    # Get site_idx
    if 'sites' not in schema_obj:
        mso.fail_json(
            msg=
            "No site associated with template '{0}'. Associate the site with the template using mso_schema_site."
            .format(template))
    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 template '{0}' is not associated to site".
                      format(template))

    # 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 l3out
    l3out_ref = mso.l3out_ref(schema_id=schema_id,
                              template=template,
                              l3out=l3out)
    l3outs = [
        v.get('l3outRef')
        for v in schema_obj.get('sites')[site_idx]['intersiteL3outs']
    ]

    if l3out is not None and l3out_ref in l3outs:
        l3out_idx = l3outs.index(l3out_ref)
        l3out_path = '/sites/{0}/intersiteL3outs/{1}'.format(
            site_template, l3out)
        mso.existing = schema_obj.get(
            'sites')[site_idx]['intersiteL3outs'][l3out_idx]

    if state == 'query':
        if l3out is None:
            mso.existing = schema_obj.get('sites')[site_idx]['intersiteL3outs']
            for l3out in mso.existing:
                l3out['l3outRef'] = mso.dict_from_ref(l3out.get('l3outRef'))
        elif not mso.existing:
            mso.fail_json(msg="L3Out '{l3out}' not found".format(l3out=l3out))
        mso.exit_json()

    l3outs_path = '/sites/{0}/intersiteL3outs'.format(site_template)
    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)

        payload = dict(
            l3outRef=dict(
                schemaId=schema_id,
                templateName=template,
                l3outName=l3out,
            ),
            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()