Ejemplo n.º 1
0
def main():
    argument_spec = intersight_argument_spec
    argument_spec.update(
        claim_code=dict(type='str'),
        device_id=dict(type='str', required=True),
        state=dict(type='str',
                   choices=['absent', 'present'],
                   default='present'),
    )

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

    intersight = IntersightModule(module)
    intersight.result['api_response'] = {}
    intersight.result['trace_id'] = ''

    # Check if device already exists in target list
    target_ids = module.params['device_id'].split('&')
    target_filter = ''
    for idx, target_id in enumerate(target_ids):
        if idx == 0:
            target_filter += f"contains(TargetId,'{target_id}')"
        else:
            target_filter += f" or contains(TargetId,'{target_id}')"
    intersight.get_resource(
        resource_path='/asset/Targets',
        query_params={
            "$select": "TargetId,RegisteredDevice",
            "$filter": target_filter,
            "$expand": "RegisteredDevice($select=DeviceClaim)"
        },
        return_list=False,
    )

    if module.params['state'] == 'present':
        # Send claim request if device id not already claimed
        if not intersight.result['api_response']:
            intersight.configure_resource(
                moid=None,
                resource_path='/asset/DeviceClaims',
                body=dict(SecurityToken=module.params['claim_code'],
                          SerialNumber=module.params['device_id']),
                query_params=None,
                update_method='post')

    elif module.params['state'] == 'absent':
        # Check if target exists
        if intersight.result['api_response'].get('Moid'):
            intersight.delete_resource(
                moid=intersight.result['api_response'].get(
                    'RegisteredDevice').get('DeviceClaim').get('Moid'),
                resource_path='/asset/DeviceClaims',
            )

    module.exit_json(**intersight.result)
Ejemplo n.º 2
0
def main():
    argument_spec = intersight_argument_spec
    argument_spec.update(
        resource_path=dict(type='str', required=True),
        query_params=dict(type='dict', default={}),
        update_method=dict(type='str',
                           choices=['patch', 'post'],
                           default='patch'),
        api_body=dict(type='dict', default={}),
        return_list=dict(type='bool', default=False),
        state=dict(type='str',
                   choices=['absent', 'present'],
                   default='present'),
    )

    module = AnsibleModule(
        argument_spec,
        supports_check_mode=True,
        mutually_exclusive=[
            ['return_list', 'api_body'],
            ['return_list', 'state'],
        ],
    )

    intersight = IntersightModule(module)
    intersight.result['api_response'] = {}
    intersight.result['trace_id'] = ''

    # get the current state of the resource
    get_resource(intersight)

    # determine requested operation (config, delete, or neither (get resource only))
    if module.params['state'] == 'present':
        request_delete = False
        # api_body implies resource configuration through post/patch
        request_config = bool(module.params['api_body'])
    else:  # state == 'absent'
        request_delete = True
        request_config = False

    moid = None
    resource_values_match = False
    if (request_config or
            request_delete) and intersight.result['api_response'].get('Moid'):
        # resource exists and moid was returned
        moid = intersight.result['api_response']['Moid']
        if request_config:
            resource_values_match = compare_values(
                module.params['api_body'], intersight.result['api_response'])
        else:  # request_delete
            delete_resource(intersight, moid)

    if request_config and not resource_values_match:
        configure_resource(intersight, moid)

    module.exit_json(**intersight.result)
Ejemplo n.º 3
0
def main():
    argument_spec = intersight_argument_spec
    argument_spec.update(server_names=dict(type='list', required=True), )

    module = AnsibleModule(
        argument_spec,
        supports_check_mode=True,
    )

    intersight = IntersightModule(module)

    # one API call returning all requested servers
    module.exit_json(intersight_servers=get_servers(module, intersight))
def main():
    argument_spec = intersight_argument_spec
    argument_spec.update(server_names=dict(type='list', required=True), )

    module = AnsibleModule(
        argument_spec,
        supports_check_mode=True,
    )
    if module._name == 'intersight_facts':
        module.deprecate(
            "The 'intersight_facts' module has been renamed to 'intersight_info'",
            version='2.13')

    intersight = IntersightModule(module)

    # one API call returning all requested servers
    module.exit_json(intersight_servers=get_servers(module, intersight))
Ejemplo n.º 5
0
def main():
    argument_spec = intersight_argument_spec
    argument_spec.update(
        state=dict(type='str', choices=['present', 'absent'], default='present'),
        organization=dict(type='str', default='default'),
        name=dict(type='str', required=True),
        description=dict(type='str', aliases=['descr'], default=''),
        tags=dict(type='list', default=[]),
        enable=dict(type='bool', default=True),
        ntp_servers=dict(type='list', default=[]),
        timezone=dict(type='str', default=''),
    )

    module = AnsibleModule(
        argument_spec,
        supports_check_mode=True,
    )

    intersight = IntersightModule(module)
    intersight.result['api_response'] = {}
    intersight.result['trace_id'] = ''
    #
    # Argument spec above, resource path, and API body should be the only code changed in each policy module
    #
    # Resource path used to configure policy
    resource_path = '/ntp/Policies'
    # Define API body used in compares or create
    intersight.api_body = {
        'Organization': {
            'Name': intersight.module.params['organization'],
        },
        'Name': intersight.module.params['name'],
        'Tags': intersight.module.params['tags'],
        'Description': intersight.module.params['description'],
        'Enabled': intersight.module.params['enable'],
        'NtpServers': intersight.module.params['ntp_servers'],
        'Timezone': intersight.module.params['timezone'],
    }

    #
    # Code below should be common across all policy modules
    #
    intersight.configure_policy_or_profile(resource_path=resource_path)

    module.exit_json(**intersight.result)
