Пример #1
0
def main():
    module = AnsibleModule(argument_spec=dict(
        display_name=dict(required=True, type='str'),
        description=dict(required=False, type='str', default=None),
        host_switch_mode=dict(required=False,
                              type='str',
                              default='STANDARD',
                              choices=['STANDARD', 'ENS']),
        host_switch_name=dict(required=True, type='str'),
        nested_nsx=dict(required=False, type='bool', default=False),
        transport_type=dict(required=False,
                            type='str',
                            default='OVERLAY',
                            choices=['OVERLAY', 'VLAN']),
        tags=dict(required=False, type='dict', default=None),
        state=dict(required=False,
                   type='str',
                   default="present",
                   choices=['present', 'absent']),
        nsx_manager=dict(required=True, type='str'),
        nsx_username=dict(required=True, type='str'),
        nsx_passwd=dict(required=True, type='str', no_log=True)),
                           supports_check_mode=True)

    if not HAS_PYNSXT:
        module.fail_json(msg='pynsxt is required for this module')
    session = requests.session()
    session.verify = False
    nsx_url = 'https://%s:%s' % (module.params['nsx_manager'], 443)
    connector = connect.get_requests_connector(session=session,
                                               msg_protocol='rest',
                                               url=nsx_url)
    stub_config = StubConfigurationFactory.new_std_configuration(connector)
    security_context = create_user_password_security_context(
        module.params["nsx_username"], module.params["nsx_passwd"])
    connector.set_security_context(security_context)
    requests.packages.urllib3.disable_warnings()
    #tags=None
    tags = []
    tags.append(
        Tag(scope='created-by', tag=os.getenv("NSX_T_INSTALLER", "nsx-t-gen")))

    if module.params['tags'] is not None:
        #tags = []
        for key, value in module.params['tags'].items():
            tag = Tag(scope=key, tag=value)
            tags.append(tag)
    transportzones_svc = TransportZones(stub_config)
    tz = getTransportZoneByName(module, stub_config)
    if module.params['state'] == 'present':
        if tz is None:
            tags.append(
                Tag(scope='generated',
                    tag=time.strftime("%Y-%m-%d %H:%M:%S %z")))
            new_tz = TransportZone(
                transport_type=module.params['transport_type'],
                display_name=module.params['display_name'],
                description=module.params['description'],
                host_switch_name=module.params['host_switch_name'],
                host_switch_mode=module.params['host_switch_mode'],
                nested_nsx=module.params['nested_nsx'],
                tags=tags)
            if module.check_mode:
                module.exit_json(changed=True,
                                 debug_out=str(new_tz),
                                 id="1111")
            new_tz = transportzones_svc.create(new_tz)
            module.exit_json(changed=True,
                             object_name=module.params['display_name'],
                             id=new_tz.id,
                             message="Transport Zone with name %s created!" %
                             (module.params['display_name']))
        elif tz:
            #if tags != tz.tags:
            if not compareTags(tz.tags, tags):
                tags.append(findTag(tz.tags, 'generated'))
                tags.append(
                    Tag(scope='modified',
                        tag=time.strftime("%Y-%m-%d %H:%M:%S %z")))
                tz.tags = tags
                if module.check_mode:
                    module.exit_json(changed=True, debug_out=str(tz), id=tz.id)
                new_tz = transportzones_svc.update(tz.id, tz)
                module.exit_json(
                    changed=True,
                    object_name=module.params['display_name'],
                    id=new_tz.id,
                    message="Transport Zone with name %s has changed tags!" %
                    (module.params['display_name']))
            module.exit_json(
                changed=False,
                object_name=module.params['display_name'],
                id=tz.id,
                message="Transport Zone with name %s already exists!" %
                (module.params['display_name']))

    elif module.params['state'] == "absent":
        if tz:
            if module.check_mode:
                module.exit_json(changed=True, debug_out=str(tz), id=tz.id)
            transportzones_svc.delete(tz.id)
            module.exit_json(changed=True,
                             object_name=module.params['display_name'],
                             message="Transport Zone with name %s deleted!" %
                             (module.params['display_name']))
        module.exit_json(changed=False,
                         object_name=module.params['display_name'],
                         message="Transport Zone with name %s doe not exist!" %
                         (module.params['display_name']))
Пример #2
0
def main():
    args = getargs.getargs()

    print("----debug-----1")

    nsx_host="192.168.55.37"
    user = "******"
    password = "******"
    tcp_port = 443

#    stub_config = auth.get_session_auth_stub_config(args.user, args.password,
#                                                    args.nsx_host,
#                                                    args.tcp_port)
    
    stub_config = auth.get_session_auth_stub_config(user, password, nsx_host, tcp_port)
    # Create a pretty printer to make the output look nice.
    pp = PrettyPrinter()

    # Create the service we'll need.
    transportzones_svc = TransportZones(stub_config)

    # First, list all transport zones. If your NSX installation has
    # just been installed, this should return an empty list.
    tzs = transportzones_svc.list()
    print("Initial list of transport zones - %d zones" % tzs.result_count)
    pp.pprint(tzs)

    # Create a transport zone.
    new_tz = TransportZone(
        transport_type=TransportZone.TRANSPORT_TYPE_OVERLAY,
        display_name="My transport zone",
        description="Transport zone for basic create/read/update/delete demo",
        host_switch_name="hostswitch1"
    )
    result_tz = transportzones_svc.create(new_tz)
    print("Transport zone created. id is %s" % result_tz.id)

    # Save the id, which uniquely identifies the resource we created.
    tz_id = result_tz.id

    # Read that transport zone.
    read_tz = transportzones_svc.get(tz_id)
    print("Re-read the transport zone")
    pp.pprint(read_tz)

    # List all transport zones again. The newly created transport
    # zone will be in the list.
    tzs = transportzones_svc.list()
    print("Updated list of transport zones - %d zones" % tzs.result_count)
    pp.pprint(tzs)

    print("You can now examine the list of transport zones in the")
    print("NSX manager if you wish. Press enter to continue.")
    sys.stdin.readline()

    # Update the transport zone.
    read_tz.description = "Updated description for transport zone"
    updated_tz = transportzones_svc.update(tz_id, read_tz)
    print("After updating description. Note that the revision property is "
          "automatically updated.")
    pp.pprint(updated_tz)

    # Update the transport zone again.
    #
    # Note that NSX insists that clients always operate on up-to-date
    # data. To enforce this, every resource in NSX has a "revision"
    # property that is automatically maintained by NSX and is
    # incremented each time the resource is updated. If a client
    # submits an update operation, and the revision property in the
    # payload provided by the client does not match the revision
    # stored on the server, another update must have happened since
    # the client last read the resource, and the client's copy is
    # therefore stale.  In this case, the server will return a 412
    # Precondition Failed error. This is intended to prevent clients
    # from clobbering each other's updates. To recover from this
    # error, the client must re-read the resource, apply any desired
    # updates, and perform another update operation.
    updated_tz.description = "Updated description again for transport zone"
    updated_tz = transportzones_svc.update(tz_id, updated_tz)
    print("After updating description again.")
    pp.pprint(updated_tz)

    # Delete the transport zone.
    transportzones_svc.delete(tz_id)
    print("After deleting transport zone")

    # Now if we try to read the transport zone, we should get a
    # 404 Not Found error. This example also shows how you can
    # check for and handle specific errors from the NSX API.
    try:
        read_tz = transportzones_svc.get(tz_id)
    except NotFound:
        print("Transport zone is gone, as expected")