# find the objectId of the Scope with the name of the Transport Zone
vdn_scopes = client_session.read('vdnScopes', 'read')['body']
vdn_scope_dict_list = [scope_dict for scope_dict in vdn_scopes['vdnScopes'].items()]
vdn_scope = [scope[1]['objectId'] for scope in vdn_scope_dict_list if scope[1]['name'] == TRANSPORT_ZONE][0]

# get a template dict for the lswitch create
lswitch_create_dict = client_session.extract_resource_body_schema('logicalSwitches', 'create')
client_session.view_body_dict(lswitch_create_dict)

# fill the details for the new lswitch in the body dict
lswitch_create_dict['virtualWireCreateSpec']['controlPlaneMode'] = 'UNICAST_MODE'
lswitch_create_dict['virtualWireCreateSpec']['name'] = 'TestLogicalSwitch1'
lswitch_create_dict['virtualWireCreateSpec']['tenantId'] = 'Tenant1'

# create new lswitch
new_ls = client_session.create('logicalSwitches', uri_parameters={'scopeId': vdn_scope},
                               request_body_dict=lswitch_create_dict)
client_session.view_response(new_ls)

# list all logical switches
all_lswitches = client_session.read('logicalSwitchesGlobal')
client_session.view_response(all_lswitches)

# list all logical switches in transport Zone
tz_lswitches = client_session.read('logicalSwitches', uri_parameters={'scopeId': vdn_scope})
client_session.view_response(tz_lswitches)

# Read the properties of the new logical switch
new_ls_props = client_session.read('logicalSwitch', uri_parameters={'virtualWireID': new_ls['objectId']})
client_session.view_response(new_ls_props)

time.sleep(5)
示例#2
0
__author__ = 'yfauser'

from tests.config import *
from nsxramlclient.client import NsxClient
import time


client_session = NsxClient(nsxraml_file, nsxmanager, nsx_username, nsx_password, debug=True)

ipset_dict = client_session.extract_resource_body_schema('ipsetCreate', 'create')
ipset_dict['ipset']['name'] = 'Test'
ipset_dict['ipset']['value'] = '192.168.1.0/24'
ipset_dict['ipset']['inheritanceAllowed'] = 'True'

newipset_return = client_session.create('ipsetCreate', uri_parameters={'scopeMoref': 'globalroot-0'},
                                        request_body_dict=ipset_dict)

newipset = dict(client_session.read('ipset', uri_parameters={'ipsetId': newipset_return['objectId']})['body'])

newipset['ipset']['value'] = '10.0.0.0/16'
newipset['ipset']['inheritanceAllowed'] = 'False'

time.sleep(10)

client_session.update('ipset', uri_parameters={'ipsetId': newipset_return['objectId']}, request_body_dict=newipset)

client_session.read('ipsetList', uri_parameters={'scopeMoref': 'globalroot-0'})

time.sleep(10)