def main():
    argument_spec = intersight_argument_spec
    argument_spec.update(
        state=dict(type='str', choices=['present', 'absent'], default='present'),
        organization=dict(type='str', default='default'),
        name=dict(type='str', required=True),
        target_platform=dict(type='str', choices=['Standalone', 'FIAttached'], default='Standalone'),
        tags=dict(type='list', default=[]),
        description=dict(type='str', aliases=['descr'], default=''),
        assigned_server=dict(type='str', default=''),
        imc_access_policy=dict(type='str'),
        local_user_policy=dict(type='str'),
        ntp_policy=dict(type='str'),
        storage_policy=dict(type='str'),
        virtual_media_policy=dict(type='str'),
        boot_order_policy=dict(type='str'),
    )

    module = AnsibleModule(
        argument_spec,
        supports_check_mode=True,
    )

    intersight = IntersightModule(module)
    intersight.result['api_response'] = {}
    intersight.result['trace_id'] = ''

    organization_moid = None
    # GET Organization Moid
    intersight.get_resource(
        resource_path='/organization/Organizations',
        query_params={
            '$filter': "Name eq '" + intersight.module.params['organization'] + "'",
            '$select': 'Moid',
        },
    )
    if intersight.result['api_response'].get('Moid'):
        # resource exists and moid was returned
        organization_moid = intersight.result['api_response']['Moid']

    # get assigned server information
    intersight.result['api_response'] = {}
    intersight.get_resource(
        resource_path='/compute/PhysicalSummaries',
        query_params={
            '$filter': "Moid eq '" + intersight.module.params['assigned_server'] + "'",
        }
    )
    source_object_type = None
    if intersight.result['api_response'].get('SourceObjectType'):
        source_object_type = intersight.result['api_response']['SourceObjectType']

    # get the current state of the resource
    intersight.result['api_response'] = {}
    filter_str = "Name eq '" + intersight.module.params['name'] + "'"
    filter_str += "and Organization.Moid eq '" + organization_moid + "'"
    intersight.get_resource(
        resource_path='/server/Profiles',
        query_params={
            '$filter': filter_str,
            '$expand': 'Organization',
        }
    )

    # create api_body for comparison with actual state
    intersight.api_body = {
        'Organization': {
            'Name': intersight.module.params['organization'],
        },
        'Name': intersight.module.params['name'],
        'Tags': intersight.module.params['tags'],
        'Description': intersight.module.params['description'],
        'AssignedServer': {
            'Moid': intersight.module.params['assigned_server'],
            'ObjectType': source_object_type,
        },
    }
    if intersight.module.params['target_platform'] == 'FIAttached':
        intersight.api_body['TargetPlatform'] = intersight.module.params['target_platform']

    moid = None
    resource_values_match = False
    if intersight.result['api_response'].get('Moid'):
        # resource exists and moid was returned
        moid = intersight.result['api_response']['Moid']
        if module.params['state'] == 'present':
            resource_values_match = compare_values(intersight.api_body, intersight.result['api_response'])
        else:  # state == 'absent'
            intersight.delete_resource(
                moid=moid,
                resource_path='/server/Profiles',
            )
            moid = None

    if module.params['state'] == 'present' and not resource_values_match:
        # remove read-only Organization key
        intersight.api_body.pop('Organization')
        if not moid:
            # Organization must be set, but can't be changed after initial POST
            intersight.api_body['Organization'] = {
                'Moid': organization_moid,
            }
        intersight.configure_resource(
            moid=moid,
            resource_path='/server/Profiles',
            body=intersight.api_body,
            query_params={
                '$filter': filter_str
            }
        )
        if intersight.result['api_response'].get('Moid'):
            # resource exists and moid was returned
            moid = intersight.result['api_response']['Moid']

    if moid and intersight.module.params['imc_access_policy']:
        post_profile_to_policy(intersight, moid, resource_path='/access/Policies', policy_name=intersight.module.params['imc_access_policy'])

    if moid and intersight.module.params['local_user_policy']:
        post_profile_to_policy(intersight, moid, resource_path='/iam/EndPointUserPolicies', policy_name=intersight.module.params['local_user_policy'])

    if moid and intersight.module.params['storage_policy']:
        post_profile_to_policy(intersight, moid, resource_path='/storage/StoragePolicies', policy_name=intersight.module.params['storage_policy'])

    if moid and intersight.module.params['ntp_policy']:
        post_profile_to_policy(intersight, moid, resource_path='/ntp/Policies', policy_name=intersight.module.params['ntp_policy'])

    if moid and intersight.module.params['virtual_media_policy']:
        post_profile_to_policy(intersight, moid, resource_path='/vmedia/Policies', policy_name=intersight.module.params['virtual_media_policy'])

    if moid and intersight.module.params['boot_order_policy']:
        post_profile_to_policy(intersight, moid, resource_path='/boot/PrecisionPolicies', policy_name=intersight.module.params['boot_order_policy'])
    module.exit_json(**intersight.result)
