Exemple #1
0
def main():
    """
    Main function
    :returns: Server Anti-Affinity Group information
    """
    module = AnsibleModule(argument_spec=dict(
        auth=dict(type='dict'),
        region=dict(default='na', type='str'),
        datacenter=dict(required=True, type='str'),
        network_domain=dict(required=True, type='str'),
        servers=dict(required=True, type='list', elements='str'),
        state=dict(default='present',
                   required=False,
                   choices=['present', 'absent'])),
                           supports_check_mode=True)
    network_domain_name = module.params.get('network_domain')
    network_domain_id = aa_group = None
    server_ids = list()
    datacenter = module.params.get('datacenter')
    state = module.params.get('state')
    try:
        credentials = get_credentials(module)
    except ImportError as e:
        module.fail_json(msg='{0}'.format(e))

    # Check the region supplied is valid
    regions = get_regions()
    if module.params.get('region') not in regions:
        module.fail_json(
            msg='Invalid region. Regions must be one of {0}'.format(regions))

    if credentials is False:
        module.fail_json(msg='Could not load the user credentials')

    try:
        client = NTTMCPClient(credentials, module.params.get('region'))
    except NTTMCPAPIException as e:
        module.fail_json(msg=e.msg)

    # Get the CND
    try:
        network = client.get_network_domain_by_name(network_domain_name,
                                                    datacenter)
        network_domain_id = network.get('id')
    except (KeyError, IndexError, AttributeError, NTTMCPAPIException):
        module.fail_json(msg='Could not find the Cloud Network Domain: {0}'.
                         format(network_domain_name))

    # Get the servers
    for server in module.params.get('servers'):
        try:
            server = client.get_server_by_name(
                datacenter=datacenter,
                network_domain_id=network_domain_id,
                name=server)
            if server:
                server_ids.append(server.get('id'))
            else:
                module.fail_json(
                    msg='Could not find the server - {0} in {1}'.format(
                        server, datacenter))
        except (KeyError, IndexError, AttributeError):
            module.fail_json(
                msg='Could not find the server - {0} in {1}'.format(
                    server, datacenter))

    # Attempt to find any existing AntiAffinity Group for this server combination
    try:
        aa_group = client.get_anti_affinity_group_by_servers(
            server_ids[0], server_ids[1])
    except (KeyError, IndexError, AttributeError, NTTMCPAPIException) as e:
        module.fail_json(
            msg='Could not retrieve any Server Anti Affinity Groups - {0}'.
            format(e))

    try:
        if state == 'present':
            if aa_group:
                module.exit_json(
                    msg='The server anti-affinity group already exists',
                    data=aa_group)
            if module.check_mode:
                module.exit_json(
                    msg='A new server anti-affinity group will be created')
            client.create_anti_affinity_group(server_ids[0], server_ids[1])
            aa_group = client.get_anti_affinity_group_by_servers(
                server_ids[0], server_ids[1])
            module.exit_json(changed=True, data=aa_group)
        elif state == 'absent':
            if not aa_group:
                module.exit_json(
                    msg=
                    'No server anti-affinity group exists for this server combination'
                )
            if module.check_mode:
                module.exit_json(
                    msg='The server anti-affinity group {0} will be removed'.
                    format(aa_group.get('id')))
            client.delete_anti_affinity_group(aa_group.get('id'))
            module.exit_json(
                changed=True,
                msg='The Anti-Affinity Group {0} was successfully removed'.
                format(aa_group.get('id')))
    except (KeyError, IndexError, AttributeError, NTTMCPAPIException) as e:
        module.fail_json(msg='{0}'.format(e).replace('"', '\''))
def main():
    """
    Main function

    :returns: Server Information
    """
    module = AnsibleModule(argument_spec=dict(auth=dict(type='dict'),
                                              region=dict(default='na',
                                                          type='str'),
                                              datacenter=dict(required=True,
                                                              type='str'),
                                              network_domain=dict(
                                                  required=False, type='str'),
                                              vlan=dict(default=None,
                                                        required=False,
                                                        type='str'),
                                              name=dict(required=False,
                                                        type='str'),
                                              id=dict(required=False,
                                                      type='str')),
                           supports_check_mode=True)

    try:
        credentials = get_credentials(module)
    except ImportError as e:
        module.fail_json(msg='{0}'.format(e))
    return_data = return_object('server')
    name = module.params.get('name')
    server_id = module.params.get('id')
    datacenter = module.params.get('datacenter')
    network_domain_name = module.params.get('network_domain')
    vlan_name = module.params.get('vlan')
    network_domain_id = vlan_id = None

    # Check the region supplied is valid
    regions = get_regions()
    if module.params.get('region') not in regions:
        module.fail_json(
            msg='Invalid region. Regions must be one of {0}'.format(regions))

    if credentials is False:
        module.fail_json(msg='Could not load the user credentials')

    try:
        client = NTTMCPClient(credentials, module.params.get('region'))
    except NTTMCPAPIException as e:
        module.fail_json(msg=e.msg)

    # Get the CND object based on the supplied name
    try:
        if network_domain_name:
            network_domain = client.get_network_domain_by_name(
                name=network_domain_name, datacenter=datacenter)
            network_domain_id = network_domain.get('id')
        else:
            network_domain_id = None
        if network_domain_name and not network_domain:
            module.fail_json(
                msg='Failed to locate the Cloud Network Domain - {0}'.format(
                    network_domain_name))
    except (KeyError, IndexError, AttributeError, NTTMCPAPIException):
        module.fail_json(msg='Failed to locate the Cloud Network Domain - {0}'.
                         format(network_domain_name))

    # Get the VLAN object based on the supplied name
    try:
        if vlan_name:
            vlan = client.get_vlan_by_name(name=vlan_name,
                                           datacenter=datacenter,
                                           network_domain_id=network_domain_id)
            vlan_id = vlan.get('id')
        else:
            vlan_id = None
    except (KeyError, IndexError, AttributeError, NTTMCPAPIException):
        module.fail_json(
            msg='Failed to locate the VLAN - {0}'.format(vlan_name))

    try:
        if server_id:
            server = client.get_server_by_id(server_id=server_id)
            if server:
                return_data['server'].append(server)
        elif name:
            server = client.get_server_by_name(
                datacenter=datacenter,
                network_domain_id=network_domain_id,
                name=name)
            if server:
                return_data['server'].append(server)
        else:
            servers = client.list_servers(datacenter, network_domain_id,
                                          vlan_id, name)
            return_data['server'] = servers
    except (KeyError, IndexError, AttributeError):
        module.fail_json(msg='Could not find the server - {0} in {1}'.format(
            name, datacenter))

    return_data['count'] = len(return_data.get('server'))

    module.exit_json(data=return_data)
def main():
    """
    Main function

    :returns: Server Information
    """
    module = AnsibleModule(argument_spec=dict(
        auth=dict(type='dict'),
        region=dict(default='na', type='str'),
        datacenter=dict(required=True, type='str'),
        network_domain=dict(required=True, type='str'),
        server=dict(required=True, type='str'),
        plan=dict(required=False, type='str'),
        state=dict(default='present', choices=['present', 'absent']),
    ),
                           supports_check_mode=True)

    try:
        credentials = get_credentials(module)
    except ImportError as e:
        module.fail_json(msg='{0}'.format(e))
    name = module.params.get('server')
    datacenter = module.params.get('datacenter')
    state = module.params.get('state')
    network_domain_name = module.params.get('network_domain')
    server = {}

    # Check the region supplied is valid
    regions = get_regions()
    if module.params.get('region') not in regions:
        module.fail_json(
            msg='Invalid region. Regions must be one of {0}'.format(regions))

    if credentials is False:
        module.fail_json(msg='Could not load the user credentials')

    try:
        client = NTTMCPClient(credentials, module.params.get('region'))
    except NTTMCPAPIException as e:
        module.fail_json(msg=e.msg)

    # Get the CND object based on the supplied name
    try:
        if network_domain_name is None:
            module.fail_json(
                msg=
                'No network_domain or network_info.network_domain was provided'
            )
        network = client.get_network_domain_by_name(datacenter=datacenter,
                                                    name=network_domain_name)
        network_domain_id = network.get('id')
    except (KeyError, IndexError, AttributeError, NTTMCPAPIException):
        module.fail_json(msg='Failed to find the Cloud Network Domain: {0}'.
                         format(network_domain_name))

    # Check if the Server exists based on the supplied name
    try:
        server = client.get_server_by_name(datacenter, network_domain_id, None,
                                           name)
    except (KeyError, IndexError, AttributeError, NTTMCPAPIException) as e:
        module.fail_json(
            msg='Failed attempting to locate any existing server - {0}'.format(
                e))

    monitoring = server.get('monitoring', {})

    if state == 'present':
        # Implement Check Mode
        if module.check_mode:
            if not monitoring.get('servicePlan') == module.params.get('plan'):
                module.exit_json(
                    msg=
                    'Monitoring of type {0} will be applied to server with ID {1}'
                    .format(module.params.get('plan'), server.get('id')))
            else:
                module.exit_json(msg='No changes are required')
        if not monitoring:
            add_monitoring(module, client, False, server.get('id'))
        else:
            if monitoring.get('servicePlan') != module.params.get('plan'):
                add_monitoring(module, client, True, server.get('id'))
            else:
                module.exit_json(changed=False, data=server)
        try:
            server = client.get_server_by_name(datacenter, None, name)
        except NTTMCPAPIException:
            pass
        module.exit_json(changed=True, data=server)
    elif state == 'absent':
        try:
            if not monitoring:
                module.exit_json(
                    msg='Server {0} does not currently have monitoring enabled'
                    .format(server.get('name')))
            # Implement Check Mode
            if module.check_mode:
                module.exit_json(
                    msg=
                    'Monitoring of type {0} will be removed from the server with ID {1}'
                    .format(module.params.get('plan'), server.get('id')))
            remove_monitoring(module, client, server.get('id'))
            try:
                server = client.get_server_by_name(datacenter,
                                                   network_domain_id, None,
                                                   name)
            except NTTMCPAPIException:
                pass
            module.exit_json(changed=True, data=server)
        except (KeyError, IndexError, AttributeError, NTTMCPAPIException) as e:
            module.fail_json(
                msg='Could not remove the monitoring from server {0} - {1}'.
                format(module.params.get('name'), e))