client_session.delete('ipset', uri_parameters={'ipsetId': newipset_return['objectId']})
def main():
    """main function:
         Accept arguments from Ansible
         Create an nsxramlclient session
         Depending on the mode of operation call the specific function
    """
    module = AnsibleModule(argument_spec=
    dict(
        nsxmanager_spec=dict(required=True, type="dict"),
        edge_name=dict(required=False),
        edge_id=dict(required=False),
        mode=dict(required=True, choices=["create", "append", "query", "delete", "set_default_action", "reset"]),
        source=dict(required=False, type="dict"),
        destination=dict(required=False, type="dict"),
        action=dict(required=False, choices=["accept", "deny", "reject"]),
        name=dict(required=False),
        description=dict(required=False),
        application=dict(required=False, type="dict"),        
        rule_id=dict(required=False),
        direction=dict(required=False, choices=["in", "out"]),
        global_config=dict(required=False, type="dict"),
        rules=dict(required=False, type="list"),
        default_action=dict(required=False, choices=["accept", "deny", "reject"]),
    ), required_one_of=[["edge_name", "edge_id"]])

    try:
        client_session = NsxClient(module.params['nsxmanager_spec']['raml_file'],
                                   module.params['nsxmanager_spec']['host'],
                                   module.params['nsxmanager_spec']['user'],
                                   module.params['nsxmanager_spec']['password'])
    except:
        module.fail_json(msg="Could not connect to the NSX manager")

    

    edge_name = module.params.get("edge_name", None)
    if not edge_name:
        edge_id = module.params["edge_id"]
    else:
        edge_id = get_edge_id(client_session, edge_name)
        if not edge_id:
            module.fail_json(msg="The edge with the name %s does not exist." % (edge_name))

    mode = module.params["mode"]
    action = module.params.get("action", None)
    name = module.params.get("name", None)
    rule_id = module.params.get("rule_id", None)
    application = module.params.get("application", None)
    source = module.params.get("source", None)
    destination = module.params.get("destination", None)
    description = module.params.get("description", None)
    direction = module.params.get("direction", None)
    rules = module.params.get("rules", None)
    global_config = module.params.get("global_config", None)
    default_action = module.params.get("default_action", None)

    if mode == "create":
        #'create' mode:
        #   1)Create a Firewall object out of the given rules,global_config and default_action
        #   2)Get the resource body to be sent
        #   3)Send the resource body to the NSX Manager
        if not rules:
            module.fail_json(msg="The parameter 'rules' is required in order to create the firewall rules")

        firewall_rules = []
        for rule in rules:
            firewall_rules.append(FirewallRule(rule))
  
        F = Firewall(firewall_rules, global_config, default_action)
        resource_body = F.get_resource_body()


        resp = client_session.update("nsxEdgeFirewallConfig", uri_parameters={"edgeId": edge_id},
                                     request_body_dict=resource_body)
        if resp["status"] == 204:
            module.exit_json(changed=True, msg="Successfully created the rules for the edge with ID %s" % (edge_id))
        else:
            module.fail_json(msg="The resource could not be created")


    elif mode == "append":
        #'append' mode:
        #   1)Check if the rule to be added already exists in the firewall
        #   2)If yes, exit
        #   3)If no, create the resource body and send the request to the NSX Manager

        if not action:
            module.fail_json(msg="The 'action' attribute is mandatory while appending a new rule")


        rule_to_be_added = FirewallRule({"name":name, "action":action, "description":description, "source":source, "destination":destination, "application":application, "direction":direction})

        current_rules = [FirewallRule(rule) for rule in query_firewall_rules(client_session, edge_id)]
        current_hashes = [hash(rule) for rule in current_rules]
        if hash(rule_to_be_added) in current_hashes:
            module.exit_json(changed=False, msg="The given rule already exists in the firewall")

        resource_body = append_api_resource_body
        resource_body["firewallRules"]["firewallRule"] = rule_to_be_added.get_rule() 

        resp = client_session.create("firewallRules", uri_parameters={"edgeId": edge_id},
                                     request_body_dict=resource_body)
        if resp["status"] == 201:
            module.exit_json(changed=True, meta={"ruleId": resp["objectId"]})
        else:
            module.fail_json(msg="The resource could not be created")

    elif mode == "query":
        #'query' mode:
        #   1)Query the rules existing for the given edge
        #   2)Display the results (requires <result>.split("\n") in Ansible as Ansible does not support printing newlines
        rules = query_firewall_rules(client_session, edge_id)
        print_str = display_firewall_rules(rules)

        module.exit_json(changed=False, meta={"output": print_str})

    elif mode == "delete":
        #'delete' mode:
        #   - Delete the rule with the given rule_id
        if not rule_id:
            module.fail_json(msg="The parameter 'rule_id' is required to delete a given rule")
        resp = client_session.delete("firewallRule", uri_parameters={"ruleId": rule_id, "edgeId": edge_id})
        if resp["status"] == 204:
            module.exit_json(changed=True, msg="Rule with the ID %s successfully deleted" % (rule_id))
        else:
            module.fail_json(msg="Could not delete the rule with ID %s. Make sure that the rule exists" % (rule_id))

    elif mode == "set_default_action":
        #'set_default_action' mode:
        #   - Sets the default action for the firewall(can be 'accept', 'deny' or 'reject')
        if not default_action:
            module.fail_json(msg="The parameter 'default_action' is required to set the default action")

        resource_body = default_action_resource_body
        resource_body["firewallDefaultPolicy"]["action"] = default_action

        resp = client_session.update("defaultFirewallPolicy", uri_parameters={"edgeId": edge_id},
                                     request_body_dict=resource_body)
        if resp["status"] == 204:
            module.exit_json(changed=True, msg="Successfully updated the firewall config")
        else:
            module.fail_json(msg="The resource could not be updated")

    elif mode == "reset":
        #'reset' mode:
        #   - Resets the firewall by deleting all the existing rules
        resp = client_session.delete("nsxEdgeFirewallConfig",  uri_parameters={"edgeId": edge_id})
        if resp["status"] == 204:
            module.exit_json(msg="Successfully reset the firewall configuration for the edge with ID %s" %(edge_id), changed=True)
        else:
            module.fail_json(msg="Could not reset the firewall rules for the edge with ID %s" %(edge_id))
