Example #1
0
def check_if_trusted(ip, trusted_list):
    try:
        _ip = ip_addr(ip)
        for trusted in trusted_list:
            if _ip in ip_net(trusted):
                return True
        else:
            return False
    except:
        return False
Example #2
0
def main():
    """
    Main function

    :returns: SNAT exclusion 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'),
        id=dict(default=None, required=False, type='str'),
        description=dict(default=None, required=False, type='str'),
        cidr=dict(default=None, required=False, type='str'),
        new_cidr=dict(default=None, required=False, type='str'),
        state=dict(default='present', choices=['present', 'absent',
                                               'restore'])),
                           supports_check_mode=True)
    try:
        credentials = get_credentials(module)
    except ImportError as e:
        module.fail_json(msg='{0}'.format(e))
    network_domain_name = module.params.get('network_domain')
    datacenter = module.params.get('datacenter')
    state = module.params.get('state')
    snat = new_network_cidr = network_cidr = None
    snats = []

    # Check Imports
    if not HAS_IPADDRESS:
        module.fail_json(msg='Missing Python module: ipaddress')

    # 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'])

    # Check to see the CIDR provided is valid
    if module.params.get('cidr'):
        try:
            network_cidr = ip_net(unicode(module.params.get('cidr')))
        except (AddressValueError, ValueError) as e:
            module.fail_json(msg='Invalid network CIDR format {0}: {1}'.format(
                module.params.get('cidr'), e))
        if network_cidr.version != 4:
            module.fail_json(
                msg='The cidr argument must be in valid IPv4 CIDR notation')
    if module.params.get('new_cidr'):
        try:
            new_network_cidr = ip_net(unicode(module.params.get('new_cidr')))
        except (AddressValueError, ValueError) as e:
            module.fail_json(msg='Invalid network CIDR format {0}: {1}'.format(
                module.params.get('new_cidr'), e))
        if new_network_cidr.version != 4:
            module.fail_json(
                msg='The new_cidr argument must be in valid IPv4 CIDR notation'
            )

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

    # Check if a SNAT exclusion already exists for this ID
    if not state == 'restore':
        try:
            if module.params.get('id'):
                snat = client.get_snat_exclusion(module.params.get('id'))
            if not snat and network_cidr:
                # If no matching routes were found for the name check to see if the supplied network parameters match a rule with a different name
                snats = client.list_snat_exclusion(
                    network_domain_id=network_domain_id,
                    network=str(network_cidr.network_address),
                    prefix=network_cidr.prefixlen)
                if len(snats) == 1:
                    snat = snats[0]
        except (IndexError, AttributeError, NTTMCPAPIException) as e:
            module.fail_json(
                msg='Failed to get a list of existing SNAT exclusions - {0}'.
                format(e))
    try:
        if state == 'present':
            if not snat:
                # Implement Check Mode
                if module.check_mode:
                    module.exit_json(
                        msg='A new SNAT exclusion will be created for {0}'.
                        format(str(network_cidr)))
                create_snat_exclusion(module, client, network_domain_id,
                                      network_cidr)
            else:
                # SNAT exclusions cannot be updated. The old one must be removed and a new one created with the new parameters
                if compare_snat_exclusion(module, new_network_cidr, snat):
                    delete_snat_exclusion(module, client, snat.get('id'))
                    create_snat_exclusion(module, client, network_domain_id,
                                          new_network_cidr)
                module.exit_json(data=snat)
        elif state == 'restore':
            client.restore_snat_exclusion(network_domain_id)
            module.exit_json(
                changed=True,
                msg='Successfully restored the default SNAT exclusions')
        elif state == 'absent':
            if snat:
                # Implement Check Mode
                if module.check_mode:
                    module.exit_json(
                        msg=
                        'An existing SNAT exclusion was found for {0} and will be removed'
                        .format(snat.get('id')))
                delete_snat_exclusion(module, client, snat.get('id'))
                module.exit_json(changed=True,
                                 msg='Successfully deleted the SNAT exclusion')
            else:
                module.exit_json(msg='No existing SNAT exclusion was matched')
    except (KeyError, IndexError, NTTMCPAPIException) as e:
        module.fail_json(
            msg='Could not update the SNAT exclusion - {0}'.format(e))
Example #3
0
def main():
    """
    Main function
    :returns: Static Route 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'),
            name=dict(default=None, required=False, type='str'),
            cidr=dict(default=None, required=False, type='str'),
            next_hop=dict(default=None, required=False, type='str'),
            version=dict(default=4, required=False, type='int', choices=[4, 6])
        ),
        supports_check_mode=True
    )
    try:
        credentials = get_credentials(module)
    except ImportError as e:
        module.fail_json(msg='{0}'.format(e))
    network_domain_name = module.params.get('network_domain')
    datacenter = module.params.get('datacenter')
    name = module.params.get('name')
    routes = []
    route = network_cidr = None

    # Check Imports
    if not HAS_IPADDRESS:
        module.fail_json(msg='Missing Python module: ipaddress')

    # 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'))

    # Check to see the CIDR provided is valid
    if module.params.get('cidr'):
        try:
            network_cidr = ip_net(unicode(module.params.get('cidr')))
        except (AddressValueError, ValueError) as e:
            module.fail_json(msg='Invalid network CIDR format {0}: {1}'.format(module.params.get('cidr'), e))

    # 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, NTTMCPAPIException):
        module.fail_json(msg='Could not find the Cloud Network Domain: {0}'.format(network_domain_name))

    # Check if a route already exists for this name
    try:
        if name:
            routes = client.list_static_routes(network_domain_id=network_domain_id, name=name)
        if not routes and module.params.get('cidr'):
            # If no matching routes were found for the name check to see if the supplied
            # network parameters match a rule with a different name
            routes = client.list_static_routes(network_domain_id=network_domain_id,
                                               name=None,
                                               network=str(network_cidr.network_address),
                                               prefix=network_cidr.prefixlen,
                                               next_hop=module.params.get('next_hop'))
            if len(routes) == 1:
                route = routes[0]
        elif len(routes) == 1:
            route = routes[0]
    except (KeyError, IndexError, AttributeError, NTTMCPAPIException) as e:
        module.fail_json(msg='Failed to get a list of existing Static Routes - {0}'.format(e))

    if route:
        return_data = return_object('route')
        return_data = return_object('route')
        return_data['count'] = len(return_data.get('route'))
        module.exit_json(data=route)
    list_static_routes(module, client, network_domain_id, network_cidr)