def main():
    """
    Main function

    :returns: Server Information
    """
    module = AnsibleModule(
        argument_spec=dict(
            auth=dict(type='dict'),
            region=dict(default='na', type='str'),
            datacenter=dict(required=True, type='str'),
            network_domain=dict(required=True, type='str'),
            server=dict(required=True, type='str'),
            iso=dict(required=False, default=False, type='bool'),
            vmtools=dict(required=False, default=True, type='bool'),
            vapp=dict(required=False, default=None, type='list', elements='dict'),
            wait=dict(required=False, default=True, type='bool'),
            wait_time=dict(required=False, default=600, type='int'),
            wait_poll_interval=dict(required=False, default=5, type='int'),
            state=dict(default='present', choices=['present', 'absent']),
        ),
        supports_check_mode=True
    )

    try:
        credentials = get_credentials(module)
    except ImportError as e:
        module.fail_json(msg='{0}'.format(e))
    name = module.params.get('server')
    datacenter = module.params.get('datacenter')
    state = module.params.get('state')
    network_domain_name = module.params.get('network_domain')
    server = vapp = dict()
    server_id = None

    # Check the region supplied is valid
    regions = get_regions()
    if module.params.get('region') not in regions:
        module.fail_json(msg='Invalid region. Regions must be one of {0}'.format(regions))

    if credentials is False:
        module.fail_json(msg='Could not load the user credentials')

    try:
        client = NTTMCPClient(credentials, module.params.get('region'))
    except NTTMCPAPIException as e:
        module.fail_json(msg=e.msg)

    # Get the CND object based on the supplied name
    try:
        if network_domain_name is None:
            module.fail_json(msg='No network_domain or network_info.network_domain was provided')
        network = client.get_network_domain_by_name(datacenter=datacenter, name=network_domain_name)
        network_domain_id = network.get('id')
    except (KeyError, IndexError, AttributeError, NTTMCPAPIException):
        module.fail_json(msg='Failed to find the Cloud Network Domain: {0}'.format(network_domain_name))

    # Check if the Server exists based on the supplied name
    try:
        server = client.get_server_by_name(datacenter, network_domain_id, None, name)
        server_id = server.get('id')
        if server.get('started'):
            module.fail_json(msg='vApp properties cannot be modified while the server is running')
        if not server_id:
            module.fail_json(msg='Failed to locate the server')
        # vapp = ast.literal_eval(str(server.get('vAppProperties')).encode('ascii')) or dict()
        vapp = ast.literal_eval(str(server.get('vAppProperties'))) or dict()
    except (KeyError, IndexError, AttributeError, NTTMCPAPIException) as e:
        module.fail_json(msg='Failed to locate the server - {0}'.format(e))

    # Check vApp dictionary is valid
    if not (state == 'absent' and module.params.get('vapp') is None):
        validate_vapp_args(module, client)

    if state == 'present':
        if compare_vapp(module, vapp):
            configure_vapp(module, client, server_id)
        else:
            module.exit_json(msg='No update required', data=server.get('vAppProperties'))
        try:
            # Pause to allow the API/DB to catch up
            sleep(2)
            server = client.get_server_by_name(datacenter, network_domain_id, None, name)
        except NTTMCPAPIException:
            module.warn(warning='The update was successfull but there was an issue getting the updated server')
            pass
        module.exit_json(changed=True, data=server.get('vAppProperties'))
    elif state == 'absent':
        try:
            if not vapp:
                module.exit_json(msg='Server {0} does not currently have vApp enabled'.format(server.get('name')))
            # Implement Check Mode
            if module.check_mode:
                if not module.params.get('vapp'):
                    module.exit_json(msg='vApp will be disabled on the server with ID {0}'.format(server.get('id')))
                module.exit_json(msg='The following vApp keys will be removed from the server with ID {0}'.format(
                                 server.get('id')), data=module.params.get('vapp'))

            if module.params.get('vapp'):
                remove_vapp(module, client, server.get('id'), vapp)
                try:
                    server = client.get_server_by_name(datacenter, network_domain_id, None, name)
                except NTTMCPAPIException:
                    module.warn(warning='The update was successfull but there was an issue getting the updated server')
                    pass
                module.exit_json(changed=True, data=server.get('vAppProperties'))
            else:
                disable_vapp(module, client, server.get('id'))
        except (KeyError, IndexError, AttributeError, NTTMCPAPIException) as e:
            module.fail_json(msg='Could not remove vApp from server {0} - {1}'.format(server.get('id'),
                                                                                      e))
def main():
    """
    Main function
    :returns: A message
    """
    module = AnsibleModule(argument_spec=dict(
        auth=dict(type='dict'),
        region=dict(default='na', type='str'),
        datacenter=dict(required=True, type='str'),
        network_domain=dict(required=False, default=None, type='str'),
        name=dict(required=True, type='str'),
        wait=dict(required=False, default=True, type='bool'),
        wait_time=dict(required=False, default=1800, type='int'),
        wait_poll_interval=dict(required=False, default=30, type='int'),
    ),
                           supports_check_mode=True)
    result = None
    CORE['name'] = module.params.get('name')
    try:
        credentials = get_credentials(module)
    except ImportError as e:
        module.fail_json(msg='{0}'.format(e))

    # Check the region supplied is valid
    regions = get_regions()
    if module.params.get('region') not in regions:
        module.fail_json(
            msg='Invalid region. Regions must be one of {0}'.format(regions))

    if credentials is False:
        module.fail_json(msg='Could not load the user credentials')

    try:
        client = NTTMCPClient(credentials, module.params.get('region'))
    except NTTMCPAPIException as e:
        module.fail_json(msg=e.msg)

    # Get the CND
    try:
        network = client.get_network_domain_by_name(
            name=module.params.get('network_domain'),
            datacenter=module.params.get('datacenter'))
        CORE['network_domain_id'] = network.get('id')
    except (KeyError, IndexError, AttributeError, NTTMCPAPIException):
        module.fail_json(
            msg='Could not find the Cloud Network Domain: {0}'.format(
                module.params.get('network_domain')))

    try:
        server = client.get_server_by_name(
            datacenter=module.params.get('datacenter'),
            network_domain_id=network.get('id'),
            name=CORE.get('name'))
        if not server:
            module.fail_json(msg='Could not find the server - {0} in {1}'.
                             format(module.params.get('name'),
                                    module.params.get('datacenter')))
    except (KeyError, IndexError, AttributeError):
        module.fail_json(msg='Could not find the server - {0} in {1}'.format(
            module.params.get('name'), module.params.get('datacenter')))

    try:
        if module.check_mode:
            module.exit_json(
                'Server with ID {0} will be migrated from preview mode'.format(
                    server.get('id')))
        result = client.migrate_snapshot_preview(server.get('id'))
        if result.get('responseCode') != 'IN_PROGRESS':
            module.fail_json(
                msg='The Snapshot server migration failed with reason - {0}'.
                format(result.get('responseCode')))
        wait_for_migration(module, client, server.get('id'))
        module.exit_json(
            msg='The Snapshot Preview server migration was successful')
    except (KeyError, IndexError, AttributeError, NTTMCPAPIException) as e:
        module.fail_json(msg='Could not retrieve the Snapshot - {0}'.format(e))