def main():
    boot_device = dict(
        enabled=dict(type='bool', default=True),
        device_type=dict(
            type='str',
            choices=[
                'iscsi', 'local_cdd', 'local_disk', 'nvme', 'pch_storage',
                'pxe', 'san', 'sd_card', 'uefi_shell', 'usb', 'virtual_media'
            ],
            required=True,
        ),
        device_name=dict(type='str', required=True),
        # iscsi and pxe options
        network_slot=dict(type='str', default=''),
        port=dict(type='int', default=0),
        # local disk options
        controller_slot=dict(type='str', default=''),
        # bootloader options
        bootloader_name=dict(type='str', default=''),
        bootloader_description=dict(type='str', default=''),
        bootloader_path=dict(type='str', default=''),
        #pxe only options
        ip_type=dict(type='str',
                     choices=['None', 'IPv4', 'IPv6'],
                     default='None'),
        interface_source=dict(type='str',
                              choices=['name', 'mac', 'port'],
                              default='name'),
        interface_name=dict(type='str', default=''),
        mac_address=dict(type='str', defualt=''),
        #sd card options
        sd_card_subtype=dict(
            type='str',
            choices=['None', 'flex-util', 'flex-flash', 'SDCARD'],
            default='None',
        ),
        #lun for pch, san, sd_card
        lun=dict(type='int', default=0),
        #usb options
        usb_subtype=dict(
            type='str',
            choices=['None', 'usb-cd', 'usb-fdd', 'usb-hdd'],
            default='None',
        ),
        # virtual media options
        virtual_media_subtype=dict(
            type='str',
            choices=[
                'None', 'cimc-mapped-dvd', 'cimc-mapped-hdd', 'kvm-mapped-dvd',
                'kvm-mapped-hdd', 'kvm-mapped-fdd'
            ],
            default='None',
        ),
    )
    argument_spec = intersight_argument_spec
    argument_spec.update(
        state=dict(type='str',
                   choices=['present', 'absent'],
                   default='present'),
        organization=dict(type='str', default='default'),
        name=dict(type='str', required=True),
        description=dict(type='str', aliases=['descr'], default=''),
        tags=dict(type='list', default=[]),
        configured_boot_mode=dict(type='str',
                                  choices=['Legacy', 'Uefi'],
                                  default='Legacy'),
        uefi_enable_secure_boot=dict(type='bool', default=False),
        boot_devices=dict(type='list', elements='dict', options=boot_device),
    )

    module = AnsibleModule(
        argument_spec,
        supports_check_mode=True,
    )

    intersight = IntersightModule(module)
    intersight.result['api_response'] = {}
    intersight.result['trace_id'] = ''
    #
    # Argument spec above, resource path, and API body should be the only code changed in each policy module
    #
    # Resource path used to configure policy
    resource_path = '/boot/PrecisionPolicies'
    # Defined API body used in compares or create
    intersight.api_body = {
        'Organization': {
            'Name': intersight.module.params['organization'],
        },
        'Name':
        intersight.module.params['name'],
        'Tags':
        intersight.module.params['tags'],
        'Description':
        intersight.module.params['description'],
        'ConfiguredBootMode':
        intersight.module.params['configured_boot_mode'],
        "EnforceUefiSecureBoot":
        intersight.module.params['uefi_enable_secure_boot'],
        'BootDevices': [],
    }
    if intersight.module.params.get('boot_devices'):
        for device in intersight.module.params['boot_devices']:
            if device['device_type'] == 'iscsi':
                intersight.api_body['BootDevices'].append({
                    "ClassId":
                    "boot.Iscsi",
                    "ObjectType":
                    "boot.Iscsi",
                    "Enabled":
                    device['enabled'],
                    "Name":
                    device['device_name'],
                    "Slot":
                    device['network_slot'],
                    "Port":
                    device['port'],
                })
            elif device['device_type'] == 'local_cdd':
                intersight.api_body['BootDevices'].append({
                    "ClassId":
                    "boot.LocalCDD",
                    "ObjectType":
                    "boot.LocalCDD",
                    "Enabled":
                    device['enabled'],
                    "Name":
                    device['device_name'],
                })
            elif device['device_type'] == 'local_disk':
                intersight.api_body['BootDevices'].append({
                    "ClassId":
                    "boot.LocalDisk",
                    "ObjectType":
                    "boot.LocalDisk",
                    "Enabled":
                    device['enabled'],
                    "Name":
                    device['device_name'],
                    "Slot":
                    device['controller_slot'],
                    "Bootloader": {
                        "ClassId": "boot.Bootloader",
                        "ObjectType": "boot.Bootloader",
                        "Description": device['bootloader_description'],
                        "Name": device['bootloader_name'],
                        "Path": device['bootloader_path'],
                    },
                })
            elif device['device_type'] == 'nvme':
                intersight.api_body['BootDevices'].append({
                    "ClassId":
                    "boot.NVMe",
                    "ObjectType":
                    "boot.NVMe",
                    "Enabled":
                    device['enabled'],
                    "Name":
                    device['device_name'],
                    "Bootloader": {
                        "ClassId": "boot.Bootloader",
                        "ObjectType": "boot.Bootloader",
                        "Description": device['bootloader_description'],
                        "Name": device['bootloader_name'],
                        "Path": device['bootloader_path'],
                    },
                })
            elif device['device_type'] == 'pch_storage':
                intersight.api_body['BootDevices'].append({
                    "ClassId":
                    "boot.PchStorage",
                    "ObjectType":
                    "boot.PchStorage",
                    "Enabled":
                    device['enabled'],
                    "Name":
                    device['device_name'],
                    "Bootloader": {
                        "ClassId": "boot.Bootloader",
                        "ObjectType": "boot.Bootloader",
                        "Description": device['bootloader_description'],
                        "Name": device['bootloader_name'],
                        "Path": device['bootloader_path'],
                    },
                    "Lun":
                    device['lun'],
                })
            elif device['device_type'] == 'pxe':
                intersight.api_body['BootDevices'].append({
                    "ClassId":
                    "boot.Pxe",
                    "ObjectType":
                    "boot.Pxe",
                    "Enabled":
                    device['enabled'],
                    "Name":
                    device['device_name'],
                    "IpType":
                    device['ip_type'],
                    "InterfaceSource":
                    device['interface_source'],
                    "Slot":
                    device['network_slot'],
                    "InterfaceName":
                    device['interface_name'],
                    "Port":
                    device['port'],
                    "MacAddress":
                    device['mac_address'],
                })
            elif device['device_type'] == 'san':
                intersight.api_body['BootDevices'].append({
                    "ClassId":
                    "boot.San",
                    "ObjectType":
                    "boot.San",
                    "Enabled":
                    device['enabled'],
                    "Name":
                    device['device_name'],
                    "Lun":
                    device['lun'],
                    "Slot":
                    device['network_slot'],
                    "Bootloader": {
                        "ClassId": "boot.Bootloader",
                        "ObjectType": "boot.Bootloader",
                        "Description": device['bootloader_description'],
                        "Name": device['bootloader_name'],
                        "Path": device['bootloader_path'],
                    },
                })
            elif device['device_type'] == 'sd_card':
                intersight.api_body['BootDevices'].append({
                    "ClassId":
                    "boot.SdCard",
                    "ObjectType":
                    "boot.SdCard",
                    "Enabled":
                    device['enabled'],
                    "Name":
                    device['device_name'],
                    "Lun":
                    device['lun'],
                    "SubType":
                    device['sd_card_subtype'],
                    "Bootloader": {
                        "ClassId": "boot.Bootloader",
                        "ObjectType": "boot.Bootloader",
                        "Description": device['bootloader_description'],
                        "Name": device['bootloader_name'],
                        "Path": device['bootloader_path'],
                    },
                })
            elif device['device_type'] == 'uefi_shell':
                intersight.api_body['BootDevices'].append({
                    "ClassId":
                    "boot.UefiShell",
                    "ObjectType":
                    "boot.UefiShell",
                    "Enabled":
                    device['enabled'],
                    "Name":
                    device['device_name'],
                })
            elif device['device_type'] == 'usb':
                intersight.api_body['BootDevices'].append({
                    "ClassId":
                    "boot.Usb",
                    "ObjectType":
                    "boot.Usb",
                    "Enabled":
                    device['enabled'],
                    "Name":
                    device['device_name'],
                    "SubType":
                    device['usb_subtype'],
                })
            elif device['device_type'] == 'virtual_media':
                intersight.api_body['BootDevices'].append({
                    "ClassId":
                    "boot.VirtualMedia",
                    "ObjectType":
                    "boot.VirtualMedia",
                    "Enabled":
                    device['enabled'],
                    "Name":
                    device['device_name'],
                    "SubType":
                    device['virtual_media_subtype'],
                })
    #
    # Code below should be common across all policy modules
    #
    # intersight.configure_policy(...)
    organization_moid = None
    # GET Organization Moid
    intersight.get_resource(
        resource_path='/organization/Organizations',
        query_params={
            '$filter':
            "Name eq '" + intersight.module.params['organization'] + "'",
            '$select': 'Moid',
        },
    )
    if intersight.result['api_response'].get('Moid'):
        # resource exists and moid was returned
        organization_moid = intersight.result['api_response']['Moid']

    intersight.result['api_response'] = {}
    # get the current state of the resource
    filter_str = "Name eq '" + intersight.module.params['name'] + "'"
    filter_str += "and Organization.Moid eq '" + organization_moid + "'"
    intersight.get_resource(
        resource_path=resource_path,
        query_params={
            '$filter': filter_str,
            '$expand': 'Organization',
        },
    )

    moid = None
    resource_values_match = False
    if intersight.result['api_response'].get('Moid'):
        # resource exists and moid was returned
        moid = intersight.result['api_response']['Moid']
        if module.params['state'] == 'present':
            resource_values_match = compare_values(
                intersight.api_body, intersight.result['api_response'])
        else:  # state == 'absent'
            intersight.delete_resource(
                moid=moid,
                resource_path=resource_path,
            )
            moid = None

    if module.params['state'] == 'present' and not resource_values_match:
        # remove read-only Organization key
        intersight.api_body.pop('Organization')
        if not moid:
            # Organization must be set, but can't be changed after initial POST
            intersight.api_body['Organization'] = {
                'Moid': organization_moid,
            }
        intersight.configure_resource(
            moid=moid,
            resource_path=resource_path,
            body=intersight.api_body,
            query_params={
                '$filter': filter_str,
            },
        )

    module.exit_json(**intersight.result)