def main():
    """
    Main function

    :returns: Static route 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'),
            name=dict(default=None, required=False, type='str'),
            description=dict(default=None, required=False, type='str'),
            cidr=dict(default=None, required=False, type='str'),
            next_hop=dict(default=None, required=False, type='str'),
            state=dict(default='present', choices=['present', 'absent', 'restore'])
        ),
        supports_check_mode=True
    )
    try:
        credentials = get_credentials(module)
    except ImportError as e:
        module.fail_json(msg='{0}'.format(e))
    name = module.params.get('name')
    network_domain_name = module.params.get('network_domain')
    datacenter = module.params.get('datacenter')
    state = module.params.get('state')
    route = network_cidr = None
    routes = []

    # Check Imports
    if not HAS_IPADDRESS:
        module.fail_json(msg='Missing Python module: ipaddress')

    # 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')

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

    # Check to see the CIDR provided is valid
    if module.params.get('cidr'):
        try:
            network_cidr = ip_net(unicode(module.params.get('cidr')))
        except (AddressValueError, ValueError) as e:
            module.fail_json(msg='Invalid network CIDR format {0}: {1}'.format(module.params.get('cidr'), e))

    # Get a list of existing CNDs and check if the name already exists
    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='Failed to get a list of Cloud Network Domains - {0}'.format(e))

    # Check if a route already exists for this name
    if state != 'restore':
        try:
            if name:
                routes = client.list_static_routes(network_domain_id=network_domain_id, name=name)
            if not routes and network_cidr:
                # If no matching routes were found for the name check to see if the supplied
                # network parameters match a rule with a different name
                routes = client.list_static_routes(network_domain_id=network_domain_id,
                                                   name=None,
                                                   network=str(network_cidr.network_address),
                                                   prefix=network_cidr.prefixlen,
                                                   next_hop=module.params.get('next_hop'))
                if len(routes) == 1:
                    route = routes[0]
            elif len(routes) == 1:
                route = routes[0]
        except (KeyError, IndexError, AttributeError, NTTMCPAPIException) as e:
            module.fail_json(msg='Failed to get a list of existing Static Routes - {0}'.format(e))

    try:
        if state == 'present':
            if not route:
                # Implement Check Mode
                if module.check_mode:
                    module.exit_json(msg='A new static route will be created for {0}'.format(str(network_cidr)))
                create_static_route(module, client, network_domain_id, network_cidr)
            else:
                # Static Routes cannot be updated. The old one must be removed and a new one created with the new parameters
                if compare_static_route(module, network_cidr, route):
                    delete_static_route(module, client, route.get('id'))
                    create_static_route(module, client, network_domain_id, network_cidr)
                module.exit_json(data=route)
        elif state == 'restore':
            # Implement Check Mode
            if module.check_mode:
                module.exit_json(msg='The routes for Network Domain {0} will be restored to defaults'.format(
                    module.params.get('network_domain')))
            client.restore_static_routes(network_domain_id)
            module.exit_json(changed=True, msg='Successfully restored the default Static Routes')
        elif state == 'absent':
            if route:
                # Implement Check Mode
                if module.check_mode:
                    module.exit_json(msg='An existing static route was found for {0} and will be removed'.format(
                        route.get('name')))
                delete_static_route(module, client, route.get('id'))
                module.exit_json(changed=True, msg='Successfully deleted the Static Route rule')
            else:
                module.exit_json(msg='No existing static route was matched')
    except (KeyError, IndexError, AttributeError, NTTMCPAPIException) as e:
        module.fail_json(msg='Could not update the static route - {0}'.format(e))
def main():
    """
    Main function

    :returns: Firewall rule Information
    """
    module = AnsibleModule(argument_spec=dict(
        auth=dict(type='dict'),
        region=dict(default='na', type='str'),
        datacenter=dict(required=True, type='str'),
        name=dict(required=False, type='str'),
        network_domain=dict(required=True, type='str'),
        action=dict(default='ACCEPT_DECISIVELY',
                    choices=['ACCEPT_DECISIVELY', 'DROP']),
        version=dict(required=False, default='IPV4', choices=['IPV4', 'IPV6']),
        protocol=dict(default='TCP', choices=['TCP', 'UDP', 'IP', 'ICMP']),
        src_cidr=dict(required=False, type='str'),
        src_ip_list=dict(required=False, type='str'),
        dst_cidr=dict(required=False, type='str'),
        dst_ip_list=dict(required=False, type='str'),
        src_port_start=dict(required=False, default=None, type='str'),
        src_port_end=dict(required=False, default=None, type='str'),
        src_port_list=dict(required=False, default=None, type='str'),
        dst_port_start=dict(required=False, default=None, type='str'),
        dst_port_end=dict(required=False, default=None, type='str'),
        dst_port_list=dict(required=False, default=None, type='str'),
        enabled=dict(default=True, type='bool'),
        position=dict(default='LAST',
                      choices=['FIRST', 'LAST', 'BEFORE', 'AFTER']),
        position_to=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))
    fw_rule_exists = None
    name = module.params['name']
    network_domain_name = module.params['network_domain']
    datacenter = module.params['datacenter']
    state = module.params['state']
    src_cidr = dst_cidr = None

    # Check Imports
    if not HAS_IPADDRESS:
        module.fail_json(msg='Missing Python module: ipaddress')

    # 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')

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

    # Check to see the CIDR provided is valid
    if module.params.get('src_cidr'):
        try:
            src_cidr = ip_net(unicode(module.params.get('src_cidr')))
        except (AddressValueError, ValueError) as e:
            module.fail_json(msg='Invalid source CIDR format {0}: {1}'.format(
                module.params.get('src_cidr'), e))
    if module.params.get('dst_cidr'):
        try:
            dst_cidr = ip_net(unicode(module.params.get('dst_cidr')))
        except (AddressValueError, ValueError) as e:
            module.fail_json(
                msg='Invalid destination CIDR format {0}: {1}'.format(
                    module.params.get('dst_cidr'), e))

    # 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 e:
        module.fail_json(
            msg='Failed to find the Cloud Network Domains - {0}'.format(e),
            exception=traceback.format_exc())

    # If a firewall rule name is provided try and locate the rule
    if name:
        try:
            fw_rule_exists = client.get_fw_rule_by_name(
                network_domain_id, name)
        except NTTMCPAPIException as e:
            module.fail_json(
                msg='Could not locate the existing firewall rule - {0}'.format(
                    e),
                exception=traceback.format_exc())

    try:
        if state == 'present':
            if fw_rule_exists:
                update_fw_rule(module, client, network_domain_id,
                               fw_rule_exists, src_cidr, dst_cidr)
            else:
                # Implement check_mode
                if module.check_mode:
                    module.exit_json(msg='This firewall rule will be created',
                                     data=module.params)
                create_fw_rule(module, client, network_domain_id, src_cidr,
                               dst_cidr)
        elif state == 'absent':
            if not fw_rule_exists:
                module.exit_json(
                    msg='The firewall rule {0} was not found'.format(name))
            # Implement check_mode
            if module.check_mode:
                module.exit_json(msg='This firewall rule will be removed',
                                 data=fw_rule_exists)
            delete_fw_rule(module, client, network_domain_id, name)
    except NTTMCPAPIException as e:
        module.fail_json(
            msg='Could not operate on the firewall rule - {0}'.format(e),
            exception=traceback.format_exc())
def main():
    """
    Main function
    :returns: SNAT 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'),
                                              id=dict(default=None,
                                                      required=False,
                                                      type='str'),
                                              cidr=dict(default=None,
                                                        required=False,
                                                        type='str')),
                           supports_check_mode=True)
    try:
        credentials = get_credentials(module)
    except ImportError as e:
        module.fail_json(msg='{0}'.format(e))
    network_domain_name = module.params.get('network_domain')
    datacenter = module.params.get('datacenter')
    snat_id = module.params.get('id')
    network_cidr = None

    # Check Imports
    if not HAS_IPADDRESS:
        module.fail_json(msg='Missing Python module: ipaddress')

    # 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'))

    # Check to see the CIDR provided is valid
    if module.params.get('cidr'):
        try:
            network_cidr = ip_net(unicode(module.params.get('cidr')))
        except (AddressValueError, ValueError) as e:
            module.fail_json(msg='Invalid network CIDR format {0}: {1}'.format(
                module.params.get('cidr'), e))
        if network_cidr.version != 4:
            module.fail_json(
                msg='The cidr argument must be in valid IPv4 CIDR notation')

    # 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):
        module.fail_json(msg='Could not find the Cloud Network Domain: {0}'.
                         format(network_domain_name))

    if snat_id or network_cidr:
        get_snat_exclusion(module, client, network_domain_id, snat_id,
                           network_cidr)
    else:
        list_snat_exclusion(module, client, network_domain_id)