Exemple #6
0
def main():
    """
    Main function

    :returns: Server Information
    """
    module = AnsibleModule(
        argument_spec=dict(
            auth=dict(type='dict'),
            region=dict(default='na', type='str'),
            datacenter=dict(required=True, type='str'),
            network_domain=dict(required=True, type='str'),
            server=dict(required=True, type='str'),
            description=dict(required=False, type='str'),
            image=dict(required=True, type='str'),
            cluster=dict(required=False, type='str'),
            goc=dict(required=False, default=True, type='bool'),
            wait=dict(required=False, default=True, type='bool'),
            wait_time=dict(required=False, default=3600, type='int'),
            wait_poll_interval=dict(required=False, default=30, type='int')
        ),
        supports_check_mode=True
    )

    try:
        credentials = get_credentials(module)
    except ImportError as e:
        module.fail_json(msg='{0}'.format(e))
    server_name = module.params.get('server')
    datacenter = module.params.get('datacenter')
    network_domain_name = module.params.get('network_domain')
    server = dict()

    # Check the region supplied is valid
    regions = get_regions()
    if module.params.get('region') not in regions:
        module.fail_json(msg='Invalid region. Regions must be one of {0}'.format(regions))

    if credentials is False:
        module.fail_json(msg='Could not load the user credentials')

    try:
        client = NTTMCPClient(credentials, module.params.get('region'))
    except NTTMCPAPIException as e:
        module.fail_json(msg=e.msg)

    # Get the CND
    try:
        network = client.get_network_domain_by_name(network_domain_name, datacenter)
        network_domain_id = network.get('id')
    except (KeyError, IndexError, AttributeError, NTTMCPAPIException):
        module.fail_json(msg='Could not find the Cloud Network Domain: {0}'.format(network_domain_name))

    # Check if the Server exists based on the supplied name
    try:
        server = client.get_server_by_name(datacenter=datacenter,
                                           network_domain_id=network_domain_id,
                                           name=server_name)
        if not server:
            module.fail_json(msg='Failed attempting to locate any existing server')
    except (KeyError, IndexError, AttributeError, NTTMCPAPIException) as e:
        module.fail_json(msg='Failed attempting to locate any existing server - {0}'.format(e))

    if module.check_mode:
        module.exit_json(msg='The server with ID {0} will be cloned to the image {1}'.format(server.get('id'),
                                                                                             module.params.get('image')))

    try:
        result = client.clone_server_to_image(server_id=server.get('id'),
                                              image_name=module.params.get('image'),
                                              description=module.params.get('description'),
                                              cluster_id=module.params.get('cluster'),
                                              goc=module.params.get('goc'))
        if module.params.get('wait'):
            wait_for_server(module, client, server.get('id'))
        module.exit_json(changed=True,
                         msg='The server with ID {0} was successfully cloned to the new image with ID {1}'.format(server.get('id'),
                                                                                                                  result))
    except NTTMCPAPIException as e:
        module.fail_json(msg='Could not clone the server with ID {0} - {1}'.format(server.get('id'), e))
def main():
    """
    Main function

    :returns: Server Information
    """
    module = AnsibleModule(
        argument_spec=dict(
            auth=dict(type='dict'),
            region=dict(default='na', type='str'),
            datacenter=dict(required=True, type='str'),
            network_domain=dict(required=True, type='str'),
            server=dict(required=True, type='str'),
            vlan=dict(default=None, required=False, type='str'),
            vlan_2=dict(default=None, required=False, type='str'),
            ipv4_address=dict(default=None, required=False, type='str'),
            ipv4_address_2=dict(default=None, required=False, type='str'),
            type=dict(default='VMXNET3', required=False, choices=NIC_ADAPTER_TYPES),
            connected=dict(default=True, required=False, type='bool'),
            state=dict(default='present', choices=['present', 'absent', 'exchange']),
            stop=dict(default=True, type='bool'),
            start=dict(default=True, type='bool'),
            wait=dict(required=False, default=True, type='bool'),
            wait_time=dict(required=False, default=1200, type='int'),
            wait_poll_interval=dict(required=False, default=30, type='int'),
            wait_for_vmtools=dict(required=False, default=False, type='bool')
        ),
        supports_check_mode=True
    )

    try:
        credentials = get_credentials(module)
    except ImportError as e:
        module.fail_json(msg='{0}'.format(e))
    name = module.params.get('server')
    datacenter = module.params.get('datacenter')
    state = module.params.get('state')
    network_domain_name = module.params.get('network_domain')
    server_running = True
    changed = False
    vlan_name = module.params.get('vlan')
    vlan_name_2 = module.params.get('vlan_2')
    ipv4_address = module.params.get('ipv4_address')
    ipv4_address_2 = module.params.get('ipv4_address_2')
    start = module.params.get('start')
    server = {}

    # Check the region supplied is valid
    regions = get_regions()
    if module.params.get('region') not in regions:
        module.fail_json(msg='Invalid region. Regions must be one of {0}'.format(regions))

    if credentials is False:
        module.fail_json(msg='Could not load the user credentials')

    client = NTTMCPClient(credentials, module.params.get('region'))

    # Get the CND object based on the supplied name
    try:
        if network_domain_name is None:
            module.fail_json(msg='No network_domain or network_info.network_domain was provided')
        network = client.get_network_domain_by_name(datacenter=datacenter, name=network_domain_name)
        network_domain_id = network.get('id')
    except (KeyError, IndexError, AttributeError, NTTMCPAPIException):
        module.fail_json(msg='Failed to find the Cloud Network Domain: {0}'.format(network_domain_name))

    # Get a list of existing VLANs
    if vlan_name:
        try:
            vlan = client.get_vlan_by_name(name=vlan_name, datacenter=datacenter, network_domain_id=network_domain_id)
        except NTTMCPAPIException as e:
            module.fail_json(msg='Failed to get a list of VLANs - {0}'.format(e))
    else:
        vlan = False
    if not vlan:
        module.fail_json(msg='A valid VLAN name must be supplied')
        if state != 'absent' and not ipv4_address:
            module.fail_json(msg='A valid IPv4 address must be supplied')

    # Get the secondary VLAN and or IPv4 address
    if vlan_name_2:
        try:
            vlan_2 = client.get_vlan_by_name(name=vlan_name_2, datacenter=datacenter, network_domain_id=network_domain_id)
        except NTTMCPAPIException as e:
            module.fail_json(msg='Failed to get a list of VLANs for the second VLAN - {0}'.format(e))
    else:
        vlan_2 = False
    if state == 'exchange' and not vlan_2:
        module.fail_json(msg='A valid secondary VLAN name or secondary IPv4 address is required when exchanging NIC VLANs')
        if state == 'exchange' and not ipv4_address_2:
            module.fail_json(msg='A valid secondary IPv4 address is required if no secondary VLAN is supplied when exchanging NIC VLANs')

    # Check if the Server exists based on the supplied name
    try:
        server = client.get_server_by_name(datacenter, network_domain_id, None, name)
        if server:
            server_running = server.get('started')
        else:
            module.fail_json(msg='Failed to find the server - {0}'.format(name))
    except (KeyError, IndexError, AttributeError, NTTMCPAPIException) as e:
        module.fail_json(msg='Failed attempting to locate any existing server - {0}'.format(e))

    # Setup the rest of the CORE dictionary to save passing data around
    CORE['network_domain_id'] = network_domain_id
    CORE['module'] = module
    CORE['client'] = client
    CORE['name'] = server.get('name')

    if state == 'present':
        try:
            nic = get_nic(module, server, vlan, ipv4_address)
            if not nic:
                # Implement Check Mode
                if module.check_mode:
                    module.exit_json(msg='A new NIC in VLAN {0} will be added to the server {1}'.format(
                        vlan.get('name'),
                        server.get('name')))
                server_running = check_and_stop_server(module, client, server, server_running)
                add_nic(module, client, network_domain_id, server, vlan)
                changed = True
            else:
                if nic.get('networkAdapter') != module.params.get('type'):
                    # Implement Check Mode
                    if module.check_mode:
                        module.exit_json(msg='NIC with the IP {0} in VLAN {1} will be changed from {2} to {3}'.format(
                            nic.get('privateIpv4'),
                            nic.get('vlanName'),
                            nic.get('networkAdapter'),
                            module.params.get('type')))
                    server_running = check_and_stop_server(module, client, server, server_running)
                    change_nic_type(module, client, network_domain_id, server, nic.get('id'),
                                    module.params.get('type'))
                    changed = True
                if (not module.params.get('connected') and nic.get('connected')) or (
                   (module.params.get('connected') and not nic.get('connected'))):
                    operation = 'connected' if module.params.get('connected') else 'disconnected'
                    if module.check_mode:
                        module.exit_json(msg='NIC with the IP {0} in VLAN {1} will be {2}'.format(
                            nic.get('privateIpv4'),
                            nic.get('vlanName'),
                            operation))
                    change_nic_state(module, client, network_domain_id, server, nic.get('id'))
                    changed = True
        except NTTMCPAPIException as e:
            module.fail_json(msg='Could not add the NIC - {0}'.format(e))
    elif state == 'absent':
        try:
            nic = get_nic(module, server, vlan, ipv4_address)
            if nic:
                # Implement Check Mode
                if module.check_mode:
                    module.exit_json(msg='The NIC with IP {0} in VLAN {1} will be removed'.format(
                        nic.get('privateIpv4'),
                        nic.get('vlanName')))
                server_running = check_and_stop_server(module, client, server, server_running)
                remove_nic(module, client, network_domain_id, server, nic)
                changed = True
            else:
                module.fail_json(msg='Server {0} has not matching NIC'.format(module.params.get('name')))
        except NTTMCPAPIException as e:
            module.fail_json(msg='Could not remove the NIC - {0}'.format(e))
    elif state == 'exchange':
        try:
            nic_1 = get_nic(module, server, vlan, ipv4_address)
            nic_2 = get_nic(module, server, vlan_2, ipv4_address_2)
            if nic_1 and nic_2:
                # Implement Check Mode
                if module.check_mode:
                    module.exit_json(msg='The NIC with IP {0} in VLAN {1} will be exchanged with the NIC with IP {2} in VLAN {3}'.format(
                        nic_1.get('privateIpv4'),
                        nic_1.get('vlanName'),
                        nic_2.get('privateIpv4'),
                        nic_2.get('vlanName'),))
                server_running = check_and_stop_server(module, client, server, server_running)
                exchange_nic(module, client, network_domain_id, server, nic_1, nic_2)
                changed = True
            else:
                module.fail_json(msg='Server {0} has no matching NICs'.format(module.params.get('server')))
        except NTTMCPAPIException as e:
            module.fail_json(msg='Could not exchange the server {0} has no matching NICs - {1}'.format(module.params.get('name'), e))

    # Introduce a pause to allow the API to catch up in more remote MCP locations
    sleep(10)
    try:
        server = client.get_server_by_name(datacenter, network_domain_id, None, name)
        if server:
            server_running = server.get('started')
        else:
            module.fail_json(msg='Failed to find the server to determine the final running state - {0}'.format(name))
        if start and not server_running:
            server_command(module, client, server, 'start')
        server = client.get_server_by_name(datacenter, network_domain_id, None, name)
        module.exit_json(changed=changed, data=server)
    except NTTMCPAPIException as e:
        module.fail_json(changed=changed, msg='Could not verify the server status - {0}'.format(e))