Ejemplo n.º 8
0
def main():
    path = '/vmedia/Policies'
    virtual_media_mapping = dict(
        enable=dict(type='bool', default=True),
        mount_type=dict(type='str',
                        choices=['nfs', 'cifs', 'http', 'https'],
                        required=True),
        volume=dict(type='str', required=True),
        remote_hostname=dict(type='str', required=True),
        remote_path=dict(type='str', required=True),
        remote_file=dict(type='str', required=True),
        mount_options=dict(type='str', default=''),
        username=dict(type='str', default=''),
        password=dict(type='str', default='', no_log=True),
        authentication_protocol=dict(type='str', default='none'),
    )
    argument_spec = intersight_argument_spec
    argument_spec.update(
        state=dict(type='str',
                   choices=['present', 'absent'],
                   default='present'),
        organization=dict(type='str', default='default'),
        name=dict(type='str', required=True),
        description=dict(type='str', aliases=['descr'], default=''),
        tags=dict(type='list', default=[]),
        enable=dict(type='bool', default=True),
        encryption=dict(type='bool', default=False),
        low_power_usb=dict(type='bool', default=True),
        cdd_virtual_media=dict(type='dict', options=virtual_media_mapping),
        hdd_virtual_media=dict(type='dict', options=virtual_media_mapping),
    )

    module = AnsibleModule(
        argument_spec,
        supports_check_mode=True,
    )

    intersight = IntersightModule(module)
    intersight.result['api_response'] = {}
    intersight.result['trace_id'] = ''
    # Defined API body used in compares or create
    intersight.api_body = {
        'Organization': {
            'Name': intersight.module.params['organization'],
        },
        'Name': intersight.module.params['name'],
        'Tags': intersight.module.params['tags'],
        'Description': intersight.module.params['description'],
        'Enabled': intersight.module.params['enable'],
        "Encryption": intersight.module.params['encryption'],
        "LowPowerUsb": intersight.module.params['low_power_usb'],
        'Mappings': [],
    }

    if intersight.module.params.get('cdd_virtual_media'):
        intersight.api_body['Mappings'].append({
            "ClassId":
            "vmedia.Mapping",
            "ObjectType":
            "vmedia.Mapping",
            "AuthenticationProtocol":
            intersight.module.params['cdd_virtual_media']
            ['authentication_protocol'],
            "DeviceType":
            "cdd",
            "HostName":
            intersight.module.params['cdd_virtual_media']['remote_hostname'],
            "Password":
            intersight.module.params['cdd_virtual_media']['password'],
            "IsPasswordSet":
            intersight.module.params['cdd_virtual_media']['password'] != '',
            "MountOptions":
            intersight.module.params['cdd_virtual_media']['mount_options'],
            "MountProtocol":
            intersight.module.params['cdd_virtual_media']['mount_type'],
            "RemoteFile":
            intersight.module.params['cdd_virtual_media']['remote_file'],
            "RemotePath":
            intersight.module.params['cdd_virtual_media']['remote_path'],
            "Username":
            intersight.module.params['cdd_virtual_media']['username'],
            "VolumeName":
            intersight.module.params['cdd_virtual_media']['volume'],
        })
    if intersight.module.params.get('hdd_virtual_media'):
        intersight.api_body['Mappings'].append({
            "ClassId":
            "vmedia.Mapping",
            "ObjectType":
            "vmedia.Mapping",
            "AuthenticationProtocol":
            intersight.module.params['hdd_virtual_media']
            ['authentication_protocol'],
            "DeviceType":
            "hdd",
            "HostName":
            intersight.module.params['hdd_virtual_media']['remote_hostname'],
            "Password":
            intersight.module.params['hdd_virtual_media']['password'],
            "IsPasswordSet":
            intersight.module.params['hdd_virtual_media']['password'] != '',
            "MountOptions":
            intersight.module.params['hdd_virtual_media']['mount_options'],
            "MountProtocol":
            intersight.module.params['hdd_virtual_media']['mount_type'],
            "RemoteFile":
            intersight.module.params['hdd_virtual_media']['remote_file'],
            "RemotePath":
            intersight.module.params['hdd_virtual_media']['remote_path'],
            "Username":
            intersight.module.params['hdd_virtual_media']['username'],
            "VolumeName":
            intersight.module.params['hdd_virtual_media']['volume'],
        })

    organization_moid = None
    # GET Organization Moid
    intersight.get_resource(
        resource_path='/organization/Organizations',
        query_params={
            '$filter':
            "Name eq '" + intersight.module.params['organization'] + "'",
            '$select': 'Moid',
        },
    )
    if intersight.result['api_response'].get('Moid'):
        # resource exists and moid was returned
        organization_moid = intersight.result['api_response']['Moid']

    intersight.result['api_response'] = {}
    # get the current state of the resource
    filter_str = "Name eq '" + intersight.module.params['name'] + "'"
    filter_str += "and Organization.Moid eq '" + organization_moid + "'"
    intersight.get_resource(
        resource_path=path,
        query_params={
            '$filter': filter_str,
            '$expand': 'Organization',
        },
    )

    moid = None
    resource_values_match = False
    if intersight.result['api_response'].get('Moid'):
        # resource exists and moid was returned
        moid = intersight.result['api_response']['Moid']
        if module.params['state'] == 'present':
            resource_values_match = compare_values(
                intersight.api_body, intersight.result['api_response'])
        else:  # state == 'absent'
            intersight.delete_resource(
                moid=moid,
                resource_path=path,
            )
            moid = None

    if module.params['state'] == 'present' and not resource_values_match:
        # remove read-only Organization key
        intersight.api_body.pop('Organization')
        if not moid:
            # Organization must be set, but can't be changed after initial POST
            intersight.api_body['Organization'] = {
                'Moid': organization_moid,
            }
        intersight.configure_resource(
            moid=moid,
            resource_path=path,
            body=intersight.api_body,
            query_params={
                '$filter': filter_str,
            },
        )

    module.exit_json(**intersight.result)