class NSX():
    '''
    NSX Class: Following functionality are implemented.
    1. Create and get a hardware gateway.
    2. Create and get a hardware binding.
    3. Create and get a logical switch.
    '''

    def __init__(self, **kwargs):
        self._nsxraml_file = kwargs.pop('raml_file')
        self._nsx_password = kwargs.pop('password')
        self._nsx_username = kwargs.pop('username')
        self._nsxmanager = kwargs.pop('ip')
        self._client_session = NsxClient(self._nsxraml_file,
                                         self._nsxmanager, self._nsx_username, self._nsx_password)
        self.logger = logging.getLogger(__name__)
        self._cert = ""
        self._bfd = True
        self._name = ""

    def add_hwdevice_cert(self, **kwargs):
        self._cert = str(kwargs.pop('cert'))
        self._bfd = kwargs.pop('bfd', True)
        self._name = str(kwargs.pop('name'))
        self.logger.info("Creating Hardware Device: %s", self._name)
        hw_dict = self._client_session.extract_resource_body_example('vdnHardwareGateway', 'create')
        hw_dict['hardwareGatewaySpec']['name'] = self._name
        hw_dict['hardwareGatewaySpec']['certificate'] = self._cert
        hw_dict['hardwareGatewaySpec']['bfdEnabled'] = self._bfd

        hw = self._client_session.create('vdnHardwareGateway', request_body_dict=hw_dict)

        if 200 in hw.values():
            return True
        return False

    def get_hwdevice(self):
        self.logger.info("Reading Hardware Gateway Certificates")
        hw = self._client_session.read('vdnHardwareGateway')

        if 200 in hw.values():
            return hw['body']['list']
        else:
            return False

    def get_hwgateway_biding(self, **kwargs):
        lswitch_name = str(kwargs.pop('lswitch_name'))
        self.logger.info("Reading Hardware Bidings for the logical switch id: %r", lswitch_name)
        objid = self.get_lswitch_objectId(lswitch_name=lswitch_name)
        if objid:
            hw_bindings = self._client_session.read('vdnHardwareBinding',
                                                    uri_parameters={'virtualWireID': objid})
            if 200 in hw_bindings.values():
                return hw_bindings['body']['list']
            else:
                return False
        else:
            self.logger.info("Logical Switch: %r entry not found", lswitch_name)
            return False

    def get_hwdevice_objectId(self, **kwargs):
        hwdevice_name = str(kwargs.pop('hwdevice_name'))

        hwdevice = self.get_hwdevice()
        objid = None
        hw_list = hwdevice['hardwareGateway']
        if isinstance(hw_list, dict):
            if hw_list['name'] == hwdevice_name:
                objid = hw_list['objectId']
        else:
            for i in hw_list:
                if i['name'] == hwdevice_name:
                    objid = i['objectId']
                    break
        return objid

    def get_logicalswitch(self):

        self.logger.info("Reading list of Logical Switches")
        lswitch = self._client_session.read('logicalSwitchesGlobal')
        if 200 in lswitch.values():
            return lswitch['body']['virtualWires']
        else:
            return False

    def create_logicalswitch(self, **kwargs):
        lswitch_name = str(kwargs.pop('name'))
        zone = str(kwargs.pop('zone', 'TZ1'))
        controlplan_mode = str(kwargs.pop('controlplan_mode', 'UNICAST_MODE'))
        tenant = str(kwargs.pop('tenant', 'vsphere.local'))
        self.logger.info("Crating Logical Switch: %r", lswitch_name)

        # find the objectId of the Scope with the name of the Transport Zone
        vdn_scopes = self._client_session.read('vdnScopes', 'read')['body']
        vdn_scope_dict_list = [scope_dict for scope_dict in vdn_scopes['vdnScopes'].items()]
        vdn_scope = [scope[1]['objectId']
                     for scope in vdn_scope_dict_list if scope[1]['name'] == zone][0]

        # get a template dict for the lswitch create
        lswitch_create_dict = self._client_session.extract_resource_body_example('logicalSwitches',
                                                                                 'create')
        # self._client_session.view_body_dict(lswitch_create_dict)

        # fill the details for the new lswitch in the body dict
        lswitch_create_dict['virtualWireCreateSpec']['controlPlaneMode'] = controlplan_mode
        lswitch_create_dict['virtualWireCreateSpec']['name'] = lswitch_name
        lswitch_create_dict['virtualWireCreateSpec']['tenantId'] = tenant

        # create new lswitch
        new_ls = self._client_session.create('logicalSwitches',
                                             uri_parameters={'scopeId': vdn_scope},
                                             request_body_dict=lswitch_create_dict)
        # self._client_session.view_response(new_ls)

        if 200 in new_ls.values():
            return True
        else:
            return False

    def get_lswitch_objectId(self, **kwargs):
        lswitch_name = str(kwargs.pop('lswitch_name'))
        lswitch = self.get_logicalswitch()
        objid = None
        sw_list = lswitch['dataPage']['virtualWire']
        if isinstance(sw_list, dict):
            if sw_list['name'] == lswitch_name:
                objid = sw_list['objectId']
        else:
            for i in sw_list:
                if i['name'] == lswitch_name:
                    objid = i['objectId']
                    break
        return objid

    def create_hardwarebinding(self, **kwargs):

        lswitch_name = str(kwargs.pop('lswitch_name'))
        vlan = str(kwargs.pop('vlan'))
        port_name = str(kwargs.pop('port_name'))
        switch_name = str(kwargs.pop('switch_name'))
        hardware_gateway_name = str(kwargs.pop('hardware_gateway_name'))
        self.logger.info("Creating Hardware bindings for the logical switch: %r", lswitch_name)
        hwdevice_id = self.get_hwdevice_objectId(hwdevice_name=hardware_gateway_name)
        if not hwdevice_id:
            self.logger.info("Hardware device entry: %r entry not found", hardware_gateway_name)
            return False
        objectId = self.get_lswitch_objectId(lswitch_name=lswitch_name)
        if objectId:
            hw_dict = self._client_session.extract_resource_body_example('vdnHardwareBinding',
                                                                         'create')
            hw_dict['hardwareGatewayBinding']['hardwareGatewayId'] = hwdevice_id
            hw_dict['hardwareGatewayBinding']['portName'] = port_name
            hw_dict['hardwareGatewayBinding']['vlan'] = vlan
            hw_dict['hardwareGatewayBinding']['switchName'] = switch_name
            hw = self._client_session.create('vdnHardwareBinding',
                                             uri_parameters={'virtualWireID': objectId},
                                             request_body_dict=hw_dict)

            if 200 in hw.values():
                return True
            else:
                return False

        else:
            self.logger.info("Logical Switch: %r entry not found", lswitch_name)
            return False