def main():
    """
    Main function
    :returns: Server Anti-Affinity Group information or a message
    """
    module = AnsibleModule(argument_spec=dict(
        auth=dict(type='dict'),
        region=dict(default='na', type='str'),
        datacenter=dict(required=True, type='str'),
        network_domain=dict(required=True, type='str'),
        id=dict(default=None, required=False, type='str'),
        name=dict(default=None, required=False, type='str'),
        server=dict(required=True, type='str'),
        vlan=dict(default=None, required=False, type='str'),
        state=dict(default='present',
                   required=False,
                   choices=['present', 'absent'])),
                           supports_check_mode=True)
    network_domain_name = module.params.get('network_domain')
    network_domain_id = group_type = member_id = None
    vlan = sec_group = server = nic = dict()
    datacenter = module.params.get('datacenter')
    state = module.params.get('state')
    try:
        credentials = get_credentials(module)
        if credentials is False:
            module.fail_json(msg='Could not load the user credentials')
    except ImportError as e:
        module.fail_json(msg='{0}'.format(e))

    # Check the region supplied is valid
    regions = get_regions()
    if module.params.get('region') not in regions:
        module.fail_json(
            msg='Invalid region. Regions must be one of {0}'.format(regions))

    try:
        client = NTTMCPClient(credentials, module.params.get('region'))
    except NTTMCPAPIException as e:
        module.fail_json(msg=e.msg)

    # Get the CND
    try:
        network = client.get_network_domain_by_name(network_domain_name,
                                                    datacenter)
        network_domain_id = network.get('id')
    except (KeyError, IndexError, AttributeError, NTTMCPAPIException):
        module.fail_json(msg='Could not find the Cloud Network Domain: {0}'.
                         format(network_domain_name))

    # Try and find any existing Security Group
    try:
        if module.params.get('name'):
            sec_groups = client.list_security_groups(
                network_domain_id=None
                if module.params.get('vlan') else network_domain_id,
                name=None,
                group_type=None,
                server_id=None,
                vlan_id=vlan.get('id', None))
            sec_group = [
                x for x in sec_groups
                if x.get('name') == module.params.get('name')
            ][0]
        if module.params.get('id'):
            sec_group = client.get_security_group_by_id(
                group_id=module.params.get('id'))
        if sec_group:
            group_type = sec_group.get('type').lower()
        else:
            module.fail_json(
                msg='Could not find the Security Group {0}'.format(
                    module.params.get('name')))
    except (KeyError, IndexError, AttributeError, NTTMCPAPIException):
        module.fail_json(msg='Could not find the Security Group {0}'.format(
            module.params.get('name')))

    # Check if the Server exists based on the supplied name
    try:
        server = client.get_server_by_name(datacenter, network_domain_id, None,
                                           module.params.get('server'))
        if not server:
            module.fail_json(msg='Failed to find the server - {0}'.format(
                module.params.get('server')))
    except (KeyError, IndexError, AttributeError, NTTMCPAPIException) as e:
        module.fail_json(msg='Failed to find the server - {0}'.format(e))

    # Search for any NICs that match any supplied VLAN
    if module.params.get('vlan'):
        try:
            nics = [server.get('networkInfo', {}).get('primaryNic')
                    ] + server.get('networkInfo', {}).get('additionalNic')
            nic = [
                x for x in nics
                if x.get('vlanName') == module.params.get('vlan')
            ][0]
        except (KeyError, IndexError, AttributeError):
            module.fail_json(
                msg='Failed to find the NIC for server {0} in VLAN {1}'.format(
                    module.params.get('server'), module.params.get('vlan')))

        # Check if the NIC already exists in the Security Group
        try:
            if [
                    x for x in sec_group.get('nics', {}).get('nic', [])
                    if x.get('id') == nic.get('id')
            ][0]:
                if state == 'present':
                    module.exit_json(
                        msg=
                        'NIC with ID {0} is already a member of the Security Group {1}'
                        .format(nic.get('id'), sec_group.get('id')))
        except IndexError:
            if state == 'absent':
                module.exit_json(
                    msg=
                    'The NIC with ID {0} is not a member of the Security Group {1}'
                    .format(nic.get('id'), sec_group.get('id')))
            pass

        if module.check_mode:
            module.exit_json(
                msg=
                'The NIC ID {0} will be added to the Security Group with ID {1}'
                .format(nic.get('id'), sec_group.get('id')))
        member_id = nic.get('id')
    else:
        member_id = server.get('id')
        # Check if the server is already a member of the Security Group
        try:
            if [
                    x for x in sec_group.get('servers', {}).get('server', [])
                    if x.get('id') == server.get('id')
            ][0]:
                if state == 'present':
                    module.exit_json(
                        msg=
                        'Server with ID {0} is already a member of the Security Group {1}'
                        .format(server.get('id'), sec_group.get('id')))
        except IndexError:
            if state == 'absent':
                module.exit_json(
                    msg=
                    'The Server with ID {0} is not a member of the Security Group {1}'
                    .format(server.get('id'), sec_group.get('id')))
            pass

        if module.check_mode:
            module.exit_json(
                msg=
                'The Server ID {0} will be added to the Security Group with ID {1}'
                .format(server.get('id'), sec_group.get('id')))

    try:
        if state == 'present':
            try:
                client.add_security_group_member(group_id=sec_group.get('id'),
                                                 group_type=group_type,
                                                 member_id=member_id)
                sec_group = client.get_security_group_by_id(
                    group_id=sec_group.get('id'))
                if not sec_group:
                    module.warn(
                        warning=
                        'Could not verify the update of the Security Group with ID {0}'
                        .format(sec_group.get('id')))
                module.exit_json(changed=True, data=sec_group)
            except (NTTMCPAPIException) as e:
                module.fail_json(
                    msg='Failed to update the Security Group - {0}'.format(e))
        # Delete the Security Group
        elif state == 'absent':
            if not sec_group:
                module.exit_json(msg='Security Group not found')
            # Implement Check Mode
            if module.check_mode:
                module.exit_json(
                    msg=
                    'An existing Security Group was found for {0} and will be removed'
                    .format(sec_group.get('id')))
            result = client.delete_security_group_member(
                group_id=sec_group.get('id'),
                member_id=member_id,
                group_type=group_type)
            if result.get('responseCode') == 'OK':
                module.exit_json(
                    changed=True,
                    msg='The Security Group member was successfully removed')
            module.fail_json(
                msg='Could not remove the Security Group member - {0}'.format(
                    result.content))
    except (KeyError, IndexError, AttributeError, NTTMCPAPIException) as e:
        module.fail_json(
            msg='Could not remove the Security Group member - {0}'.format(e))