def main():
    argument_spec = intersight_argument_spec
    argument_spec.update(
        state=dict(type='str',
                   choices=['present', 'absent'],
                   default='present'),
        organization=dict(type='str', default='default'),
        name=dict(type='str', required=True),
        description=dict(type='str', aliases=['descr'], default=''),
        tags=dict(type='list', default=[]),
        enable=dict(type='bool', default=True),
        ntp_servers=dict(type='list', default=[]),
        timezone=dict(type='str', default=''),
    )

    module = AnsibleModule(
        argument_spec,
        supports_check_mode=True,
    )

    intersight = IntersightModule(module)
    intersight.result['api_response'] = {}
    intersight.result['trace_id'] = ''
    # Defined API body used in compares or create
    intersight.api_body = {
        'Organization': {
            'Name': intersight.module.params['organization'],
        },
        'Name': intersight.module.params['name'],
        'Tags': intersight.module.params['tags'],
        'Description': intersight.module.params['description'],
        'Enabled': intersight.module.params['enable'],
        'NtpServers': intersight.module.params['ntp_servers'],
        'Timezone': intersight.module.params['timezone'],
    }

    organization_moid = None
    # GET Organization Moid
    intersight.get_resource(
        resource_path='/organization/Organizations',
        query_params={
            '$filter':
            "Name eq '" + intersight.module.params['organization'] + "'",
            '$select': 'Moid',
        },
    )
    if intersight.result['api_response'].get('Moid'):
        # resource exists and moid was returned
        organization_moid = intersight.result['api_response']['Moid']

    intersight.result['api_response'] = {}
    # get the current state of the resource
    filter_str = "Name eq '" + intersight.module.params['name'] + "'"
    filter_str += "and Organization.Moid eq '" + organization_moid + "'"
    intersight.get_resource(
        resource_path='/ntp/Policies',
        query_params={
            '$filter': filter_str,
            '$expand': 'Organization',
        },
    )

    moid = None
    resource_values_match = False
    if intersight.result['api_response'].get('Moid'):
        # resource exists and moid was returned
        moid = intersight.result['api_response']['Moid']
        if module.params['state'] == 'present':
            resource_values_match = compare_values(
                intersight.api_body, intersight.result['api_response'])
        else:  # state == 'absent'
            intersight.delete_resource(
                moid=moid,
                resource_path='/ntp/Policies',
            )
            moid = None

    if module.params['state'] == 'present' and not resource_values_match:
        # remove read-only Organization key
        intersight.api_body.pop('Organization')
        if not moid:
            # Organization must be set, but can't be changed after initial POST
            intersight.api_body['Organization'] = {
                'Moid': organization_moid,
            }
        intersight.configure_resource(
            moid=moid,
            resource_path='/ntp/Policies',
            body=intersight.api_body,
            query_params={
                '$filter': filter_str,
            },
        )

    module.exit_json(**intersight.result)