示例#5
0
from nsxramlclient.client import NsxClient
import time

client_session = NsxClient(nsxraml_file,
                           nsxmanager,
                           nsx_username,
                           nsx_password,
                           debug=True)

macset_dict = client_session.extract_resource_body_schema(
    'macsetScopeCreate', 'create')
macset_dict['macset']['name'] = 'test0'

# CREATE macset on scope
newmacset_return = client_session.create(
    'macsetScopeCreate',
    uri_parameters={'scopeId': 'globalroot-0'},
    request_body_dict=macset_dict)

# READ macset by ID
newmacset = dict(
    client_session.read(
        'macset', uri_parameters={'macsetId':
                                  newmacset_return['objectId']})['body'])

# UPDATE macset by ID
newmacset['macset']['name'] = 'test1'
newmacset['macset']['revision'] = '1'
newmacset['macset']['value'] = '44:55:66:77:88:99'

time.sleep(10)
示例#6
0
# find the objectId of the Scope with the name of the Transport Zone
vdn_scopes = client_session.read('vdnScopes', 'read')['body']
vdn_scope_dict_list = [scope_dict for scope_dict in vdn_scopes['vdnScopes'].items()]
vdn_scope = [scope[1]['objectId'] for scope in vdn_scope_dict_list if scope[1]['name'] == TRANSPORT_ZONE][0]