def main():
    """
    Main function
    :returns: Snapshot Information
    """
    module = AnsibleModule(argument_spec=dict(
        auth=dict(type='dict'),
        region=dict(default='na', type='str'),
        datacenter=dict(required=True, type='str'),
        network_domain=dict(required=True, type='str'),
        server=dict(required=True, type='str'),
        pre_path=dict(required=False, default=None, type='str'),
        pre_description=dict(required=False, default=None, type='str'),
        pre_timeout=dict(required=False, default=300, type='int'),
        on_failure=dict(required=False,
                        default='CONTINUE',
                        choices=['CONTINUE', 'ABORT']),
        post_path=dict(required=False, default=None, type='str'),
        post_description=dict(required=False, default=None, type='str'),
        username=dict(required=False, default=None, type='str'),
        password=dict(required=False, default=None, type='str'),
        state=dict(default='present', choices=['present', 'absent'])),
                           supports_check_mode=True)
    try:
        credentials = get_credentials(module)
    except ImportError as e:
        module.fail_json(msg='{0}'.format(e))

    state = module.params.get('state')
    datacenter = module.params.get('datacenter')
    network_domain_name = module.params.get('network_domain')
    server_name = module.params.get('server')
    network_domain_id = None
    server = None

    # Check the region supplied is valid
    regions = get_regions()
    if module.params.get('region') not in regions:
        module.fail_json(
            msg='Invalid region. Regions must be one of {0}'.format(regions))

    if credentials is False:
        module.fail_json(msg='Could not load the user credentials')

    try:
        client = NTTMCPClient(credentials, module.params.get('region'))
    except NTTMCPAPIException as e:
        module.fail_json(msg=e.msg)

    # Get the CND
    try:
        network = client.get_network_domain_by_name(name=network_domain_name,
                                                    datacenter=datacenter)
        network_domain_id = network.get('id')
    except (KeyError, IndexError, AttributeError, NTTMCPAPIException) as e:
        module.fail_json(
            msg='Could not find the Cloud Network Domain: {0}'.format(e))

    # Check if the Server exists based on the supplied name
    try:
        server = client.get_server_by_name(datacenter=datacenter,
                                           network_domain_id=network_domain_id,
                                           name=server_name)
        if not server.get('guest', {}).get(
                'vmTools', {}).get('runningStatus') == 'RUNNING':
            raise NTTMCPAPIException(
                'VMWare Tools is required to be running on server {0}'.format(
                    server_name))
    except (KeyError, IndexError, AttributeError, NTTMCPAPIException) as e:
        module.fail_json(
            msg='Could not locate any existing server - {0}'.format(e))

    if state == 'present':
        if module.params.get('pre_path') is not None or module.params.get(
                'post_path') is not None:
            if None in [
                    module.params.get('username'),
                    module.params.get('password')
            ]:
                module.fail_json(
                    msg=
                    'A username and password is required when configuring a snapshot script(s)'
                )
        if not server.get('snapshotService'):
            module.fail_json(
                msg=
                'This server does not currently have the Snapshot Service enabled'
            )
        else:
            if compare_scripts(module, server.get('snapshotService')):
                update_scripts(module, client, server)
                module.exit_json(
                    changed=True,
                    msg='Snapshot scripts updated for server {0}'.format(
                        server.get('id')))
            module.exit_json(msg='No changes required')
    elif state == 'absent':
        if not server.get('snapshotService'):
            module.exit_json(
                msg='Snapshots are not currently configured for this server')
        if compare_scripts(module, server.get('snapshotService')):
            delete_scripts(module, client, server)
            module.exit_json(changed=True,
                             msg="Server snapshot script(s) have been deleted")
        module.exit_json(msg='No changes required')
def main():
    """
    Main function

    :returns: Server Information
    """
    module = AnsibleModule(
        argument_spec=dict(
            auth=dict(type='dict'),
            region=dict(default='na', type='str'),
            datacenter=dict(required=True, type='str'),
            network_domain=dict(required=True, type='str'),
            server=dict(required=True, type='str'),
            id=dict(default=None, required=False, type='str'),
            type=dict(default='SCSI', required=False, choices=['SCSI', 'SATA', 'IDE']),
            controller_number=dict(default=0, required=False, type='int'),
            disk_number=dict(default=None, required=False, type='int'),
            size=dict(required=False, type='int'),
            speed=dict(default='STANDARD', required=False, choices=DISK_SPEEDS),
            iops=dict(default=None, required=False, type='int'),
            state=dict(default='present', choices=['present', 'absent']),
            stop=dict(default=True, type='bool'),
            start=dict(default=True, type='bool'),
            wait=dict(required=False, default=True, type='bool'),
            wait_time=dict(required=False, default=1200, type='int'),
            wait_poll_interval=dict(required=False, default=30, type='int'),
            wait_for_vmtools=dict(required=False, default=False, type='bool')
        ),
        supports_check_mode=True
    )

    try:
        credentials = get_credentials(module)
    except ImportError as e:
        module.fail_json(msg='{0}'.format(e))
    name = module.params.get('server')
    datacenter = module.params.get('datacenter')
    state = module.params.get('state')
    network_domain_name = module.params.get('network_domain')
    CORE['datacenter'] = module.params.get('datacenter')
    CORE['region'] = module.params.get('region')
    # CORE['wait_for_vmtools'] = module.params.get('wait_for_vmtools')
    server_running = True
    stop_server = module.params.get('stop')
    start = module.params.get('start')
    server = {}
    disk_number = None

    # Check the region supplied is valid
    regions = get_regions()
    if module.params.get('region') not in regions:
        module.fail_json(msg='Invalid region. Regions must be one of {0}'.format(regions))

    if credentials is False:
        module.fail_json(msg='Could not load the user credentials')

    try:
        client = NTTMCPClient(credentials, module.params.get('region'))
    except NTTMCPAPIException as e:
        module.fail_json(msg=e.msg)

    # Get the CND object based on the supplied name
    try:
        if network_domain_name is None:
            module.fail_json(msg='No network_domain or network_info.network_domain was provided')
        network = client.get_network_domain_by_name(datacenter=datacenter, name=network_domain_name)
        network_domain_id = network.get('id')
    except (KeyError, IndexError, AttributeError, NTTMCPAPIException):
        module.fail_json(msg='Failed to find the Cloud Network Domain: {0}'.format(network_domain_name))

    # Check if the Server exists based on the supplied name
    try:
        server = client.get_server_by_name(datacenter, network_domain_id, None, name)
        if server:
            server_running = server.get('started')
        else:
            module.fail_json(msg='Failed to find the server - {0}'.format(name))
    except (KeyError, IndexError, AttributeError, NTTMCPAPIException) as e:
        module.fail_json(msg='Failed attempting to locate any existing server - {0}'.format(e))

    # Setup the rest of the CORE dictionary to save passing data around
    CORE['network_domain_id'] = network_domain_id
    CORE['module'] = module
    CORE['client'] = client
    CORE['name'] = server.get('name')
    if state == 'present':
        disk = get_disk(module, server)
        if not disk:
            # Implement Check Mode
            if module.check_mode:
                module.exit_json(msg='A new {0} disk of size {1} will be added to the server {2}'.format(
                    module.params.get('type'),
                    module.params.get('size'),
                    server.get('name')))
            if server_running and stop_server:
                server_command(module, client, server, 'stop')
                server_running = False
            elif server_running and not stop_server:
                module.fail_json(msg='Server disks cannot be added while the server is running')
            disk_number = add_disk(module, client, network_domain_id, server)
            if start and not server_running:
                server_command(module, client, server, 'start')
            server = client.get_server_by_name(datacenter, network_domain_id, None, name)
            module.exit_json(changed=True, disk_number=disk_number, data=server)
        else:
            try:
                if compare_disk(module, disk):
                    if server_running and stop_server:
                        server_command(module, client, server, 'stop')
                        server_running = False
                    elif server_running and not stop_server:
                        module.fail_json(msg='Server disks cannot be added while the server is running')
                    update_disk(module, client, network_domain_id, server, disk)
                else:
                    module.exit_json(changed=False, data=server)
                if start and not server_running:
                    server_command(module, client, server, 'start')
                server = client.get_server_by_name(datacenter, network_domain_id, None, name)
                module.exit_json(changed=True, data=server)
            except NTTMCPAPIException as e:
                module.fail_json(msg='Failed to update the disk - {0}'.format(e))
    elif state == 'absent':
        try:
            disk = get_disk(module, server)
            if not disk:
                module.fail_json(msg='Controller {0} has no disk {1}'.format(module.params.get('controller_number'),
                                 module.params.get('disk_number')))
            # Implement Check Mode
            if module.check_mode:
                module.exit_json(msg='The disk with ID {0} will be removed from the server {1}'.format(
                    disk.get('id'),
                    server.get('name')))
            if server_running and stop_server:
                server_command(module, client, server, 'stop')
                server_running = False
            elif server_running and not stop_server:
                module.fail_json(msg='Disks cannot be removed while the server is running')
            remove_disk(module, client, network_domain_id, server, disk)
            # Introduce a pause to allow the API to catch up in more remote MCP locations
            sleep(10)
            server = client.get_server_by_name(datacenter, network_domain_id, None, name)
            if server:
                server_running = server.get('started')
            else:
                module.fail_json(msg='Failed to find the server to determine the final running state - {0}'.format(name))
            if start and not server_running:
                server_command(module, client, server, 'start')
            server = client.get_server_by_name(datacenter, network_domain_id, None, name)
            module.exit_json(changed=True, data=server)
        except (KeyError, IndexError, NTTMCPAPIException) as e:
            module.fail_json(msg='Could not delete the disk - {0}'.format(e))