def main():
    argument_spec = intersight_argument_spec
    argument_spec.update(
        state=dict(type='str',
                   choices=['present', 'absent'],
                   default='present'),
        organization=dict(type='str', default='default'),
        name=dict(type='str', required=True),
        target_platform=dict(type='str',
                             choices=['Standalone', 'FIAttached'],
                             default='Standalone'),
        tags=dict(type='list', default=[]),
        description=dict(type='str', aliases=['descr'], default=''),
        assigned_server=dict(type='str', default=''),
        boot_order_policy=dict(type='str'),
        imc_access_policy=dict(type='str'),
        lan_connectivity_policy=dict(type='str'),
        local_user_policy=dict(type='str'),
        ntp_policy=dict(type='str'),
        storage_policy=dict(type='str'),
        virtual_media_policy=dict(type='str'),
    )

    module = AnsibleModule(
        argument_spec,
        supports_check_mode=True,
    )

    intersight = IntersightModule(module)
    intersight.result['api_response'] = {}
    intersight.result['trace_id'] = ''
    #
    # Argument spec above, resource path, and API body should be the only code changed in this module
    #
    resource_path = '/server/Profiles'
    # Get assigned server information
    intersight.result['api_response'] = {}
    intersight.get_resource(
        resource_path='/compute/PhysicalSummaries',
        query_params={
            '$filter':
            "Moid eq '" + intersight.module.params['assigned_server'] + "'",
        })
    source_object_type = None
    if intersight.result['api_response'].get('SourceObjectType'):
        source_object_type = intersight.result['api_response'][
            'SourceObjectType']
    # Define API body used in compares or create
    intersight.api_body = {
        'Organization': {
            'Name': intersight.module.params['organization'],
        },
        'Name': intersight.module.params['name'],
        'Tags': intersight.module.params['tags'],
        'Description': intersight.module.params['description'],
        'AssignedServer': {
            'Moid': intersight.module.params['assigned_server'],
            'ObjectType': source_object_type,
        },
    }
    if intersight.module.params['target_platform'] == 'FIAttached':
        intersight.api_body['TargetPlatform'] = intersight.module.params[
            'target_platform']

    # Configure the profile
    moid = intersight.configure_policy_or_profile(resource_path=resource_path)

    if moid and intersight.module.params['boot_order_policy']:
        post_profile_to_policy(
            intersight,
            moid,
            resource_path='/boot/PrecisionPolicies',
            policy_name=intersight.module.params['boot_order_policy'])

    if moid and intersight.module.params['imc_access_policy']:
        post_profile_to_policy(
            intersight,
            moid,
            resource_path='/access/Policies',
            policy_name=intersight.module.params['imc_access_policy'])

    if moid and intersight.module.params['lan_connectivity_policy']:
        post_profile_to_policy(
            intersight,
            moid,
            resource_path='/vnic/LanConnectivityPolicies',
            policy_name=intersight.module.params['lan_connectivity_policy'])

    if moid and intersight.module.params['local_user_policy']:
        post_profile_to_policy(
            intersight,
            moid,
            resource_path='/iam/EndPointUserPolicies',
            policy_name=intersight.module.params['local_user_policy'])

    if moid and intersight.module.params['ntp_policy']:
        post_profile_to_policy(
            intersight,
            moid,
            resource_path='/ntp/Policies',
            policy_name=intersight.module.params['ntp_policy'])

    if moid and intersight.module.params['storage_policy']:
        post_profile_to_policy(
            intersight,
            moid,
            resource_path='/storage/StoragePolicies',
            policy_name=intersight.module.params['storage_policy'])

    if moid and intersight.module.params['virtual_media_policy']:
        post_profile_to_policy(
            intersight,
            moid,
            resource_path='/vmedia/Policies',
            policy_name=intersight.module.params['virtual_media_policy'])

    module.exit_json(**intersight.result)
def main():
    local_user = dict(
        username=dict(type='str', required=True),
        enable=dict(type='bool', default=True),
        role=dict(type='str',
                  choices=['admin', 'readonly', 'user'],
                  required=True),
        password=dict(type='str', required=True, no_log=True),
    )
    argument_spec = intersight_argument_spec
    argument_spec.update(
        state=dict(type='str',
                   choices=['present', 'absent'],
                   default='present'),
        organization=dict(type='str', default='default'),
        name=dict(type='str', required=True),
        description=dict(type='str', aliases=['descr'], default=''),
        tags=dict(type='list', default=[]),
        enforce_strong_password=dict(type='bool', default=True, no_log=False),
        enable_password_expiry=dict(type='bool', default=False, no_log=False),
        password_history=dict(type='int', default=5, no_log=False),
        local_users=dict(type='list',
                         elements='dict',
                         options=local_user,
                         default=[]),
        purge=dict(type='bool', default=False),
        always_update_password=dict(type='bool', default=False, no_log=False),
    )

    module = AnsibleModule(
        argument_spec,
        supports_check_mode=True,
    )

    intersight = IntersightModule(module)
    intersight.result['api_response'] = {}
    intersight.result['trace_id'] = ''

    # get the current state of the resource
    intersight.get_resource(
        resource_path='/iam/EndPointUserPolicies',
        query_params={
            '$filter':
            "Name eq '" + intersight.module.params['name'] + "'",
            '$expand':
            'EndPointUserRoles($expand=EndPointRole,EndPointUser),Organization',
        },
    )

    user_policy_moid = None
    resource_values_match = False
    if intersight.result['api_response'].get('Moid'):
        # resource exists and moid was returned
        user_policy_moid = intersight.result['api_response']['Moid']
        #
        # always_update_password
        #   false: compare expected vs. actual (won't check passwords)
        #   true: no compare
        #
        if module.params['state'] == 'present' and not module.params[
                'always_update_password']:
            # Create api body used to check current state
            end_point_user_roles = []
            for user in intersight.module.params['local_users']:
                end_point_user_roles.append({
                    'Enabled':
                    user['enable'],
                    'EndPointRole': [
                        {
                            'Name': user['role'],
                            'Type': 'IMC',
                        },
                    ],
                    'EndPointUser': {
                        'Name': user['username'],
                    },
                })
            intersight.api_body = {
                'Name': intersight.module.params['name'],
                'Tags': intersight.module.params['tags'],
                'Description': intersight.module.params['description'],
                'PasswordProperties': {
                    'EnforceStrongPassword':
                    intersight.module.params['enforce_strong_password'],
                    'EnablePasswordExpiry':
                    intersight.module.params['enable_password_expiry'],
                    'PasswordHistory':
                    intersight.module.params['password_history'],
                },
                'EndPointUserRoles': end_point_user_roles,
                'Organization': {
                    'Name': intersight.module.params['organization'],
                },
            }
            resource_values_match = compare_values(
                intersight.api_body, intersight.result['api_response'])
        elif module.params['state'] == 'absent':
            intersight.delete_resource(
                moid=user_policy_moid,
                resource_path='/iam/EndPointUserPolicies',
            )
            user_policy_moid = None

    if module.params['state'] == 'present' and not resource_values_match:
        intersight.api_body = {
            'Name': intersight.module.params['name'],
            'Tags': intersight.module.params['tags'],
            'Description': intersight.module.params['description'],
            'PasswordProperties': {
                'EnforceStrongPassword':
                intersight.module.params['enforce_strong_password'],
                'EnablePasswordExpiry':
                intersight.module.params['enable_password_expiry'],
                'PasswordHistory':
                intersight.module.params['password_history'],
            },
        }
        organization_moid = None
        if not user_policy_moid or module.params['purge']:
            # get Organization Moid which is needed when resources are created
            saved_response = intersight.result['api_response']
            intersight.get_resource(
                resource_path='/organization/Organizations',
                query_params={
                    '$filter':
                    "Name eq '" + intersight.module.params['organization'] +
                    "'",
                    '$select':
                    'Moid',
                },
            )
            if intersight.result['api_response'].get('Moid'):
                # resource exists and moid was returned
                organization_moid = intersight.result['api_response']['Moid']
            intersight.result['api_response'] = saved_response
            if not user_policy_moid:
                # Initial create: Organization must be set, but can't be changed after initial POST
                intersight.api_body['Organization'] = {
                    'Moid': organization_moid,
                }
            elif module.params['purge']:
                # update existing resource and purge any existing users
                for end_point_user_role in intersight.result['api_response'][
                        'EndPointUserRoles']:
                    intersight.delete_resource(
                        moid=end_point_user_role['Moid'],
                        resource_path='/iam/EndPointUserRoles',
                    )
        # configure the top-level policy resource
        intersight.result['api_response'] = {}
        intersight.configure_resource(
            moid=user_policy_moid,
            resource_path='/iam/EndPointUserPolicies',
            body=intersight.api_body,
            query_params={
                '$filter':
                "Name eq '" + intersight.module.params['name'] + "'",
            },
        )
        if intersight.result['api_response'].get('Moid'):
            # resource exists and moid was returned
            user_policy_moid = intersight.result['api_response']['Moid']

        # EndPointUser local_users list config
        for user in intersight.module.params['local_users']:
            intersight.api_body = {
                'Name': user['username'],
            }
            if organization_moid:
                intersight.api_body['Organization'] = {
                    'Moid': organization_moid,
                }
            intersight.configure_resource(
                moid=None,
                resource_path='/iam/EndPointUsers',
                body=intersight.api_body,
                query_params={
                    '$filter': "Name eq '" + user['username'] + "'",
                },
            )
            user_moid = None
            if intersight.result['api_response'].get('Moid'):
                # resource exists and moid was returned
                user_moid = intersight.result['api_response']['Moid']
            # GET EndPointRole Moid
            intersight.get_resource(
                resource_path='/iam/EndPointRoles',
                query_params={
                    '$filter':
                    "Name eq '" + user['role'] + "' and Type eq 'IMC'",
                },
            )
            end_point_role_moid = None
            if intersight.result['api_response'].get('Moid'):
                # resource exists and moid was returned
                end_point_role_moid = intersight.result['api_response']['Moid']
            # EndPointUserRole config
            intersight.api_body = {
                'EndPointUser': {
                    'Moid': user_moid,
                },
                'EndPointRole': [{
                    'Moid': end_point_role_moid,
                }],
                'Password': user['password'],
                'Enabled': user['enable'],
                'EndPointUserPolicy': {
                    'Moid': user_policy_moid,
                },
            }
            intersight.configure_resource(
                moid=None,
                resource_path='/iam/EndPointUserRoles',
                body=intersight.api_body,
                query_params={
                    '$filter':
                    "EndPointUserPolicy.Moid eq '" + user_policy_moid + "'",
                },
            )

    module.exit_json(**intersight.result)