# get a template dict for the lswitch create
lswitch_create_dict = client_session.extract_resource_body_example('logicalSwitches', 'create')
client_session.view_body_dict(lswitch_create_dict)

# fill the details for the new lswitch in the body dict
lswitch_create_dict['virtualWireCreateSpec']['controlPlaneMode'] = 'UNICAST_MODE'
lswitch_create_dict['virtualWireCreateSpec']['name'] = 'TestLogicalSwitch1'
lswitch_create_dict['virtualWireCreateSpec']['tenantId'] = 'Tenant1'

# create new lswitch
new_ls = client_session.create('logicalSwitches', uri_parameters={'scopeId': vdn_scope},
                               request_body_dict=lswitch_create_dict)
client_session.view_response(new_ls)

# list all logical switches
all_lswitches = client_session.read('logicalSwitchesGlobal')
client_session.view_response(all_lswitches)

# list all logical switches in transport Zone
tz_lswitches = client_session.read('logicalSwitches', uri_parameters={'scopeId': vdn_scope})
client_session.view_response(tz_lswitches)

# Read the properties of the new logical switch
new_ls_props = client_session.read('logicalSwitch', uri_parameters={'virtualWireID': new_ls['objectId']})
client_session.view_response(new_ls_props)

time.sleep(5)
示例#7
0
# IN THE SOFTWARE.


__author__ = 'cmullaney'

from tests.config import *
from nsxramlclient.client import NsxClient
import time

client_session = NsxClient(nsxraml_file, nsxmanager, nsx_username, nsx_password, debug=True)

macset_dict = client_session.extract_resource_body_example('macsetScopeCreate', 'create')
macset_dict['macset']['name'] = 'test0'

# CREATE macset on scope
newmacset_return = client_session.create('macsetScopeCreate', uri_parameters={'scopeId': 'globalroot-0'},
                                         request_body_dict=macset_dict)

# READ macset by ID
newmacset = dict(client_session.read('macset', uri_parameters={'macsetId': newmacset_return['objectId']})['body'])

# UPDATE macset by ID
newmacset['macset']['name'] = 'test1'
newmacset['macset']['revision'] = '1'
newmacset['macset']['value'] = '44:55:66:77:88:99'

time.sleep(10)

client_session.update('macset', uri_parameters={'macsetId': newmacset_return['objectId']},
                      request_body_dict=newmacset)

# READ macsets on scope