Example #7
0
def create_vlan(module, client, network_domain_id):
    """
    Create a VLAN

    :arg module: The Ansible module instance
    :arg client: The CC API client instance
    :arg network_domain_id: The UUID of the network domain
    :arg ipv4_cidr: The IPv4 network address and mask represented as an ipaddress object
    :returns: VLAN Object
    """
    return_data = return_object('vlan')
    ipv4_cidr = None

    # Determine the IPv4 network and mask
    try:
        ipv4_cidr = ip_net(unicode(module.params.get('ipv4_cidr')))
    except (AddressValueError, ValueError) as e:
        module.fail_json(msg='Invalid IPv4 CIDR format {0}: {1}'.format(module.params.get('ipv4_cidr'), e))

    datacenter = module.params['datacenter']
    name = module.params['name']
    vlan_type = module.params['vlan_type']
    ipv4_network = str(ipv4_cidr.network_address)
    ipv4_prefix = str(ipv4_cidr.prefixlen)
    wait = module.params['wait']

    if vlan_type == 'attachedVlan':
        if not module.params.get('attached_vlan_gw'):
            module.fail_json(msg='An attached_vlan_gw value [LOW/HIGH] is required for a new Attached VLAN.')
    elif vlan_type == 'detachedVlan':
        if not module.params.get('detached_vlan_gw'):
            module.fail_json(msg='A detached_vlan_gw value (e.g. 10.0.0.1) is reuiqred for a new Detached VLAN.')

    try:
        if vlan_type == 'attachedVlan':
            gateway = module.params['attached_vlan_gw']
            result = client.create_vlan(
                networkDomainId=network_domain_id,
                name=name,
                description=module.params['description'],
                privateIpv4NetworkAddress=ipv4_network,
                privateIpv4PrefixSize=ipv4_prefix,
                attachedVlan=True,
                attachedVlan_gatewayAddressing=gateway)
            new_vlan_id = result['info'][0]['value']
        elif vlan_type == 'detachedVlan':
            gateway = module.params['detached_vlan_gw']
            result = client.create_vlan(
                networkDomainId=network_domain_id,
                name=name,
                description=module.params['description'],
                privateIpv4NetworkAddress=ipv4_network,
                privateIpv4PrefixSize=ipv4_prefix,
                detachedVlan=True,
                detachedVlan_ipv4GatewayAddress=gateway)
            new_vlan_id = result['info'][0]['value']
    except (KeyError, IndexError, NTTMCPAPIException) as exc:
        module.fail_json(msg='Could not create the VLAN - {0}'.format(exc), exception=traceback.format_exc())

    if wait:
        wait_result = wait_for_vlan(module, client, name, datacenter, network_domain_id, 'NORMAL')
        if wait_result is None:
            module.fail_json(msg='Could not verify the VLAN creation was successful. Check the UI.')
        return_data['vlan'] = wait_result
    else:
        return_data['vlan'] = {'id': new_vlan_id}

    module.exit_json(changed=True, data=return_data['vlan'])