Exemple #11
0
def main():
    """
    Main function
    :returns: Ansible Gateway Host Information
    """
    module = AnsibleModule(
        argument_spec=dict(
            auth=dict(type='dict'),
            region=dict(default='na', type='str'),
            datacenter=dict(required=True, type='str'),
            network_domain=dict(required=True, type='str'),
            vlan=dict(required=True, type='str'),
            name=dict(required=False, default='ansible_gw', type='str'),
            password=dict(default=None, required=False, type='str'),
            image=dict(required=False, type='str'),
            ipv4=dict(default=None, required=False, type='str'),
            src_ip=dict(default='ANY', required=False, type='str'),
            src_prefix=dict(default=None, required=False, type='str'),
            state=dict(default='present', choices=['present', 'absent']),
            wait=dict(required=False, default=True, type='bool'),
            wait_time=dict(required=False, default=1200, type='int'),
            wait_poll_interval=dict(required=False, default=30, type='int')
        )
    )

    try:
        credentials = get_credentials(module)
    except ImportError as e:
        module.fail_json(msg='{0}'.format(e))
    name = module.params.get('name')
    datacenter = module.params.get('datacenter')
    state = module.params.get('state')
    network_domain_name = module.params.get('network_domain')
    vlan_name = module.params.get('vlan')
    vlan_id = ansible_gw = None
    return_data = {}
    changed = False

    # Check the region supplied is valid
    regions = get_regions()
    if module.params.get('region') not in regions:
        module.fail_json(msg='Invalid region. Regions must be one of {0}'.format(regions))

    if credentials is False:
        module.fail_json(msg='Error: Could not load the user credentials')

    client = NTTMCPClient(credentials, module.params['region'])

    # Get the CND object based on the supplied name
    try:
        network = client.get_network_domain_by_name(datacenter=datacenter, name=network_domain_name)
        network_domain_id = network.get('id')
    except (KeyError, IndexError, AttributeError, NTTMCPAPIException) as exc:
        module.fail_json(msg='Failed to find the Cloud Network Domain - {0}'.format(exc))

    # Get the VLAN object based on the supplied name
    try:
        vlan = client.get_vlan_by_name(datacenter=datacenter, network_domain_id=network_domain_id, name=vlan_name)
        vlan_id = vlan.get('id')
    except (KeyError, IndexError, AttributeError, NTTMCPAPIException) as exc:
        module.fail_json(msg='Failed to get a list of VLANs - {0}'.format(exc), exception=traceback.format_exc())

    # Check if the server exists based on the supplied name
    try:
        ansible_gw = client.get_server_by_name(datacenter, network_domain_id, vlan_id, name)
    except (KeyError, IndexError, AttributeError, NTTMCPAPIException) as exc:
        module.fail_json(msg='Failed attempting to locate any existing server - {0}'.format(exc))

    # Handle the case where the gateway already exists. This could mean a playbook re-run
    # If the server exists then we need to check:
    #   a public IP is allocated and if not get the next one
    #   the NAT rule is present and correct and if not update/create it
    #   the Firewall rule is present and correct and if not update/create it
    if state == 'present' and ansible_gw:
        try:
            ansible_gw_private_ipv4 = ansible_gw.get('networkInfo').get('primaryNic').get('privateIpv4')
            # Check if the NAT rule exists and if not create it
            nat_result = client.get_nat_by_private_ip(network_domain_id, ansible_gw.get('networkInfo').get('primaryNic').get('privateIpv4'))
            if nat_result:
                public_ipv4 = nat_result.get('externalIp')
            else:
                public_ipv4 = client.get_next_public_ipv4(network_domain_id).get('ipAddress')
                create_nat_rule(module, client, network_domain_id, ansible_gw_private_ipv4, public_ipv4)
                changed = True
            # Check if the Firewall rule exists and if not create it
            fw_result = client.get_fw_rule_by_name(network_domain_id, ACL_RULE_NAME)
            if fw_result:
                update_fw_rule(module, client, fw_result, network_domain_id, public_ipv4)
            else:
                create_fw_rule(module, client, network_domain_id, public_ipv4)
                changed = True
            return_data['server_id'] = ansible_gw.get('id')
            return_data['password'] = ansible_gw.get('password', None)
            return_data['internal_ipv4'] = ansible_gw.get('networkInfo').get('primaryNic').get('privateIpv4')
            return_data['ipv6'] = ansible_gw.get('networkInfo').get('primaryNic').get('ipv6')
            return_data['public_ipv4'] = public_ipv4
            module.exit_json(changed=changed, data=return_data)
        except (KeyError, IndexError, AttributeError) as e:
            module.fail_json(msg='Could not ascertain the current server state: {0}'.format(e))
    elif state == 'present' and not ansible_gw:
        try:
            ansible_gw = create_server(module, client, network_domain_id, vlan_id)
            changed = True
            ansible_gw_private_ipv4 = ansible_gw.get('networkInfo').get('primaryNic').get('privateIpv4')
            # Check if the NAT rule exists and if not create it
            nat_result = client.get_nat_by_private_ip(network_domain_id, ansible_gw_private_ipv4)
            if nat_result:
                public_ipv4 = nat_result.get('externalIp')
            else:
                public_ipv4 = client.get_next_public_ipv4(network_domain_id).get('ipAddress')
                create_nat_rule(module, client, network_domain_id, ansible_gw_private_ipv4, public_ipv4)
                changed = True
            # Check if the Firewall rule exists and if not create it
            fw_result = client.get_fw_rule_by_name(network_domain_id, ACL_RULE_NAME)
            if fw_result:
                update_fw_rule(module, client, fw_result, network_domain_id, public_ipv4)
            else:
                create_fw_rule(module, client, network_domain_id, public_ipv4)
                changed = True
            return_data['server_id'] = ansible_gw.get('id')
            return_data['password'] = ansible_gw.get('password')
            return_data['internal_ipv4'] = ansible_gw_private_ipv4
            return_data['ipv6'] = ansible_gw.get('networkInfo').get('primaryNic').get('ipv6')
            return_data['public_ipv4'] = public_ipv4
            sleep(10)
            module.exit_json(changed=changed, data=return_data)
        except (KeyError, IndexError, AttributeError, NTTMCPAPIException) as exc:
            module.fail_json(changed=changed, msg='Failed to create/update the Ansible gateway - {0}'.format(exc), exception=traceback.format_exc())
    elif state == 'absent':
        nat_result = public_ipv4 = None
        try:
            # Check if the server exists and remove it
            if ansible_gw:
                delete_server(module, client, ansible_gw)
            # Check if the Firewall rule exists and if not create it
            fw_result = client.get_fw_rule_by_name(network_domain_id, ACL_RULE_NAME)
            if fw_result:
                delete_fw_rule(module, client, network_domain_id, fw_result.get('name'))
            '''
            Cases may exist where the only either the NAT private or public address maybe know so
            two ensure we've checked all possible options we will search by both
            The private address can be found from the server/ansible_gw object but the public address
            can only be determined by the firewall rule desintation value
            '''
            if ansible_gw:
                ansible_gw_private_ipv4 = ansible_gw.get('networkInfo').get('primaryNic').get('privateIpv4')
                nat_result = client.get_nat_by_private_ip(network_domain_id, ansible_gw_private_ipv4)
                if nat_result:
                    public_ipv4 = nat_result.get('externalIp')
            elif fw_result:
                public_ipv4 = fw_result.get('destination').get('ip').get('address')
                nat_result = client.get_nat_by_public_ip(network_domain_id, public_ipv4)

            if nat_result:
                delete_nat_rule(module, client, nat_result.get('id'))
            if public_ipv4:
                public_ip_block = client.get_public_ipv4_by_ip(network_domain_id, public_ipv4)
                if public_ip_block:
                    if not client.check_public_block_in_use(network_domain_id, public_ip_block.get('baseIp')):
                        delete_public_ipv4(module, client, public_ip_block.get('id'))
        except (KeyError, IndexError, AttributeError, NTTMCPAPIException) as e:
            module.fail_json(changed=changed, msg='Failed to remove the Ansible gateway configuration - {0}'.format(e))

        module.exit_json(changed=True, msg='The Ansible gateway and associated NAT and firewall rules have been removed')
    else:
        module.exit_json(changed=False, msg='Nothing to remove')