def main():
    boot_device = dict(
        enabled=dict(type='bool', default=True),
        device_type=dict(
            type='str',
            choices=[
                'iSCSI',
                'Local CDD',
                'Local Disk',
                'NVMe',
                'PCH Storage',
                'PXE',
                'SAN',
                'SD Card',
                'UEFI Shell',
                'USB',
                'Virtual Media',
            ],
            required=True,
        ),
        device_name=dict(type='str', required=True),
        # iscsi and pxe options
        network_slot=dict(type='str', default=''),
        port=dict(type='int', default=0),
        # local disk options
        controller_slot=dict(type='str', default=''),
        # bootloader options
        bootloader_name=dict(type='str', default=''),
        bootloader_description=dict(type='str', default=''),
        bootloader_path=dict(type='str', default=''),
        # pxe only options
        ip_type=dict(type='str',
                     choices=['None', 'IPv4', 'IPv6'],
                     default='None'),
        interface_source=dict(type='str',
                              choices=['name', 'mac', 'port'],
                              default='name'),
        interface_name=dict(type='str', default=''),
        mac_address=dict(type='str', defualt=''),
        # sd card options
        sd_card_subtype=dict(
            type='str',
            choices=['None', 'flex-util', 'flex-flash', 'SDCARD'],
            default='None',
        ),
        # lun for pch, san, sd_card
        lun=dict(type='int', default=0),
        # usb options
        usb_subtype=dict(
            type='str',
            choices=['None', 'usb-cd', 'usb-fdd', 'usb-hdd'],
            default='None',
        ),
        # virtual media options
        virtual_media_subtype=dict(
            type='str',
            choices=[
                'None', 'cimc-mapped-dvd', 'cimc-mapped-hdd', 'kvm-mapped-dvd',
                'kvm-mapped-hdd', 'kvm-mapped-fdd'
            ],
            default='None',
        ),
    )
    argument_spec = intersight_argument_spec
    argument_spec.update(
        state=dict(type='str',
                   choices=['present', 'absent'],
                   default='present'),
        organization=dict(type='str', default='default'),
        name=dict(type='str', required=True),
        description=dict(type='str', aliases=['descr'], default=''),
        tags=dict(type='list', default=[]),
        configured_boot_mode=dict(type='str',
                                  choices=['Legacy', 'Uefi'],
                                  default='Legacy'),
        uefi_enable_secure_boot=dict(type='bool', default=False),
        boot_devices=dict(type='list', elements='dict', options=boot_device),
    )

    module = AnsibleModule(
        argument_spec,
        supports_check_mode=True,
    )

    intersight = IntersightModule(module)
    intersight.result['api_response'] = {}
    intersight.result['trace_id'] = ''
    #
    # Argument spec above, resource path, and API body should be the only code changed in each policy module
    #
    # Resource path used to configure policy
    resource_path = '/boot/PrecisionPolicies'
    # Define API body used in compares or create
    intersight.api_body = {
        'Organization': {
            'Name': intersight.module.params['organization'],
        },
        'Name':
        intersight.module.params['name'],
        'Tags':
        intersight.module.params['tags'],
        'Description':
        intersight.module.params['description'],
        'ConfiguredBootMode':
        intersight.module.params['configured_boot_mode'],
        "EnforceUefiSecureBoot":
        intersight.module.params['uefi_enable_secure_boot'],
        'BootDevices': [],
    }
    if intersight.module.params.get('boot_devices'):
        for device in intersight.module.params['boot_devices']:
            if device['device_type'] == 'iSCSI':
                intersight.api_body['BootDevices'].append({
                    "ClassId":
                    "boot.Iscsi",
                    "ObjectType":
                    "boot.Iscsi",
                    "Enabled":
                    device['enabled'],
                    "Name":
                    device['device_name'],
                    "Slot":
                    device['network_slot'],
                    "Port":
                    device['port'],
                })
            elif device['device_type'] == 'Local CDD':
                intersight.api_body['BootDevices'].append({
                    "ClassId":
                    "boot.LocalCDD",
                    "ObjectType":
                    "boot.LocalCDD",
                    "Enabled":
                    device['enabled'],
                    "Name":
                    device['device_name'],
                })
            elif device['device_type'] == 'Local Disk':
                intersight.api_body['BootDevices'].append({
                    "ClassId":
                    "boot.LocalDisk",
                    "ObjectType":
                    "boot.LocalDisk",
                    "Enabled":
                    device['enabled'],
                    "Name":
                    device['device_name'],
                    "Slot":
                    device['controller_slot'],
                    "Bootloader": {
                        "ClassId": "boot.Bootloader",
                        "ObjectType": "boot.Bootloader",
                        "Description": device['bootloader_description'],
                        "Name": device['bootloader_name'],
                        "Path": device['bootloader_path'],
                    },
                })
            elif device['device_type'] == 'NVMe':
                intersight.api_body['BootDevices'].append({
                    "ClassId":
                    "boot.NVMe",
                    "ObjectType":
                    "boot.NVMe",
                    "Enabled":
                    device['enabled'],
                    "Name":
                    device['device_name'],
                    "Bootloader": {
                        "ClassId": "boot.Bootloader",
                        "ObjectType": "boot.Bootloader",
                        "Description": device['bootloader_description'],
                        "Name": device['bootloader_name'],
                        "Path": device['bootloader_path'],
                    },
                })
            elif device['device_type'] == 'PCH Storage':
                intersight.api_body['BootDevices'].append({
                    "ClassId":
                    "boot.PchStorage",
                    "ObjectType":
                    "boot.PchStorage",
                    "Enabled":
                    device['enabled'],
                    "Name":
                    device['device_name'],
                    "Bootloader": {
                        "ClassId": "boot.Bootloader",
                        "ObjectType": "boot.Bootloader",
                        "Description": device['bootloader_description'],
                        "Name": device['bootloader_name'],
                        "Path": device['bootloader_path'],
                    },
                    "Lun":
                    device['lun'],
                })
            elif device['device_type'] == 'PXE':
                intersight.api_body['BootDevices'].append({
                    "ClassId":
                    "boot.Pxe",
                    "ObjectType":
                    "boot.Pxe",
                    "Enabled":
                    device['enabled'],
                    "Name":
                    device['device_name'],
                    "IpType":
                    device['ip_type'],
                    "InterfaceSource":
                    device['interface_source'],
                    "Slot":
                    device['network_slot'],
                    "InterfaceName":
                    device['interface_name'],
                    "Port":
                    device['port'],
                    "MacAddress":
                    device['mac_address'],
                })
            elif device['device_type'] == 'SAN':
                intersight.api_body['BootDevices'].append({
                    "ClassId":
                    "boot.San",
                    "ObjectType":
                    "boot.San",
                    "Enabled":
                    device['enabled'],
                    "Name":
                    device['device_name'],
                    "Lun":
                    device['lun'],
                    "Slot":
                    device['network_slot'],
                    "Bootloader": {
                        "ClassId": "boot.Bootloader",
                        "ObjectType": "boot.Bootloader",
                        "Description": device['bootloader_description'],
                        "Name": device['bootloader_name'],
                        "Path": device['bootloader_path'],
                    },
                })
            elif device['device_type'] == 'SD Card':
                intersight.api_body['BootDevices'].append({
                    "ClassId":
                    "boot.SdCard",
                    "ObjectType":
                    "boot.SdCard",
                    "Enabled":
                    device['enabled'],
                    "Name":
                    device['device_name'],
                    "Lun":
                    device['lun'],
                    "SubType":
                    device['sd_card_subtype'],
                    "Bootloader": {
                        "ClassId": "boot.Bootloader",
                        "ObjectType": "boot.Bootloader",
                        "Description": device['bootloader_description'],
                        "Name": device['bootloader_name'],
                        "Path": device['bootloader_path'],
                    },
                })
            elif device['device_type'] == 'UEFI Shell':
                intersight.api_body['BootDevices'].append({
                    "ClassId":
                    "boot.UefiShell",
                    "ObjectType":
                    "boot.UefiShell",
                    "Enabled":
                    device['enabled'],
                    "Name":
                    device['device_name'],
                })
            elif device['device_type'] == 'USB':
                intersight.api_body['BootDevices'].append({
                    "ClassId":
                    "boot.Usb",
                    "ObjectType":
                    "boot.Usb",
                    "Enabled":
                    device['enabled'],
                    "Name":
                    device['device_name'],
                    "SubType":
                    device['usb_subtype'],
                })
            elif device['device_type'] == 'Virtual Media':
                intersight.api_body['BootDevices'].append({
                    "ClassId":
                    "boot.VirtualMedia",
                    "ObjectType":
                    "boot.VirtualMedia",
                    "Enabled":
                    device['enabled'],
                    "Name":
                    device['device_name'],
                    "SubType":
                    device['virtual_media_subtype'],
                })
    #
    # Code below should be common across all policy modules
    #
    intersight.configure_policy_or_profile(resource_path=resource_path)

    module.exit_json(**intersight.result)