Example #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'),
        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 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))
Example #3
0
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(default=None, required=False, type='str'),
        id=dict(default=None, required=False, type='str'),
        name=dict(default=None, required=False, type='str'),
        new_name=dict(default=None, required=False, type='str'),
        description=dict(default=None, required=False, type='str'),
        vlan=dict(default=None, required=False, type='str'),
        force=dict(default=False, required=False, type='bool'),
        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 = None
    vlan = sec_group = 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
    if state == 'present':
        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 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, NTTMCPAPIException):
                module.fail_json(
                    msg='Could not find the VLAN - {0} in {1}'.format(
                        module.params.get('vlan'), datacenter))
    # Try and find any existing Security Group
    try:
        if module.params.get('name'):
            sec_group = client.list_security_groups(
                network_domain_id=network_domain_id,
                name=module.params.get('name'),
                group_type=None,
                server_id=None,
                vlan_id=vlan.get('id', None))[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()
    except (KeyError, IndexError, AttributeError, NTTMCPAPIException):
        pass

    try:
        if state == 'present':
            # Handle case where security Group already exists
            if not sec_group:
                # Implement Check Mode
                if module.check_mode:
                    module.exit_json(
                        msg='A new {0} Security Group will be created'.format(
                            'VLAN' if module.params.get('vlan') else 'Server'))
                sec_group = create_security_group(module, client,
                                                  network_domain_id,
                                                  vlan.get('id'))
            else:
                try:
                    if not compare_security_group(module, sec_group):
                        module.exit_json(data=sec_group)
                    sec_group = update_security_group(module, client,
                                                      sec_group)
                except (NTTMCPAPIException) as e:
                    module.fail_json(
                        msg='Failed to update the Security Group - {0}'.format(
                            e))
            module.exit_json(changed=True, data=sec_group)
        # 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')))
            if module.params.get('force'):
                delete_security_group_members(module, client, sec_group,
                                              group_type)
            result = client.delete_security_group(sec_group.get('id'))
            if result.get('responseCode') == 'OK':
                module.exit_json(
                    changed=True,
                    msg='The Security Group was successfully removed')
            module.fail_json(msg='Could not remove the Security Group - {0}'.
                             format(result.content))
    except (KeyError, IndexError, AttributeError, NTTMCPAPIException) as e:
        module.fail_json(
            msg='Could not retrieve any Security Groups - {0}'.format(e))