Exemple #12
0
def main():
    """
    Main function
    :returns: Server Anti-Affinity Group information
    """
    module = AnsibleModule(argument_spec=dict(
        auth=dict(type='dict'),
        region=dict(default='na', type='str'),
        datacenter=dict(required=True, type='str'),
        network_domain=dict(required=True, type='str'),
        type=dict(default='vlan', required=False, choices=['vlan', 'server']),
        name=dict(default=None, required=False, type='str'),
        id=dict(default=None, required=False, type='str'),
        server=dict(default=None, required=False, type='str'),
        vlan=dict(default=None, required=False, type='str')),
                           supports_check_mode=True)
    network_domain_name = module.params.get('network_domain')
    network_domain_id = None
    server = vlan = dict()
    datacenter = module.params.get('datacenter')
    return_data = return_object('security_group')
    try:
        credentials = get_credentials(module)
        if credentials is False:
            module.fail_json(msg='Could not load the user credentials')
    except ImportError as e:
        module.fail_json(msg='{0}'.format(e))

    # Check the region supplied is valid
    regions = get_regions()
    if module.params.get('region') not in regions:
        module.fail_json(
            msg='Invalid region. Regions must be one of {0}'.format(regions))

    try:
        client = NTTMCPClient(credentials, module.params.get('region'))
    except NTTMCPAPIException as e:
        module.fail_json(msg=e.msg)

    # Get the CND
    try:
        network = client.get_network_domain_by_name(network_domain_name,
                                                    datacenter)
        network_domain_id = network.get('id')
    except (KeyError, IndexError, AttributeError, NTTMCPAPIException):
        module.fail_json(msg='Could not find the Cloud Network Domain: {0}'.
                         format(network_domain_name))

    # If a server name was provided get the server object
    if module.params.get('server'):
        try:
            server = client.get_server_by_name(
                datacenter=datacenter,
                network_domain_id=network_domain_id,
                name=module.params.get('server'))
            if not server:
                module.fail_json(
                    msg='Could not find the server - {0} in {1}'.format(
                        module.params.get('server'), datacenter))
        except (KeyError, IndexError, AttributeError):
            module.fail_json(
                msg='Could not find the server - {0} in {1}'.format(
                    module.params.get('server'), datacenter))

    # If a vlan name was provided get the vlan object
    if module.params.get('vlan'):
        try:
            vlan = client.get_vlan_by_name(datacenter=datacenter,
                                           network_domain_id=network_domain_id,
                                           name=module.params.get('vlan'))
            if not vlan:
                module.fail_json(
                    msg='Could not find the VLAN - {0} in {1}'.format(
                        module.params.get('vlan'), datacenter))
        except (KeyError, IndexError, AttributeError):
            module.fail_json(msg='Could not find the VLAN - {0} in {1}'.format(
                module.params.get('vlan'), datacenter))

    try:
        if module.params.get('id'):
            return_data['security_group'] = client.get_security_group_by_id(
                group_id=module.params.get('id'))
        else:
            return_data['security_group'] = client.list_security_groups(
                network_domain_id=network_domain_id,
                name=module.params.get('name'),
                group_type=module.params.get('type'),
                server_id=server.get('id', None),
                vlan_id=vlan.get('id', None))
        return_data['count'] = len(return_data['security_group'])
        module.exit_json(data=return_data)
    except (KeyError, IndexError, AttributeError, NTTMCPAPIException) as e:
        module.fail_json(
            msg='Could not retrieve any Security Groups - {0}'.format(e))
def main():
    """
    Main function
    :returns: Server Anti-Affinity Group information
    """
    module = AnsibleModule(
        argument_spec=dict(
            auth=dict(type='dict'),
            region=dict(default='na', type='str'),
            datacenter=dict(required=True, type='str'),
            network_domain=dict(default=None, type='str'),
            servers=dict(default=list(), type='list', elements='str'),
        ),
        supports_check_mode=True
    )
    network_domain_name = module.params.get('network_domain')
    network_domain_id = None
    server_ids = list()
    datacenter = module.params.get('datacenter')
    return_data = return_object('antiaffinity_group')
    try:
        credentials = get_credentials(module)
    except ImportError as e:
        module.fail_json(msg='{0}'.format(e))

    # Check the region supplied is valid
    regions = get_regions()
    if module.params.get('region') not in regions:
        module.fail_json(msg='Invalid region. Regions must be one of {0}'.format(regions))

    if credentials is False:
        module.fail_json(msg='Could not load the user credentials')

    try:
        client = NTTMCPClient(credentials, module.params.get('region'))
    except NTTMCPAPIException as e:
        module.fail_json(msg=e.msg)

    # Get the CND
    if network_domain_name:
        try:
            network = client.get_network_domain_by_name(network_domain_name, datacenter)
            network_domain_id = network.get('id')
        except (KeyError, IndexError, AttributeError, NTTMCPAPIException):
            module.fail_json(msg='Could not find the Cloud Network Domain: {0}'.format(network_domain_name))

    # Get the servers
    for server in module.params.get('servers'):
        try:
            server = client.get_server_by_name(datacenter=datacenter,
                                               network_domain_id=network_domain_id,
                                               name=server)
            if server:
                server_ids.append(server.get('id'))
            else:
                module.warn(warning='Could not find the server - {0} in {1}'.format(server, datacenter))
        except (KeyError, IndexError, AttributeError):
            module.warn(warning='Could not find the server - {0} in {1}'.format(server, datacenter))

    try:
        if len(server_ids) == 0:
            return_data['antiaffinity_group'] = client.list_server_anti_affinity_groups(network_domain_id=network_domain_id)
        elif len(server_ids) == 1:
            return_data['antiaffinity_group'] = client.list_server_anti_affinity_groups(network_domain_id, server_ids[0])
        # Currently a server can belong to only a single antiaffinity group, while it doesn't do much more then the
        # case above today, this next section will handle any future situations were a server can belong to multiple
        # antiaffinity groups
        elif len(server_ids) == 2:
            return_data['antiaffinity_group'] = [client.get_anti_affinity_group_by_servers(server_ids[0], server_ids[1])]
        return_data['count'] = len(return_data['antiaffinity_group'])
        module.exit_json(data=return_data)
    except (KeyError, IndexError, AttributeError, NTTMCPAPIException) as e:
        module.fail_json(msg='Could not retrieve any Server Anti Affinity Groups - {0}'.format(e))
