def main():
    argument_spec = mso_argument_spec()
    argument_spec.update(
        tenant=dict(type='str', aliases=['name'], required=True),
        site=dict(type='str', aliases=['name']),
        cloud_account=dict(type='str'),
        security_domains=dict(type='list', elements='str', default=[]),
        aws_trusted=dict(type='bool'),
        azure_access_type=dict(type='str', default='shared', choices=['managed', 'unmanaged', 'shared']),
        azure_active_directory_id=dict(type='str'),
        aws_access_key=dict(type='str'),
        aws_account_org=dict(type='bool', default='false'),
        azure_active_directory_name=dict(type='str'),
        azure_subscription_id=dict(type='str'),
        azure_application_id=dict(type='str'),
        azure_credential_name=dict(type='str'),
        secret_key=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', ['tenant', 'site']],
            ['state', 'present', ['tenant', 'site']],
        ],
    )

    state = module.params.get('state')
    security_domains = module.params.get('security_domains')
    cloud_account = module.params.get('cloud_account')
    azure_access_type = module.params.get('azure_access_type')
    azure_credential_name = module.params.get('azure_credential_name')
    azure_application_id = module.params.get('azure_application_id')
    azure_active_directory_id = module.params.get('azure_active_directory_id')
    azure_active_directory_name = module.params.get('azure_active_directory_name')
    azure_subscription_id = module.params.get('azure_subscription_id')
    secret_key = module.params.get('secret_key')
    aws_account_org = module.params.get('aws_account_org')
    aws_access_key = module.params.get('aws_access_key')
    aws_trusted = module.params.get('aws_trusted')

    mso = MSOModule(module)

    # Get tenant_id and site_id
    tenant_id = mso.lookup_tenant(module.params.get('tenant'))
    site_id = mso.lookup_site(module.params.get('site'))
    tenants = [(t.get('id')) for t in mso.query_objs('tenants')]
    tenant_idx = tenants.index((tenant_id))

    # set tenent and port paths
    tenant_path = 'tenants/{0}'.format(tenant_id)
    ops = []
    ports_path = '/siteAssociations/-'
    port_path = '/siteAssociations/{0}'.format(site_id)

    payload = dict(
        siteId=site_id,
        securityDomains=security_domains,
        cloudAccount=cloud_account,
    )

    if cloud_account:
        if 'azure' in cloud_account:
            azure_account = dict(
                accessType=azure_access_type,
                securityDomains=security_domains,
                vendor='azure',
            )

            payload['azureAccount'] = [azure_account]

            cloudSubscription = dict(
                cloudSubscriptionId=azure_subscription_id,
                cloudApplicationId=azure_application_id,
            )

            payload['azureAccount'][0]['cloudSubscription'] = cloudSubscription

            if azure_access_type == 'shared':
                payload['azureAccount'] = []

            if azure_access_type == 'managed':
                if not azure_subscription_id:
                    mso.fail_json(msg="azure_susbscription_id is required when in managed mode.")
                if not azure_application_id:
                    mso.fail_json(msg="azure_application_id is required when in managed mode.")
                payload['azureAccount'][0]['cloudApplication'] = []
                payload['azureAccount'][0]['cloudActiveDirectory'] = []

            if azure_access_type == 'unmanaged':
                if not azure_subscription_id:
                    mso.fail_json(msg="azure_subscription_id is required when in unmanaged mode.")
                if not azure_application_id:
                    mso.fail_json(msg="azure_application_id is required when in unmanaged mode.")
                if not secret_key:
                    mso.fail_json(msg="secret_key is required when in unmanaged mode.")
                if not azure_active_directory_id:
                    mso.fail_json(msg="azure_active_directory_id is required when in unmanaged mode.")
                if not azure_active_directory_name:
                    mso.fail_json(msg="azure_active_directory_name is required when in unmanaged mode.")
                if not azure_credential_name:
                    mso.fail_json(msg="azure_credential_name is required when in unmanaged mode.")
                azure_account.update(
                    accessType='credentials',
                )
                cloudApplication = dict(
                    cloudApplicationId=azure_application_id,
                    cloudCredentialName=azure_credential_name,
                    secretKey=secret_key,
                    cloudActiveDirectoryId=azure_active_directory_id
                )
                cloudActiveDirectory = dict(
                    cloudActiveDirectoryId=azure_active_directory_id,
                    cloudActiveDirectoryName=azure_active_directory_name
                )
                payload['azureAccount'][0]['cloudApplication'] = [cloudApplication]
                payload['azureAccount'][0]['cloudActiveDirectory'] = [cloudActiveDirectory]

        else:
            aws_account = dict(
                accountId=cloud_account,
                isTrusted=aws_trusted,
                accessKeyId=aws_access_key,
                secretKey=secret_key,
                isAccountInOrg=aws_account_org,
            )

            if not aws_trusted:
                if not aws_access_key:
                    mso.fail_json(msg="aws_access_key is a required field in untrusted mode.")
                if not secret_key:
                    mso.fail_json(msg="secret_key is a required field in untrusted mode.")
            payload['awsAccount'] = [aws_account]

    sites = [(s.get('siteId')) for s in mso.query_objs('tenants')[tenant_idx]['siteAssociations']]

    if site_id in sites:
        site_idx = sites.index((site_id))
        mso.existing = mso.query_objs('tenants')[tenant_idx]['siteAssociations'][site_idx]

    if state == 'query':
        if len(sites) == 0:
            mso.fail_json(msg="No site associated with tenant Id {0}".format(tenant_id))
        elif site_id not in sites and site_id is not None:
            mso.fail_json(msg="Site Id {0} not associated with tenant Id {1}".format(site_id, tenant_id))
        elif site_id is None:
            mso.existing = mso.query_objs('tenants')[tenant_idx]['siteAssociations']
        mso.exit_json()

    mso.previous = mso.existing

    if state == 'absent':
        if mso.existing:
            mso.sent = mso.existing = {}
            ops.append(dict(op='remove', path=port_path))
    if state == 'present':
        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 and mso.proposed != mso.previous:
        mso.request(tenant_path, method='PATCH', data=ops)

    mso.exit_json()
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['tenant']
    schema = module.params['schema']
    template = module.params['template']
    display_name = module.params['display_name']
    state = module.params['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['name'] for t in schema_obj['templates']]
        if template:
            if template in templates:
                template_idx = templates.index(template)
                mso.existing = schema_obj['templates'][template_idx]
        else:
            mso.existing = schema_obj['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['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()
Beispiel #3
0
def main():
    argument_spec = mso_argument_spec()
    argument_spec.update(
        dhcp_relay_policy=dict(type="str", required=True, aliases=['name']),
        ip=dict(type="str"),
        tenant=dict(type="str"),
        schema=dict(type="str"),
        template=dict(type="str"),
        application_profile=dict(type="str", aliases=['anp']),
        endpoint_group=dict(type="str", aliases=['epg']),
        external_endpoint_group=dict(type="str",
                                     aliases=['ext_epg', 'external_epg']),
        state=dict(type="str",
                   default="present",
                   choices=["absent", "present", "query"]),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
        required_if=[
            ["state", "present", ["ip", "tenant", "schema", "template"]],
            ["state", "absent", ["tenant", "schema", "template"]],
        ],
    )

    dhcp_relay_policy = module.params.get("dhcp_relay_policy")
    ip = module.params.get("ip")
    tenant = module.params.get("tenant")
    schema = module.params.get("schema")
    template = module.params.get("template")
    if template is not None:
        template = template.replace(' ', '')
    application_profile = module.params.get("application_profile")
    endpoint_group = module.params.get("endpoint_group")
    external_endpoint_group = module.params.get("external_endpoint_group")
    state = module.params.get("state")

    mso = MSOModule(module)

    path = "policies/dhcp/relay"

    tenant_id = mso.lookup_tenant(tenant)
    # Get schema_id
    schema_id = mso.lookup_schema(schema)

    provider = dict(
        addr=ip,
        externalEpgRef='',
        epgRef='',
        l3Ref='',
        tenantId=tenant_id,
    )
    provider_index = None
    previous_provider = {}

    if application_profile is not None and endpoint_group is not None:
        provider[
            'epgRef'] = '/schemas/{schemaId}/templates/{templateName}/anps/{app}/epgs/{epg}'.format(
                schemaId=schema_id,
                templateName=template,
                app=application_profile,
                epg=endpoint_group,
            )
    elif external_endpoint_group is not None:
        provider[
            'externalEpgRef'] = '/schemas/{schemaId}/templates/{templateName}/externalEpgs/{ext_epg}'.format(
                schemaId=schema_id,
                templateName=template,
                ext_epg=external_endpoint_group)

    # Query for existing object(s)
    dhcp_relay_obj = mso.get_obj(path,
                                 name=dhcp_relay_policy,
                                 key="DhcpRelayPolicies")
    if 'id' not in dhcp_relay_obj:
        mso.fail_json(
            msg="DHCP Relay Policy '{0}' is not a valid DHCP Relay Policy name."
            .format(dhcp_relay_policy))
    policy_id = dhcp_relay_obj.get("id")
    providers = []
    if "provider" in dhcp_relay_obj:
        providers = dhcp_relay_obj.get('provider')
        for index, prov in enumerate(providers):
            if ((provider.get('epgRef') != ''
                 and prov.get('epgRef') == provider.get('epgRef'))
                    or (provider.get('externalEpgRef') != ''
                        and prov.get('externalEpgRef')
                        == provider.get('externalEpgRef'))):
                previous_provider = prov
                provider_index = index

    # If we found an existing object, continue with it
    path = '{0}/{1}'.format(path, policy_id)

    if state == "query":
        mso.existing = providers
        if endpoint_group is not None or external_endpoint_group is not None:
            mso.existing = previous_provider
        mso.exit_json()

    if endpoint_group is None and external_endpoint_group is None:
        mso.fail_json(
            msg=
            "Missing either endpoint_group or external_endpoint_group required attribute."
        )

    mso.previous = previous_provider
    if state == "absent":
        provider = {}
        if previous_provider:
            if provider_index is not None:
                providers.pop(provider_index)

    elif state == "present":
        if provider_index is not None:
            providers[provider_index] = provider
        else:
            providers.append(provider)

    if module.check_mode:
        mso.existing = provider
    else:
        mso.existing = dhcp_relay_obj
        dhcp_relay_obj["provider"] = providers
        mso.sanitize(dhcp_relay_obj, collate=True)
        new_dhcp_relay_obj = mso.request(path, method="PUT", data=mso.sent)
        mso.existing = {}
        for index, prov in enumerate(new_dhcp_relay_obj.get('provider')):
            if ((provider.get('epgRef') != ''
                 and prov.get('epgRef') == provider.get('epgRef'))
                    or (provider.get('externalEpgRef') != ''
                        and prov.get('externalEpgRef')
                        == provider.get('externalEpgRef'))):
                mso.existing = prov

    mso.exit_json()
Beispiel #4
0
def main():
    argument_spec = mso_argument_spec()
    argument_spec.update(
        dhcp_option_policy=dict(type="str", aliases=['name']),
        description=dict(type="str"),
        tenant=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', ['dhcp_option_policy']],
            ['state', 'present', ['dhcp_option_policy', 'tenant']],
        ],
    )

    dhcp_option_policy = module.params.get("dhcp_option_policy")
    description = module.params.get("description")
    tenant = module.params.get("tenant")
    state = module.params.get("state")

    mso = MSOModule(module)

    path = "policies/dhcp/option"

    # Query for existing object(s)
    if dhcp_option_policy:
        mso.existing = mso.get_obj(path,
                                   name=dhcp_option_policy,
                                   key="DhcpRelayPolicies")
        if mso.existing:
            policy_id = mso.existing.get("id")
            # If we found an existing object, continue with it
            path = '{0}/{1}'.format(path, policy_id)
    else:
        mso.existing = mso.query_objs(path, key="DhcpRelayPolicies")

    mso.previous = mso.existing

    if state == "absent":
        if mso.existing:
            if module.check_mode:
                mso.existing = {}
            else:
                mso.existing = mso.request(path,
                                           method="DELETE",
                                           data=mso.sent)

    elif state == "present":
        tenant_id = mso.lookup_tenant(tenant)
        payload = dict(
            name=dhcp_option_policy,
            desc=description,
            policyType="dhcp",
            policySubtype="option",
            tenantId=tenant_id,
        )
        mso.sanitize(payload, collate=True)

        if mso.existing:
            if mso.check_changed():
                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()
Beispiel #5
0
def main():
    argument_spec = mso_argument_spec()
    argument_spec.update(
        source_schema=dict(type='str'),
        destination_schema=dict(type='str'),
        destination_tenant=dict(type='str'),
        source_template_name=dict(type='str'),
        destination_template_name=dict(type='str'),
        destination_template_display_name=dict(type='str'),
        state=dict(type='str', default='clone', choices=['clone']),
    )

    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
        required_if=[
            ['state', 'clone', ['destination_schema', 'destination_tenant']],
        ],
    )

    source_schema = module.params.get('source_schema')
    destination_schema = module.params.get('destination_schema')
    destination_tenant = module.params.get('destination_tenant')
    source_template_name = module.params.get('source_template_name')
    destination_template_name = module.params.get('destination_template_name')
    destination_template_display_name = module.params.get(
        'destination_template_display_name')
    state = module.params.get('state')

    mso = MSOModule(module)

    destination_schema_id = None

    # Get source schema id and destination schema id
    schema_summary = mso.query_objs('schemas/list-identity', key='schemas')

    for schema in schema_summary:
        if schema.get('displayName') == source_schema:
            source_schema_id = schema.get('id')
        if schema.get('displayName') == destination_schema:
            destination_schema_id = schema.get('id')
            destination_schema = None
            break
    if destination_schema_id is None:
        mso.fail_json(msg="Schema with the name '{0}' does not exist.".format(
            destination_schema))

    # Get destination tenant id
    destination_tenant_id = mso.lookup_tenant(destination_tenant)

    path = 'schemas/cloneTemplates'

    if state == 'clone':
        if destination_template_display_name is None:
            destination_template_display_name = destination_template_name

        payload = dict(
            destTenantId=destination_tenant_id,
            destSchemaId=destination_schema_id,
            destSchemaName=destination_schema,
            templatesToBeCloned=[
                dict(
                    schemaId=source_schema_id,
                    templateName=source_template_name,
                    destTemplateName=destination_template_name,
                    destTempDisplayName=destination_template_display_name,
                )
            ],
        )

        mso.sanitize(payload, collate=True)

        mso.previous = {}

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

    mso.exit_json()