def main():
    """
    Main function

    :returns: Server Information
    """
    module = AnsibleModule(argument_spec=dict(
        auth=dict(type='dict'),
        region=dict(default='na', type='str'),
        datacenter=dict(required=True, type='str'),
        network_domain=dict(required=True, type='str'),
        server=dict(required=True, type='str'),
        type=dict(default='SCSI', required=False, choices=['SCSI']),
        controller_number=dict(required=False, type='int'),
        adapter_type=dict(default='LSI_LOGIC_PARALLEL',
                          choices=SCSI_ADAPTER_TYPES),
        state=dict(default='present', choices=['present', 'absent']),
        stop=dict(default=True, type='bool'),
        start=dict(default=True, type='bool'),
        wait=dict(required=False, default=True, type='bool'),
        wait_time=dict(required=False, default=1200, type='int'),
        wait_poll_interval=dict(required=False, default=30, type='int')),
                           supports_check_mode=True)

    try:
        credentials = get_credentials(module)
    except ImportError as e:
        module.fail_json(msg='{0}'.format(e))
    name = module.params.get('server')
    datacenter = module.params.get('datacenter')
    state = module.params.get('state')
    network_domain_name = module.params.get('network_domain')
    CORE['datacenter'] = module.params.get('datacenter')
    CORE['region'] = module.params.get('region')
    server_running = True
    stop_server = module.params.get('stop')
    start = module.params.get('start')
    server = {}

    # Check the region supplied is valid
    regions = get_regions()
    if module.params.get('region') not in regions:
        module.fail_json(
            msg='Invalid region. Regions must be one of {0}'.format(regions))

    if credentials is False:
        module.fail_json(msg='Could not load the user credentials')

    client = NTTMCPClient(credentials, module.params.get('region'))

    # Get the CND object based on the supplied name
    try:
        if network_domain_name is None:
            module.fail_json(
                msg=
                'No network_domain or network_info.network_domain was provided'
            )
        network = client.get_network_domain_by_name(datacenter=datacenter,
                                                    name=network_domain_name)
        network_domain_id = network.get('id')
    except (KeyError, IndexError, AttributeError, NTTMCPAPIException):
        module.fail_json(msg='Failed to find the Cloud Network Domain: {0}'.
                         format(network_domain_name))

    # Check if the Server exists based on the supplied name
    try:
        server = client.get_server_by_name(datacenter, network_domain_id, None,
                                           name)
        if server:
            server_running = server.get('started')
        else:
            module.fail_json(
                msg='Failed to find the server - {0}'.format(name))
    except (KeyError, IndexError, AttributeError, NTTMCPAPIException) as e:
        module.fail_json(
            msg='Failed attempting to locate any existing server - {0}'.format(
                e))

    # Setup the rest of the CORE dictionary to save passing data around
    CORE['network_domain_id'] = network_domain_id
    CORE['module'] = module
    CORE['client'] = client
    CORE['name'] = server.get('name')

    if state == 'present':
        controller = get_controller(module, server)
        if not controller:
            # Implement Check Mode
            if module.check_mode:
                module.exit_json(
                    msg=
                    'A new {0} controller of type {1} will be added to the server {2}'
                    .format(module.params.get('type'),
                            module.params.get('adapter_type'),
                            server.get('name')))
            if server_running and stop_server:
                server_command(module, client, server, 'stop')
                server_running = False
            elif server_running and not stop_server:
                module.fail_json(
                    msg=
                    'Controllers cannot be added while the server is running')
            add_controller(module, client, network_domain_id, server)
            if start and not server_running:
                server_command(module, client, server, 'start')
            server = client.get_server_by_name(datacenter, network_domain_id,
                                               None, name)
            module.exit_json(changed=True, data=server)
        else:
            module.exit_json(changed=False, data=server)
    elif state == 'absent':
        try:
            controller = get_controller(module, server)
            if not controller:
                module.fail_json(
                    msg='Server {0} has no {1} controller {2}'.format(
                        server.get('name'), module.params.get('type'),
                        module.params.get('controller_number')))
            # Implement Check Mode
            if module.check_mode:
                module.exit_json(
                    msg=
                    'The {0} controller of type {1} with ID {2} will be removed to the server {3}'
                    .format(module.params.get('type'),
                            controller.get('adapter_type'), controller.get(
                                'id'), server.get('name')))
            if server_running and stop_server:
                server_command(module, client, server, 'stop')
                server_running = False
            elif server_running and not stop_server:
                module.fail_json(
                    msg=
                    'Controllers cannot be removed while the server is running'
                )
            remove_controller(module, client, network_domain_id, server,
                              controller)
            # Introduce a pause to allow the API to catch up in more remote MCP locations
            sleep(10)
            if start and not server_running:
                server_command(module, client, server, 'start')
            server = client.get_server_by_name(datacenter, network_domain_id,
                                               None, name)
            module.exit_json(changed=True, data=server)
        except (KeyError, IndexError, AttributeError, NTTMCPAPIException) as e:
            module.fail_json(
                msg='Could not delete the controller - {0}'.format(e))
def main():
    """
    Main function
    :returns: Snapshot Information
    """
    module = AnsibleModule(argument_spec=dict(
        auth=dict(type='dict'),
        region=dict(default='na', type='str'),
        datacenter=dict(required=True, type='str'),
        network_domain=dict(required=False, type='str'),
        network_domain_id=dict(required=False, type='str'),
        server=dict(required=False, type='str'),
        server_id=dict(required=False, type='str'),
        plan=dict(required=False, default=None, type='str'),
        window=dict(required=False, default=None, type='int'),
        replication=dict(required=False, default=None, type='str'),
        take_snapshot=dict(required=False, default=False, type='bool'),
        state=dict(default='present', choices=['present', 'absent'])),
                           supports_check_mode=True)
    try:
        credentials = get_credentials(module)
    except ImportError as e:
        module.fail_json(msg='{0}'.format(e))

    state = module.params.get('state')
    datacenter = module.params.get('datacenter')
    network_domain_name = module.params.get('network_domain')
    server_name = module.params.get('server')
    server_id = module.params.get('server_id')
    plan = module.params.get('plan')
    window_id = None
    network_domain_id = module.params.get('network_domain_id')
    take_snapshot = module.params.get('take_snapshot')

    # Check the region supplied is valid
    regions = get_regions()
    if module.params.get('region') not in regions:
        module.fail_json(
            msg='Invalid region. Regions must be one of {0}'.format(regions))

    if credentials is False:
        module.fail_json(msg='Could not load the user credentials')

    try:
        client = NTTMCPClient(credentials, module.params.get('region'))
    except NTTMCPAPIException as e:
        module.fail_json(msg=e.msg)

    # Get the CND
    if server_id is None and network_domain_id is None:
        try:
            network = client.get_network_domain_by_name(
                name=network_domain_name, datacenter=datacenter)
            network_domain_id = network.get('id')
        except (KeyError, IndexError, AttributeError, NTTMCPAPIException) as e:
            module.fail_json(
                msg='Could not find the Cloud Network Domain: {0}'.format(e))

    # Check if the Server exists based on the supplied name
    try:
        if server_name is None and server_id is None:
            module.fail_json(
                msg='A valid value for server or server_id is required')
        if server_id:
            server = client.get_server_by_id(server_id=server_id)
        else:
            server = client.get_server_by_name(
                datacenter=datacenter,
                network_domain_id=network_domain_id,
                name=server_name)
        if not server.get('id'):
            raise NTTMCPAPIException('No server object found for {0}'.format(
                server_name or server_id))
        server_id = server.get('id')
    except (KeyError, IndexError, AttributeError, NTTMCPAPIException) as e:
        module.fail_json(
            msg='Could not locate any existing server - {0}'.format(e))

    if state == 'present':
        # Check for required arguments
        if (module.params.get('plan') is None or module.params.get('window') is
                None) and module.params.get('replication') is None:
            module.fail_json(msg='plan and window are required arguments')
        # Attempt to find the Window for the specified Service Plan
        if not module.check_mode and (module.params.get('window')
                                      or module.params.get('plan')):
            window_id = get_window_id(module, client)
        if not server.get('snapshotService'):
            if module.check_mode:
                module.exit_json(
                    msg=
                    'Input verified, Snapshots can be enabled for the server')
            enable_snapshot(module, client, server_id, plan, window_id,
                            module.params.get('replication'), take_snapshot)
        else:
            result = compare_snapshot(module, server.get('snapshotService'))
            if True in result:
                if result[0]:
                    update_snapshot(module, client, server_id, plan, window_id)
                if result[1]:
                    enable_replication(module, client, server_id,
                                       module.params.get('replication'))
                module.exit_json(
                    changed=True,
                    msg=
                    'Snapshot Service configuration has been successfully updated'
                )
            else:
                module.exit_json(msg='No update required.')
    elif state == 'absent':
        if not server.get('snapshotService'):
            module.exit_json(
                msg='Snapshots are not currently configured for this server')
        if module.check_mode:
            module.exit_json(
                msg=
                'The Snapshot service and all associated snapshots will be removed from this server'
            )
        if module.params.get('replication'):
            disable_replication(module, client, server_id)
        else:
            disable_snapshot(module, client, server_id)
        module.exit_json(msg='Snapshot replication successfully disabled')