NUTANIX · API & PLATFORM REFERENCE

Nutanix API Bible

Hier schlage ich nach, wie ich an eine VM-Liste komme, einen Snapshot aufbaue oder einen fehlgeschlagenen Request eingrenze. Die Kapitel enthalten die Pfade und den passenden Code.

Prism Centralv4.0 · VMM
GET/api/vmm/v4.0/ahv/config/vms
VM-Abfrage im Simulator öffnen →

Hier sammle ich, was ich für die Arbeit mit den Nutanix-APIs immer wieder brauche: Ressourcen, Datenfelder, lesende Codebeispiele und Hilfe bei Fehlermeldungen. Die jeweiligen Voraussetzungen und Grenzen stehen bei den Themen dabei.

01 · Einstieg nach Aufgabe

Die Nutanix-v4-APIs sind nach Produktbereichen gegliedert. Schemas, SDKs und Abfragen beziehen sich jeweils auf eine bestimmte Version. Damit lassen sich Inventar erfassen, Dokumentation erstellen und Änderungen automatisieren. Ich ergänze die öffentlichen Spezifikationen hier um Erfahrungen aus NutaDoc, NutaView, NutaFlow und dem Kubernetes-Betrieb.

Ich möchte …Hier beginnenErgebnis und Voraussetzung
VMs und Subnetze auflistenPython / PowerShell / cURLVollständige Listen mit Paginierung; lesende Rechte auf die Objekte.
Eine As-Built-Dokumentation erstellenInventarCluster, Hosts, Storage und Netzwerk über IDs zusammenführen.
Firewall-Regeln dokumentierenFlow & CategoriesKonfigurierte Policies, Gruppen und Referenzen erfassen; Traffic gesondert erheben.
Eine Änderung automatisierenETag / Request-ID / TasksSchema, Berechtigung und Abschlussprüfung der konkreten Operation.
Einen fehlgeschlagenen Aufruf verstehenHTTP / DNS / RBACTransport, Authentifizierung, API-Version und Nutzdaten getrennt prüfen.
NKP und NAI betreibenNKP / NAIPrism-Integration, Kubernetes-API und Inferenz-API richtig zuordnen.
Lesart: „Dokumentiert“ beschreibt eine öffentliche Quelle. „Praxisbeobachtung“ beschreibt einen begrenzten Erfassungsstand. „Zu prüfen“ benennt eine konkrete Versions-, Rollen- oder Produktvoraussetzung. Stand der redaktionellen Quellenprüfung: 28. Oktober 2026. Die Codebeispiele wurden dabei nicht gegen eine Kundenumgebung ausgeführt.

Developer Portal ↗ · v4 introduction ↗

02 · API-Generationen und Versionswahl

SchnittstelleAdressierungEinsatz
v4/api/{namespace}/{version}/…Für neue Integrationen die unterstützte GA-Version des benötigten Namespace wählen.
v3/api/nutanix/v3/…Bestehende Intent-Integrationen, oft POST-Listen mit kind, length und offset.
v2 / v1/PrismGateway/services/rest/v2.0/…
/PrismGateway/services/rest/v1/…
Ressourcenspezifische Legacy-Integration; PC und PE haben unterschiedliche Funktionen.

Die Produktversion von Prism Central und die API-Version sind verschiedene Größen. v4.0, v4.1 oder v4.2 bezeichnen Namespace-Revisionen. Mehrere Revisionen können parallel verfügbar sein. Ein funktionierender vmm-Aufruf belegt keine identische Verfügbarkeit von files oder microseg. EA-/RC-Suffixe gehören zu eigenen Entwicklungsständen und werden nicht einfach an einen GA-Pfad angehängt.

  • Pro Namespace eine unterstützte Version festlegen; PC, AOS und zusätzliche Produktstände erfassen.
  • SDK-Paketversion und API-Pfadversion getrennt dokumentieren. Bei REST kann eine eigene Namespace-Versionskonfiguration verwendet werden.
  • Ein HTTP 404 ist ein Diagnosehinweis auf Pfad, Version, Objekt oder Sichtbarkeit. Es beweist nicht, dass die Produktfunktion grundsätzlich fehlt.
Das Developer Portal nennt für v0.8/v1/v2/v3 eine Ablösung mit einem für Q4 2027 geplanten AOS-/PC-Upgrade-Release. Für bestehende Integrationen daraus einen Migrationsplan ableiten; die aktuelle Lifecycle-Mitteilung und den eigenen Supportstand berücksichtigen.

Versioning ↗ · GA status & lifecycle ↗

03 · Verbindung, Authentifizierung und Rollen

Prism Central ist der übliche Einstieg für v4, bei lokalen Installationen typischerweise über https://pc.example.com:9440. Prism Element adressiert einen einzelnen Cluster. DNS, Route, Port, Zertifikatskette und Uhrzeit zuerst prüfen. Den dokumentierten Endpunkt beziehungsweise die freigegebene virtuelle Adresse verwenden.

MethodeVerwendungVoraussetzung
HTTP BasicAuthorization: Basic …Benutzer- oder geeignetes Verzeichnisdienstkonto mit passender Rolle und Objektsichtbarkeit.
IAM API keyX-Ntnx-Api-Key: …Unterstützte IAM-Version, Service Account und zugeordnete Authorization Policy. Ein API-Key ersetzt keine Rechtezuweisung.
TLS-Vertrauenverify="/path/to/ca-bundle.pem"Interne CA einbinden oder Zertifikat mit vertrauenswürdiger Kette einsetzen.

Für Inventar beginnt man mit den erforderlichen Leserechten. Ob eine bestimmte Viewer-Rolle alle gewünschten Kapitel abdeckt, hängt von Ressource und Scope ab. IAM, Lizenzen und geschützte Objekte können zusätzliche Rechte verlangen. PC- und PE-Authentifizierung getrennt konfigurieren; ein an PC gültiges Konto ist nicht automatisch an jedem PE verfügbar.

Service Accounts erleichtern die Zuordnung und Rotation von Automatisierungszugängen. Geheimnisse zur Laufzeit aus einem Prompt oder Secret Store beziehen. Snapshots und Logs enthalten nur fachliche Daten sowie bereinigte Fehlermeldungen. In Kubernetes sind Secrets geschützt zu verwalten; Base64 ist keine Verschlüsselung.

API key walkthrough ↗ · IAM reference ↗

Sicherer API-Zugang: Identität, Rolle und Scope

Für einen Collector eine eigene Identität und die kleinsten benötigten Leserechte vorsehen. Eine IAM-Rolle beschreibt Operationen; Autorisierungsrichtlinien verbinden Identitäten und Rollen mit einem Geltungsbereich. Eine Rollenliste allein belegt daher nicht die effektiven Rechte. APIs, deren Verfügbarkeit, Rollen und Versionen vor dem Einsatz in der passenden IAM-Referenz prüfen.

TLS-Zertifikat und Hostnamen prüfen, statt die Prüfung pauschal abzuschalten. Zugangsdaten und API-Keys nicht in Beispieldateien, Logs, URLs oder Exporte schreiben. Auch lesende Inventardaten können interne Namen, Adressen und Sicherheitskonfiguration enthalten.

Nutanix IAM API ↗

04 · Antworten, Paginierung und Abfragen

BausteinVerhalten und Umgang
dataListe oder Einzelobjekt gemäß Operation; ein fehlendes Feld von einer erfolgreich gelesenen leeren Liste unterscheiden.
metadataJe nach Antwort Gesamtzahl, Links und Flags. Den jeweiligen Response-Typ auswerten.
extIdStabile externe Referenz im jeweiligen API-Kontext; unverändert übernehmen. Nicht jede Kennung muss als nackte UUID behandelt werden.
$page / $limitv4-Listen beginnen üblicherweise bei Seite 0. Gültiges Limit pro Endpunkt; häufig Standard 50 und Maximum 100.
$filter / $orderby / $select / $expandNur unterstützte Felder und Operatoren verwenden. Erweiterungen und Projektionen können pro Ressource abweichen.
$objectTypeTypinformation, insbesondere bei polymorphen Bodies relevant. Erforderliche Typen erhalten; Read-only-Felder anhand des Request-Schemas entfernen.

Eine Inventarliste ist erst vollständig, wenn alle Seiten gelesen wurden. Seitenzahl, Laufzeit und Retries begrenzen und einen unvollständigen Lauf als solchen melden. Daten können sich während der Erfassung ändern; mehrere Listenaufrufe sind kein transaktionaler Snapshot. Für Vergleiche Erfassungszeit, PC-Identität und API-Version mitführen.

params = {
    "$page": 0,
    "$limit": 50,
    "$filter": "startswith(name, 'demo-')",
    "$orderby": "name asc",
}
# Pass params to the HTTP client; check supported fields in the endpoint reference.

Adressen können IPv4-, IPv6- oder FQDN-Strukturen haben. Bytewerte erst für die Ausgabe nach GiB umrechnen. Fehlende, leere und numerisch null gesetzte Werte getrennt halten. Referenzen werden über IDs mit Kategorien, Subnetzen, Clustern oder Hosts verknüpft.

Query and response guide ↗ · Networking models ↗

05 · Cluster, Hosts, CVMs und Hardware

Der Namespace clustermgmt ist die zentrale Quelle für Infrastrukturinventar. Die folgenden Pfade verwenden die in vielen Bestandsintegrationen verwendete Revision v4.0; für das Zielsystem die unterstützte Revision wählen. Detailfelder sind eine Arbeitsauswahl aus Referenz und bisherigen Erfassungen, keine Pflichtfeldliste für jede Hardware.

Cluster und Prism-Central-Zuordnung

GET /api/clustermgmt/v4.0/config/clusters
GET /api/clustermgmt/v4.0/config/clusters/{clusterExtId}
GET /api/prism/v4.0/config/domain-managers
GET /api/prism/v4.0/management/domain-managers/{extId}/backup-targets
InformationFeld oder Relation
IdentitätextId, name
Software und Funktionconfig.buildInfo.version, config.clusterSoftwareMap[], config.clusterFunction[]
Redundanz und Hypervisorconfig.redundancyFactor, config.hypervisorTypes[]
VIP / DNS / NTPnetwork.externalAddress, network.nameServerIpList[], network.ntpServerIpList[]
Nodes im Detailnodes.nodeList[], nodes.numberOfNodes
Betriebskonfigurationconfig.timezone, config.isRemoteSupportEnabled, config.isPasswordRemoteLoginEnabled

Praxisbeobachtung: Eine Clusterliste kann auch einen Eintrag mit PRISM_CENTRAL in config.clusterFunction enthalten. Diesen als Management-Instanz behandeln und nicht ungeprüft wie einen AOS-Cluster auf Hosts abfragen. Die Domain-Manager-API liefert Angaben zur PC-Instanz; Backup-Ziele sind gesonderte Ressourcen.

Hosts, CVMs und Disks

GET /api/clustermgmt/v4.0/config/clusters/{clusterExtId}/hosts
GET /api/clustermgmt/v4.0/config/clusters/{clusterExtId}/cvms
GET /api/clustermgmt/v4.0/config/disks
ObjektRelevante FelderAuswertung
HostextId, hostName, hypervisor.type, hypervisor.version, hypervisor.externalAddress, controllerVm.externalAddress, ipmi.ipNetzrollen getrennt dokumentieren; eine IPMI-Adresse ist keine Hypervisor-Adresse.
Host-HardwareblockModel, blockSerial, cpuModel, numberOfCpuSockets, numberOfCpuCores, memorySizeBytesModell-, CPU- und Speicherdaten erfassen; optionalen Feldern einen Erfassungsstatus geben.
CVMextId, nodeExtId, name, ipAddress, numVcpus, memorySizeBytesÜber die Node-Referenz zuordnen; die konkrete Adressstruktur im Schema prüfen.
DisknodeExtId, serialNumber, vendor, model, firmwareVersion, storageTier, diskSizeBytes, physicalCapacityBytes, status, storagePoolExtIdMit Host-ID und Storage-Pool verknüpfen; Boot-, Kapazitäts- und Gesundheitsangaben unterscheiden.

Für BIOS, BMC oder HBA die LCM-Inventardaten ergänzen. Ein auf einer Hardwareplattform leeres Legacy-Feld ist keine allgemeine Aussage zur API-Abdeckung. Physische NIC- und LLDP-Daten können einen gezielten PE-Aufruf benötigen; dafür einen optionalen Collector mit eigener Authentifizierung verwenden.

Cluster Management ↗ · Prism ↗

06 · Subnetze, vSwitches und VPCs

GET /api/networking/v4.0/config/subnets
GET /api/networking/v4.0/config/virtual-switches
GET /api/networking/v4.0/config/vpcs
RessourceWichtige FelderVoraussetzung oder Grenze
SubnetzextId, name, subnetType, networkId, clusterReference, ipConfig[]networkId im Kontext von subnetType interpretieren; bei VLAN-Subnetzen als VLAN-ID. Overlay-Netze separat behandeln.
IPv4 IPAMipConfig[].ipv4.ipSubnet.ip.value, ipConfig[].ipv4.ipSubnet.prefixLengthAlle IP-Konfigurationen lesen. Fehlendes IPAM bedeutet nicht, dass keine VM-Adressen existieren.
Virtual Switchclusters[].extId, clusters[].hosts[].hostNics[]Alle Cluster-/Host-Zuordnungen verarbeiten. Der erste Listeneintrag bildet keine Mehrclusterumgebung ab.
VPCVPC-Referenz und zugehörige Subnetze gemäß Zielrevision.Für VLAN-only-Umgebungen kann die Liste leer sein. Routen, externe Netze und Policies über die jeweiligen Ressourcen erfassen.

Praxisbeobachtung: Frühere Collector-Annahmen behandelten ipConfig als Objekt und clusterReference als {extId: …}. In den erfassten Antworten waren es eine Liste beziehungsweise ein ID-String. Der Parser muss dem gewählten Schema folgen. Eine unerwartete Entität wird einzeln gemeldet, während bereits erfasste Daten erhalten bleiben.

Networking reference ↗ · Nutanix networking SDK models ↗

07 · AHV-VMs, Images und Volume Groups

GET /api/vmm/v4.0/ahv/config/vms
GET /api/vmm/v4.0/ahv/config/vms/{extId}
GET /api/vmm/v4.0/content/images
GET /api/volumes/v4.0/config/volume-groups
BereichFelder und Beziehungen
Identität und PlatzierungextId, name, description, powerState, cluster.extId, host.extId, projectExtId, ownershipInfo.owner.extId
CPU / RAMnumSockets, numCoresPerSocket, numThreadsPerCore, numNumaNodes, memorySizeBytes
Boot und SicherheitmachineType, bootConfig, vtpmConfig, categories[].extId
Disks und CD-ROMdisks[].backingInfo, disks[].diskAddress, cdRoms[]
GPUgpus[].name, vendor, mode, frameBufferSizeBytes
NIC-Konfigurationnics[].networkInfo, nics[].backingInfo
IP-Konfiguration und gelernte IPsnetworkInfo.ipv4Config, networkInfo.ipv4Info.learnedIpAddresses[]
Image-MetadatenextId, name, type, sizeBytes, clusterLocationExtIds[]

Konfigurierte IP-Adressen und gelernte Gastadressen getrennt ausgeben. Beide können fehlen oder voneinander abweichen. Feldaliasnamen wie nicNetworkInfo nur dann unterstützen, wenn sie in den eingesetzten Revisionen tatsächlich vorkommen. CPU-Werte nach der Semantik der gewählten VM-Revision berechnen; Topologieangaben nicht pauschal miteinander multiplizieren.

Ein vorhandenes Image ist erst nach abgeschlossenem Import einsatzbereit. Für ISO-Workflows den dokumentierten Image-Zustand, Clusterzugriff und ein geeignetes CD-ROM-Gerät der VM prüfen. Bei Volume Groups sind VM-/iSCSI-Anbindungen und Schutzbeziehungen eigene Abhängigkeiten. Eine gefundene Volume Group ist kein Nachweis, dass sie unbenutzt ist.

VMM ↗ · Volumes ↗ · Legacy-to-v4 mapping ↗

08 · Storage, Datensicherung und Lizenzen

AufgabeAPI-ZuordnungWas sich daraus ableiten lässt
Storage Containerclustermgmt · …/config/storage-containersInventar und Konfiguration in unterstützten v4-Revisionen. Clusterkontext und Rechte laut Operation berücksichtigen.
Storage Poolsclustermgmt · Versionsabhängige Ressourcen im API-Katalog.Für die eingesetzte Revision in der Referenz nachsehen. Legacy-v1 ist eine Kompatibilitätsoption, kein universeller einziger Weg.
SchutzrichtliniendatapoliciesRichtlinien- und Planungsobjekte. Für die konkrete Funktion mit der Referenz abgleichen.
Recovery Points und Recovery-AktionendataprotectionDatensicherungs- und Wiederherstellungsressourcen. Ein vorhandener Recovery Point ersetzt keine Wiederherstellungsprüfung.
Legacy Protection Domains / Remote SitesPE-Kontext, sofern für die Bestandsversion erforderlich.PC-Policies, PE-Protection-Domains und NDK sind unterschiedliche Modelle; nicht nur Feldnamen austauschen.
Lizenzen und Entitlementslicensing · …/config/licensesLizenzressourcen, Compliance und Feature-Entitlements nach jeweils verfügbarer Operation. Eine Lizenzliste allein ist kein vollständiger Compliance-Bericht.
Ein früheres /api/storage/… mit HTTP 404 begründet keine fehlende v4-Storage-Unterstützung: Storage Container liegen unter clustermgmt. Ebenso sind ein leerer Lizenzwert und ein negativer Compliance-Status unterschiedliche Ergebnisse. Fehlende Daten mit Quelle und Erfassungsstatus ausweisen.

Cluster Management SDK ↗ · Data Policies ↗ · Data Protection ↗ · Licensing ↗

09 · LCM, Files, Alerts und IAM

LCM-Inventar und Firmware

GET /api/lifecycle/v4.0/resources/entities

Relevante Felder sind entityClass, entityModel, entityVersion, targetVersion, entityType, clusterExtId und locationInfo. Über locationType und uuid lässt sich ein Inventarobjekt einem Node oder einer Produktinstanz zuordnen. BIOS-, BMC- und HBA-Versionen sowie Files-Software können so in die Dokumentation einfließen. Inventarzeitpunkt und fehlgeschlagene Erfassungen mitführen; targetVersion ist nicht die installierte Version.

Files und Mount Targets

GET /api/files/v4.0/config/file-servers
GET /api/files/v4.0/config/file-servers/{extId}/mount-targets

Mount Targets liefern je nach Protokoll Name, Pfad, Zustand, Kapazität und SMB-/NFS-Einstellungen. Beispiele sind protocol, state, maxSizeGB, smbProperties und nfsProperties. Die tatsächlich verfügbaren Felder hängen von Files-/Files-Manager-Version und API-Revision ab.

Praxisbeobachtung: In einem bisherigen Erfassungsstand enthielt das File-Server-Objekt im Wesentlichen extId, name und Links. Ein API-Link beschreibt eine API-Ressource; seine Hostadresse darf nicht als Daten-IP des File Servers übernommen werden. Wenn eine Netzadresse fehlt, eine passende Files-Netzwerkquelle nutzen oder „nicht erhoben“ ausgeben.

Alerts, Events, Tasks und IAM

PfadErfassung
/api/monitoring/v4.0/serviceability/alertsSeverity, Status, Zeitpunkte, betroffene Entitäten und Ursachen-/KB-Verweise. Aktive, bestätigte und aufgelöste Zustände unterscheiden.
/api/monitoring/v4.0/serviceability/eventsEreignisart, Zeitpunkt und betroffene Objekte; dient der zeitlichen Einordnung.
/api/prism/v4.0/config/tasksStatus, Fortschritt, betroffene Entitäten und Fehlerausgang asynchroner Aktionen.
/api/iam/v4.0/authn/users
/api/iam/v4.0/authz/roles
Identitäten und Rollen. Eine Rollenliste allein beschreibt keine effektiven Rechte; Authorization Policies und Scope ergänzen.

LCM ↗ · Files ↗ · Monitoring ↗ · IAM ↗

Praxischeck: Server und Mount Target getrennt betrachten

Bei einer lesenden Abfrage im Oktober 2026 lieferte die Umgebung File-Server- und Mount-Target-Objekte. Ein Mount Target verweist über fileServerExtId auf seinen Server; Felder wie protocol, state und isReadOnly helfen bei der Einordnung. SMB- und NFS-Details sind protokoll- und versionsabhängig. Die Abfrage bestätigt weder Dateiinhalte noch effektive Zugriffsrechte einzelner Benutzer.

10 · Flow-Regeln und Kommunikationsdokumentation

GET /api/prism/v4.0/config/categories
GET /api/microseg/v4.0/config/policies
GET /api/microseg/v4.0/config/policies/{extId}
GET /api/microseg/v4.0/config/service-groups
GET /api/microseg/v4.0/config/address-groups

Für eine nachvollziehbare Regelübersicht Policies, Regeltypen, Kategorien, Service-Gruppen und Address-Gruppen gemeinsam erfassen. Listen können nur Kopfdaten liefern; benötigte Regeln gegebenenfalls im Detail oder über die dokumentierte Unterressource abfragen. Referenzen vor der Ausgabe auflösen und nicht auflösbare IDs im Bericht kennzeichnen.

BausteinRelevante Informationen
Policyname, type, state, scope, securedGroups
RegelRegeltyp, Richtung, Quellen, Ziele, Dienstreferenzen, Logging und Aktion gemäß Schema.
KategorienextId → key:value
Service-GruppenTCP-/UDP-Portbereiche, ICMP-Spezifikation und alle Protokolle getrennt behandeln.
ReferenzauflösungKategorie ↔ VM, Subnetz ↔ Netzbereich, Service-Gruppe ↔ Port/Protokoll.
Drei Datensichten: Eine konfigurierte Policy beschreibt Regeln. Ein Kommunikationsplan beschreibt erforderliche Verbindungen. Beobachteter Traffic beschreibt gemessene Kommunikation in einem Zeitraum. Diese Sichten können zusammengeführt werden, benötigen aber eigene Quellen und Kennzeichnungen. Eine Management-Portmatrix ist keine gemessene Flow-Analyse.

Für NutaFlow ergeben sich daraus zwei sinnvolle Ausgaben: ein Diagramm der benötigten Beziehungen und eine referenzierbare Regelmatrix für Dokumentation oder Excel. Den Geltungsbereich jeder Regel nennen. Regeln für VM-Anwendungen nicht pauschal auf CVM-, AHV- oder sonstigen Management-Traffic übertragen. v3-network_security_rules und v4-microseg über eigene Parser in ein gemeinsames Datenmodell überführen.

Flow Management ↗ · Categories ↗

Praxischeck: 404 bei der Policy-Abfrage

Eine frühere lesende Abfrage verwendete /api/microseg/v4.0/config/network-security-policies und erhielt HTTP 404. Dieser Pfad unterscheidet sich vom Policy-Pfad config/policies in den gezeigten Beispielen; der 404 belegt daher weder dessen Verhalten noch einen leeren Policy-Bestand. Der gezeigte Policy-Pfad wurde in dieser Prüfung nicht direkt ausgeführt. Zuerst den für die konkrete Version dokumentierten Pfad, Prism-Central-Version und verfügbaren Dienst prüfen; Berechtigungen und Lizenzierung gehören ebenfalls zur Einordnung. Ein 404 ist kein leerer Policy-Bestand.

Microseg SDK: Policy-Operationen ↗

11 · Änderungen: Request-ID, ETag und Task

v4 bietet Mechanismen für wiederholbare und konfliktkontrollierte Änderungen. Dafür die Header, das Request-Modell und den Task-Rückgabewert der konkreten Operation verwenden. Ein POST auf eine Legacy-Listenoperation ist fachlich lesend; die HTTP-Methode allein beschreibt nicht die Wirkung.

SchrittVorgehen
1 · GETAktuellen Objektstand und ETag lesen, wenn die Operation ein bestehendes Objekt ändert.
2 · BodyRequest-Schema verwenden; erforderliche $objectType-Angaben erhalten. Read-only-Felder nicht ungeprüft zurücksenden. Bei PUT den dokumentierten Ersetzungsumfang beachten.
3 · HeadersIf-Match mit dem dokumentierten unveränderten ETag. Ntnx-Request-Id je neuer logischer Änderung erzeugen, soweit gefordert.
4 · RetryFür denselben idempotenten Request dieselbe Request-ID und denselben Inhalt verwenden. Nach einem fachlichen Konflikt erst neu lesen und die Änderung neu bewerten.
5 · TaskTask-Referenz oder dokumentierten Location-Header auswerten. Mit Zeitlimit bis zu einem terminalen Status pollen und den Fehlerkörper sichern.
6 · ErgebnisObjekt erneut lesen und gewünschten Zustand bestätigen. Ein angenommenes Request ist noch kein fachlicher Abschluss.
# Header structure only; the request body is operation-specific.
from uuid import uuid4

request_id = str(uuid4())  # New logical operation
headers = {"Ntnx-Request-Id": request_id, "If-Match": etag}
# Reuse request_id only when retrying this same operation and payload.
# Do not split or decode etag; use the endpoint's documented representation.

SDKs übernehmen die Request-ID-Verwaltung und bieten Hilfen für ETags sowie typisierte Modelle. Headeranforderungen unterscheiden sich nach Operation. Bei einem Konflikt den ETag weder kürzen noch alternative Formate durchprobieren. Für VM-Power-Aktionen ist beispielsweise …/vms/{extId}/$actions/power-on vorgesehen; Ausschalten und Gast-Shutdown sind getrennte Wirkungen.

Request ID explanation ↗ · ETag retrieval ↗ · SDK code examples ↗

12 · Ein lesender Python-Client

Der folgende REST-Client macht Authentifizierung, Paginierung und begrenzte Wiederholungen sichtbar. Für größere Integrationen sind die offiziellen SDKs eine passende Alternative. Voraussetzung: Python mit httpx, ein erreichbares PC, konfigurierte TLS-Vertrauensstellung und Leserechte. PC_URL und optional PC_CA_BUNDLE setzen; die Versionswerte an das Ziel anpassen.

import os
import time
from getpass import getpass
from email.utils import parsedate_to_datetime
from datetime import datetime, timezone
from urllib.parse import urlsplit
import httpx

pc_url = os.environ.get("PC_URL", "https://pc.example.com:9440").rstrip("/")
if urlsplit(pc_url).scheme != "https":
    raise ValueError("PC_URL must use HTTPS")
username = input("Prism Central user: ")
password = getpass("Prism Central password: ")
ca_file = os.environ.get("PC_CA_BUNDLE")
client = httpx.Client(base_url=pc_url, auth=(username, password),
                      verify=ca_file if ca_file else True,
                      timeout=httpx.Timeout(30.0), follow_redirects=False)
VERSIONS = {ns: "v4.0" for ns in ("clustermgmt", "vmm", "networking", "prism")}

def path_for(namespace, resource):
    return f"/api/{namespace}/{VERSIONS[namespace]}/{resource.lstrip('/')}"

def retry_delay(value, attempt):
    if value:
        try:
            return max(0.0, float(value))
        except ValueError:
            try:
                return max(0.0, (parsedate_to_datetime(value) -
                    datetime.now(timezone.utc)).total_seconds())
            except (ValueError, TypeError, OverflowError):
                pass
    return min(2 ** attempt, 16)

def get_json(path, params=None):
    deadline = time.monotonic() + 120
    for attempt in range(4):
        response = client.get(path, params=params)
        if response.status_code not in (429, 502, 503, 504):
            response.raise_for_status()
            return response.json()
        if attempt == 3:
            response.raise_for_status()
        delay = retry_delay(response.headers.get("Retry-After"), attempt)
        if delay > 60 or time.monotonic() + delay > deadline:
            raise TimeoutError("Retry budget exceeded; collection incomplete")
        time.sleep(delay)

def v4_list(path, params=None, max_pages=500, max_seconds=900):
    items, seen = [], set()
    deadline = time.monotonic() + max_seconds
    for page in range(max_pages):
        if time.monotonic() >= deadline:
            raise TimeoutError("Collection incomplete: time limit exceeded")
        query = {**(params or {}), "$page": page, "$limit": 50}
        body = get_json(path, query)
        data = body.get("data")
        meta = body.get("metadata") or {}
        total = meta.get("totalAvailableResults")
        if data is None and total == 0:
            return items
        if not isinstance(data, list):
            raise ValueError("Expected a v4 list response; collection incomplete")
        if not data:
            if isinstance(total, int) and len(items) < total:
                raise ValueError("Empty page before reported total was reached")
            return items
        ids = [item.get("extId") for item in data if isinstance(item, dict)]
        if any(ext_id in seen for ext_id in ids if ext_id):
            raise ValueError("Repeated entity: retry collection against a stable inventory")
        seen.update(ext_id for ext_id in ids if ext_id)
        items.extend(data)
        if isinstance(total, int) and len(items) >= total:
            return items
    raise RuntimeError("Collection incomplete: page limit exceeded")
Das Beispiel wiederholt nur ausgewählte lesende GET-Aufrufe. 401 und 403 werden sofort zurückgegeben. Ein unvollständiger Abruf endet mit Fehler statt mit einer scheinbar vollständigen Liste. Der Zeitrahmen ist eine begrenzte Laufzeitsteuerung zwischen Requests; einzelne Aufrufe unterliegen zusätzlich dem HTTP-Timeout. Nach den Beispielen client.close() aufrufen.

Python-Beispielsammlung herunterladen ↓

Nutanix code samples ↗

13 · Praxisbeispiele zum Kopieren

Die Python-Beispiele bauen auf dem Client aus Kapitel 12 auf und können in dieser Reihenfolge ausgeführt werden. Sie zeigen Grundbausteine für NutaDoc, NutaView und NutaFlow. Mit „alle“ sind alle für das Konto sichtbaren Objekte gemeint.

Alle sichtbaren VMs ausgeben

vms = v4_list(path_for("vmm", "ahv/config/vms"))
for vm in vms:
    print(vm.get("name"), vm.get("powerState"),
          (vm.get("cluster") or {}).get("extId"),
          (vm.get("host") or {}).get("extId"))

Alle sichtbaren Subnetze ausgeben

subnets = v4_list(path_for("networking", "config/subnets"))
for subnet in subnets:
    cidrs = []
    for config in subnet.get("ipConfig") or []:
        ip_subnet = (config.get("ipv4") or {}).get("ipSubnet") or {}
        address = (ip_subnet.get("ip") or {}).get("value")
        prefix = ip_subnet.get("prefixLength")
        if address is not None and prefix is not None:
            cidrs.append(f"{address}/{prefix}")
    print(subnet.get("name"), subnet.get("subnetType"),
          subnet.get("networkId"), ", ".join(cidrs))

Cluster mit Hostanzahl ausgeben

clusters = v4_list(path_for("clustermgmt", "config/clusters"))
for cluster in clusters:
    config = cluster.get("config") or {}
    if "PRISM_CENTRAL" in (config.get("clusterFunction") or []):
        continue
    hosts = v4_list(path_for("clustermgmt",
        f"config/clusters/{cluster['extId']}/hosts"))
    version = (config.get("buildInfo") or {}).get("version")
    print(cluster.get("name"), version, len(hosts))

Kategorien zu VM-Namen auflösen

categories = v4_list(path_for("prism", "config/categories"))
labels = {c["extId"]: f"{c.get('key')}:{c.get('value')}"
          for c in categories if c.get("extId")}
for vm in vms:
    assigned = [labels.get(c.get("extId"), c.get("extId"))
                for c in vm.get("categories") or []]
    print(vm.get("name"), ", ".join(str(x) for x in assigned))

VM-Inventar für Excel als CSV

import csv
with open("vm-inventory.csv", "w", encoding="utf-8-sig", newline="") as output:
    writer = csv.writer(output, delimiter=";")
    writer.writerow(["Name", "PowerState", "MemoryGiB", "ClusterExtId"])
    for vm in vms:
        writer.writerow([vm.get("name"), vm.get("powerState"),
            round(vm["memorySizeBytes"] / 1024**3, 2)
                if vm.get("memorySizeBytes") is not None else "",
            (vm.get("cluster") or {}).get("extId")])

Inventar als versionierten Snapshot speichern

import json
from datetime import datetime, timezone
snapshot = {
    "schema_version": "1.0", "source": pc_url,
    "collected_at": datetime.now(timezone.utc).isoformat(),
    "api_versions": VERSIONS,
    "resources": {"vms": vms, "subnets": subnets},
    "collection_status": {"vms": "complete", "subnets": "complete"},
}
with open("inventory.json", "w", encoding="utf-8") as output:
    json.dump(snapshot, output, ensure_ascii=False, indent=2)
client.close()

Das CSV-Beispiel setzt auf UTF-8 mit BOM und Semikolon. Für frei bearbeitbare Namen beim Weitergeben an Tabellenkalkulationen zusätzlich eine eigene Regel gegen Formelauswertung festlegen. Der Snapshot enthält eine vereinfachte Auswahl; produktive Collector exportieren nur benötigte Felder und bereinigen sensible Metadaten vor einer Weitergabe.

cURL: eine einzelne Listenseite lesen

# curl prompts for the password; this example returns one page only.
curl --fail-with-body --cacert /path/to/ca-bundle.pem \
  --user readonly-user --get \
  --data-urlencode '$page=0' --data-urlencode '$limit=50' \
  'https://pc.example.com:9440/api/vmm/v4.0/ahv/config/vms'

PowerShell 7: VM-Liste paginieren

$Pc = 'https://pc.example.com:9440'
$Credential = Get-Credential
$All = [System.Collections.Generic.List[object]]::new()
$Complete = $false
for ($Page = 0; $Page -lt 500; $Page++) {
    $Uri = '{0}/api/vmm/v4.0/ahv/config/vms?$page={1}&$limit=50' -f $Pc, $Page
    $Response = Invoke-RestMethod -Uri $Uri -Authentication Basic `
        -Credential $Credential -TimeoutSec 30 -ErrorAction Stop
    $Rows = @($Response.data | Where-Object { $null -ne $_ })
    $Total = $Response.metadata.totalAvailableResults
    if ($Rows.Count -eq 0) {
        if ($null -eq $Total -or $All.Count -lt $Total) {
            throw 'Response incomplete or unexpected'
        }
        $Complete = $true; break
    }
    foreach ($Row in $Rows) { $All.Add($Row) }
    if ($null -ne $Total -and $All.Count -ge $Total) {
        $Complete = $true; break
    }
}
if (-not $Complete) { throw 'Collection incomplete: page limit exceeded' }
$All | Select-Object name, powerState, extId
# Trust your CA in the OS certificate store before running this example.

Das PowerShell-Beispiel bricht bei HTTP-Fehlern ab; es implementiert keine automatische Wiederholung. Für JSON-Snapshots eine passende ConvertTo-Json -Depth-Tiefe wählen und die Ausgabe auf abgeschnittene Strukturen prüfen. Große Inventare bevorzugt selektiv exportieren.

Files-Server und Freigaben auflisten

Zuerst Server auflisten, dann je Server die Mount Targets anhand seiner extId abfragen. Dieses Beispiel verwendet den Client aus Kapitel 12. Versions- und Rechtevoraussetzungen stehen in der Files-API-Referenz.

VERSIONS["files"] = "v4.0"  # choose the version supported by your PC and Files
servers = v4_list(path_for("files", "config/file-servers"))
for server in servers:
    server_id = server.get("extId")
    if not server_id:
        continue
    targets = v4_list(path_for("files", f"config/file-servers/{server_id}/mount-targets"))
    for target in targets:
        print(server.get("name"), target.get("name"),
              target.get("protocol"), target.get("state"))

Nutanix Files API ↗

14 · Eigene Collector und Tools aufbauen

Für Dokumentation bewährt sich ein getrennter Erfassungs- und Darstellungsweg: Der Collector spricht mit Prism, normalisiert Referenzen und speichert einen Snapshot. Der Renderer liest diesen Snapshot. Dadurch lassen sich HTML, Word und Diagramme aus demselben Datenstand erzeugen und zwei Zeitpunkte vergleichen.

  • Pro Namespace beziehungsweise Kapitel einen Collector mit eigenem Status und bereinigter Fehlerliste führen. „Leer“, „nicht berechtigt“, „nicht unterstützt“ und „unvollständig“ unterscheiden.
  • IDs als Join-Schlüssel verwenden. Zeitstempel, API-Version und Quellenzuordnung erhalten; Namen können sich ändern oder mehrfach vorkommen.
  • Für eine Browseroberfläche serverseitiges Backend oder lokalen JSON-Import vorsehen. Direkter Browserzugriff hängt von CORS und TLS ab und ist mit Client-Geheimnissen meist ungeeignet.
  • Inventare können sensible Nutzdaten enthalten. Feldfreigabe und Anonymisierung ausdrücklich umsetzen; Credentials und Auth-Header nie mitspeichern.
  • Für Offline-Kundennetze Assets mitliefern. SDKs und Abhängigkeiten versionieren; Parallelität begrenzen und auf 429 reagieren.

NutaDoc kann daraus die As-Built-Ausgabe erzeugen, NutaView das Inventar visualisieren und NutaFlow Policies beziehungsweise erforderliche Verbindungen dokumentieren. Die Trennung von Datenmodell und Ansicht erleichtert auch spätere API-Migrationen.

Official SDKs ↗ · Terraform provider ↗

15 · Fehler systematisch einordnen

SignalZuerst prüfenNächster Schritt
DNS / TLS / TimeoutAuflösung aus dem tatsächlich betroffenen Client oder Pod, Routing, CA-Kette und Proxy.Ein erreichbarer Browser beweist keine Erreichbarkeit aus einem Cluster-Pod.
400Pfadparameter, Body-Typ, Pflichtheader, Abfrageoperatoren und Feldnamen.Validierungsfehler lesen; Request gegen die konkrete Revision vergleichen.
401Benutzer/Key, Gültigkeit, Sperrstatus und Ziel PC/PE.Wiederholungen stoppen und gespeicherte Zugänge beim verursachenden Client prüfen.
403Operation, Rolle, Authorization Policy, Projekt und Objektscope.Fehlende Operation gezielt zuweisen; vollständige Adminrechte nicht pauschal voraussetzen.
404 / 501Namespace, Revision, Schreibweise, Ressource und unterstützte Funktion.Referenz und Zielversion vergleichen; keine zufälligen Pfade ausprobieren.
409 / 412Konflikt, ETag, Zustand und API-spezifischen Fehlertext.Neu lesen und Änderung prüfen. Ein Legacy-412 kann auch „auf PC nicht unterstützt“ bedeuten.
429Retry-After, Parallelität und Abfragevolumen.Begrenzt warten, GET wiederholen und unnötige Detailaufrufe reduzieren.
5xxFehlerkörper, Task, Dienstzustand und zeitliche Korrelation.Bei Änderungen zuerst den Task-/Objektzustand prüfen; Ergebnis kann trotz Timeout vorliegen.

Ein leerer Wert allein erklärt die Ursache nicht. Beispiele aus der Praxis: Ein nicht aufgelöster interner Dienstname kann Aufrufe nach erfolgreichem Login verhindern; ein nicht verfügbares LCM-Inventar kann Firmwarefelder leer lassen. Beobachtung, Hypothese und bestätigte Ursache im Bericht getrennt notieren. Eine weiße Oberfläche nach einem Upgrade hat keine universelle Einzelursache.

Namespace error references ↗ · Pod diagnostics ↗

16 · Legacy gezielt integrieren und migrieren

v3: Listen und Read-Modify-Write

POST /api/nutanix/v3/vms/list
{"kind":"vm","length":100,"offset":0}

GET /api/nutanix/v3/vms/{uuid}
PUT /api/nutanix/v3/vms/{uuid}

v3-Listen liefern häufig entities[] und eigene Metadaten. Weitere Seiten über offset und length lesen; der Filterdialekt unterscheidet sich von v4-OData. Beim Update einer VM nur die dokumentierten Request-Bestandteile aus api_version, metadata und spec übermitteln. Die aktuelle metadata.spec_version für die Konfliktkontrolle erhalten; status ist kein Änderungsauftrag.

v2/v1: Ressourcen und Zielsystem

BeispielKontext und Erfassung
/hosts/{uuid}/host_nics/PE-Host-NICs, gegebenenfalls LLDP-Daten. Verfügbarkeit und Rechte am PE prüfen.
/protection_domains/ · /remote_sites/Legacy-Clusterfunktionen am dokumentierten PE-Endpunkt; PC-Sichtbarkeit nicht voraussetzen.
/storage_containers/ · /storage_poolsBestehende Collector nach Antwortschema und Ziel differenzieren. v4-Entsprechungen zuerst prüfen.
/cluster/ · /cluster/smtpLegacy-Konfiguration in bestimmten Versionen. Antwortfelder vor Snapshot/Logging filtern; Konfiguration kann Secret-Felder enthalten.

Legacy-Paginierung ist ressourcenspezifisch: count/offset, page/count oder andere Parameter sind möglich. Ein gemeinsamer Client kann getrennte Adapter anbieten; er darf die v4-Abbruchregeln nicht unverändert auf jede Legacy-Liste anwenden. Für jede Abhängigkeit Zweck, Zielversion und geplantes v4-Pendant dokumentieren.

Migration in Schritten: Objektinventar erstellen → v4-Ressource und Rechte zuordnen → Datenmodell vergleichen → Leseergebnisse parallel abgleichen → Schreibabläufe samt Tasks prüfen → umstellen. Unterschiede zwischen PC-Policies, PE-Protection-Domains und neuen Produktmodellen fachlich bewerten.

Legacy API overview ↗ · v3 reference ↗

17 · Praxiswissen für den Plattformbetrieb

Die folgenden Muster fassen Betriebserfahrungen ohne Bezug auf eine konkrete Kundeninstallation zusammen. Sie dienen als Diagnosewege; die genaue Ursache wird aus Events, Logs und Versionsdaten der betroffenen Umgebung ermittelt.

BeobachtungZusammenhangVorgehen
Wiederholte 401 / KontosperreEin Controller kann mit einem veralteten Secret weiter authentifizieren. Eine Sperre allein bestätigt diesen Auslöser noch nicht.Verursachenden Client identifizieren, Wiederholungen kontrolliert unterbrechen, Secret an der richtigen Quelle korrigieren und Dienst kontrolliert wiederaufnehmen.
PVC Bound, Pod startet nichtProvisionierung, Attachment und Mount sind getrennte Storage-Schritte.Pod-Events, VolumeAttachment, CSI-Controller/-Node und Prism-Authentifizierung prüfen. Bound allein bestätigt keinen erfolgreichen Mount.
Katalog-App bleibt PendingAppDeployment → Kustomization → HelmRelease → Workload können voneinander abhängen.Erste nicht bereite Abhängigkeit und Fehlermeldung lesen. Unbekannte HelmRelease-Felder mit CRD und Controller-Version vergleichen.
CrashLoopBackOffWiederholtes Containerende mit Kubernetes-Backoff; kein eigener Ursachenname.Vorherige Logs, Exit-Code, OOM, Probes, Konfiguration und abhängige Dienste prüfen.
Files per IP erreichbar, SMB aus Pod scheitertSMB/DFS kann zusätzliche Zielnamen zurückgeben. Netzwerkzugriff auf eine einzelne IP genügt dann nicht.DNS für Share-Namen und Referral-Ziele aus dem Workload-Netz prüfen. Conditional Forwarding zentral pflegen.
kubectl config current-context
kubectl get nodes -o wide
kubectl get pods -A
kubectl get events -A --sort-by=.metadata.creationTimestamp
kubectl get kustomizations.kustomize.toolkit.fluxcd.io -A
kubectl get helmreleases.helm.toolkit.fluxcd.io -A
kubectl get ocirepositories.source.toolkit.fluxcd.io -A

# Replace placeholders after selecting the correct cluster context.
kubectl -n <namespace> describe pod <pod>
kubectl -n <namespace> logs <pod> -c <container> --previous --tail=200
kubectl -n <namespace> describe pvc <claim>
kubectl explain helmrelease.spec.install --api-version=helm.toolkit.fluxcd.io/v2

Secret-Namen und Namespaces sind versions- und installationsabhängig. CSI, CCM und CAPX können unterschiedliche Identitäten oder Formate verwenden; ein funktionierendes Konto nicht automatisch in alle Secrets kopieren. Plattformcontroller und ihre CRDs über den unterstützten NKP-Lifecycle aktualisieren. Destruktive Bereinigung oder Namespace-Löschung ist kein allgemeiner Reparaturschritt.

Bei NAI nach der Plattformprüfung Modellliste, kurzen Textrequest und Streaming getrennt testen. Bilder können andere Nutzungsangaben liefern als Textmodelle; fehlende Tokenzahlen nicht als null berechnen. Endpunkt-Token, Routing, Modellzustand und GPU-Kapazität gehören in eigene Prüfschritte.

Flux HelmRelease schema ↗ · Kubernetes pod troubleshooting ↗ · CoreDNS forwarding ↗

NKP: verfügbare Kubernetes-APIs entdecken

Prism-APIs und die Kubernetes-API sind getrennte Schnittstellen. Bei einer lesenden Discovery im NKP-Cluster waren unter anderem NKP-, Cluster-API-, Flux- und Storage-Ressourcen sichtbar. Welche davon verfügbar sind, hängt vom Cluster, den installierten Komponenten und dem Zugang ab. Discovery allein bestätigt keine Leserechte auf einzelne Objekte.

kubectl version
kubectl api-versions
kubectl api-resources --verbs=list
kubectl explain appdeployment --api-version=apps.kommander.d2iq.io/v1alpha3
kubectl auth can-i list pods --namespace YOUR_NAMESPACE

Vor der Weitergabe von Ausgaben Namen, Adressen, IDs und andere Umgebungsdaten entfernen. Secrets und deren Inhalte nicht für eine öffentliche Dokumentation auslesen.

Kubernetes API Discovery ↗

NKP-Sicherheit: Berechtigungen gezielt abfragen

Die folgenden SelfSubjectAccessReview-Abfragen prüfen jeweils eine Aktion der aktuell angemeldeten Identität. In der untersuchten Umgebung waren diese Prüfungen im Namespace default möglich. Ein „yes“ für Secrets ist ein guter Anlass, den genutzten Zugang und dessen Geltungsbereich zu prüfen; es bedeutet nicht, dass Secrets ausgelesen wurden. Kubernetes-Discovery zeigt angebotene Ressourcen und Verben, aber nicht die individuellen Rechte.

# Ask about the current identity; no objects or secret values are retrieved.
kubectl auth can-i list pods -n YOUR_NAMESPACE
kubectl auth can-i get pods --subresource=log -n YOUR_NAMESPACE
kubectl auth can-i list secrets -n YOUR_NAMESPACE
kubectl auth can-i list networkpolicies.networking.k8s.io -n YOUR_NAMESPACE

Kubernetes authorization ↗ · Kubernetes RBAC ↗

18 · Abfragen für den Alltag

Vierzehn lesende Abfragen für typische Fragen im Betrieb. Alle außer Beispiel 10 verwenden den Client aus Kapitel 12 und können einzeln ausgeführt werden. Die Ergebnisse umfassen nur Objekte, die das Konto sehen darf. Fehlende Felder und Berechtigungen prüfen.

01 · Wie viele VMs sind sichtbar?

vms = v4_list(path_for("vmm", "ahv/config/vms"))
print("VMs:", len(vms))

02 · Wie verteilen sich VMs auf ihre Zustände?

from collections import Counter
vms = v4_list(path_for("vmm", "ahv/config/vms"))
for state, count in Counter(vm.get("powerState") or "UNKNOWN" for vm in vms).items():
    print(state, count)

03 · Welche VMs sind ausgeschaltet?

vms = v4_list(path_for("vmm", "ahv/config/vms"))
for vm in vms:
    if vm.get("powerState") == "OFF":
        print(vm.get("name"), vm.get("extId"))

04 · Welche VMs haben mindestens 16 GiB RAM?

vms = v4_list(path_for("vmm", "ahv/config/vms"))
for vm in vms:
    memory = vm.get("memorySizeBytes")
    if memory is not None and memory >= 16 * 1024**3:
        print(vm.get("name"), round(memory / 1024**3, 1), "GiB")

05 · Wie viele VMs liegen auf welchem Cluster?

from collections import Counter
vms = v4_list(path_for("vmm", "ahv/config/vms"))
clusters = v4_list(path_for("clustermgmt", "config/clusters"))
names = {c.get("extId"): c.get("name") for c in clusters}
counts = Counter((v.get("cluster") or {}).get("extId") for v in vms)
for cluster_id, count in counts.items():
    print(names.get(cluster_id) or cluster_id or "unassigned", count)

06 · Welche Hosts gehören zu welchem Cluster?

clusters = v4_list(path_for("clustermgmt", "config/clusters"))
for cluster in clusters:
    if "PRISM_CENTRAL" in ((cluster.get("config") or {}).get("clusterFunction") or []):
        continue
    hosts = v4_list(path_for("clustermgmt", f"config/clusters/{cluster['extId']}/hosts"))
    print(cluster.get("name"), len(hosts))
    for host in hosts:
        print("  ", host.get("name"), host.get("extId"))

07 · Welche Subnetze und VLAN-IDs gibt es?

subnets = v4_list(path_for("networking", "config/subnets"))
for subnet in subnets:
    print(subnet.get("name"), subnet.get("subnetType"), subnet.get("networkId"))

08 · Welche Kategorien sind einer VM zugeordnet?

vms = v4_list(path_for("vmm", "ahv/config/vms"))
categories = v4_list(path_for("prism", "config/categories"))
labels = {c["extId"]: f"{c.get('key')}:{c.get('value')}" for c in categories if c.get("extId")}
for vm in vms:
    assigned = [labels.get(c.get("extId"), c.get("extId")) for c in vm.get("categories") or []]
    print(vm.get("name"), ", ".join(str(x) for x in assigned))

09 · Welche VMs haben keinen Host zugeordnet?

Ein fehlender Host ist nicht automatisch ein Fehler; Zustand und Schema prüfen.

vms = v4_list(path_for("vmm", "ahv/config/vms"))
for vm in vms:
    if not (vm.get("host") or {}).get("extId"):
        print(vm.get("name"), vm.get("powerState"), vm.get("extId"))

10 · Wie viele VM-Snapshots hat ein Cluster?

Dieser Legacy-v2-Aufruf geht direkt an Prism Element, nicht an Prism Central. Er zählt die zurückgegebenen Snapshot-Objekte dieses Clusters; Zugriff, Antwortumfang und Version am Ziel prüfen. Recovery Points und andere Schutzobjekte sind nicht automatisch enthalten. Nutanix API schema ↗

import httpx
from getpass import getpass
# Replace the URL with the Prism Element address; trust its CA.
pe_url = "https://pe.example.com:9440"
user = input("Prism Element user: ")
password = getpass("Prism Element password: ")
with httpx.Client(base_url=pe_url, auth=(user, password), verify=True, timeout=30) as pe:
    response = pe.get("/api/nutanix/v2.0/snapshots/")
    response.raise_for_status()
    body = response.json()
    print("Snapshots returned:", len(body["entities"]))

11 · Welche Images liegen im Image Store?

Der Zustand und der Zugriff auf das Zielcluster entscheiden mit, ob ein Image verwendet werden kann.

images = v4_list(path_for("vmm", "content/images"))
for image in images:
    print(image.get("name"), image.get("type") or image.get("imageType"), image.get("state"))

12 · Welche Storage Container sind sichtbar?

Verfügbarkeit und Clusterkontext hängen von der eingesetzten API-Version und den Rechten ab.

containers = v4_list(path_for("clustermgmt", "config/storage-containers"))
for container in containers:
    print(container.get("name"), container.get("extId"))

13 · Welche Tasks laufen oder sind fehlgeschlagen?

Prism Central begrenzt gegebenenfalls den verfügbaren Zeitraum; die Liste ist kein vollständiges Langzeitprotokoll.

tasks = v4_list(path_for("prism", "config/tasks"))
for task in tasks:
    if task.get("status") in {"RUNNING", "QUEUED", "FAILED"}:
        print(task.get("extId"), task.get("status"))

14 · Welche Flow Policies sind konfiguriert?

Flow, API-Version und Leserechte vorausgesetzt. Die Policy-Liste zeigt konfigurierte Objekte, keinen beobachteten Traffic.

VERSIONS["microseg"] = "v4.0"
policies = v4_list(path_for("microseg", "config/policies"))
for policy in policies:
    print(policy.get("name"), policy.get("type"), policy.get("state"))

19 · Quellen und weiterführende Ressourcen

Für eine konkrete Implementierung beginnt die Recherche bei der API-Referenz des Zielsystems. Herstellerblogs liefern Ablaufbeispiele, die Nutanix Cloud Bible liefert Architekturkontext, und Upstream-Projekte erklären die verwendeten Kubernetes-Bausteine. Veröffentlichungsstand und Versionsbezug entscheiden, ob ein Beispiel übertragbar ist. Die Auswahl unten wurde am 28. Oktober 2026 redaktionell gesichtet.

QuelleNutzen und Einordnung
Nutanix Developer Portal ↗Versionsbezogene API-, SDK- und Fehlerreferenzen.
Nutanix.dev · v4 introduction ↗GA-Status, Produktvoraussetzungen und Legacy-Lifecycle.
Nutanix.dev · API user guide ↗REST-/SDK-Einstieg und allgemeine API-Konzepte.
Nutanix.dev · versioning ↗Namespace-Revisionen und EA/RC/GA-Kennzeichnung.
Nutanix.dev · request IDs ↗Idempotenz erklärt an einem früheren EA-Beispiel; aktuelle Pfade aus der Referenz wählen.
Nutanix.dev · ETags ↗ETag-Zugriff und SDK-Helfer; Revision beachten.
Nutanix.dev · API keys ↗Service Accounts, API-Keys und Authorization Policies.
NutanixDev · code samples ↗Ausführbare Herstellerbeispiele in mehreren Sprachen; Readme und Version beachten.
Nutanix · Go SDK source ↗Typisierte Modelle und Methoden; passende Release-Version auswählen.
Nutanix · Terraform provider ↗Deklarative Infrastruktur und Beispiele für unterstützte Ressourcen.
Nutanix · API MCP server ↗Einbindung von v4-Werkzeugen in AI-Clients; Rechte und Toolumfang konfigurieren.
The Nutanix Cloud Bible · NKP ↗Architektur und Hintergrund. Das Kapitel nennt einen älteren NKP-Stand; nicht als 2.19-Upgradeanleitung verwenden.
Nutanix Community · NKP 2.19 ↗Release-Überblick mit geänderten Upgrade- und Kataloganforderungen.
Nutanix Portal · NAI on NKP ↗Versionsbezogenes NAI-Upgradeverfahren; Portal-Anmeldung kann erforderlich sein.
CAPX upstream ↗Nutanix-Infrastrukturprovider für Cluster API.
Flux · HelmRelease ↗Upstream-Schema, Conditions und Abhängigkeiten; die mit NKP gelieferte Version bleibt maßgeblich.
Flux · troubleshooting ↗Diagnose von Sources, Kustomizations und Helm-Releases.
Kubernetes · pod diagnostics ↗Events, Containerzustand und vorherige Logs.
CoreDNS · forward ↗Bedingte Weiterleitung von DNS-Zonen.

This is where I keep the things I regularly need when working with Nutanix APIs: resources, data fields, read-only code examples and help with errors. Each topic includes its prerequisites and limits.

01 · Start with a task

Nutanix v4 APIs are organized by product area. Schemas, SDKs and queries each target a particular version. They support inventory collection, documentation and automated changes. Here I add experience from NutaDoc, NutaView, NutaFlow and Kubernetes operations to the public specifications.

I want to …Start hereResult and prerequisite
List VMs and subnetsPython / PowerShell / cURLComplete paginated lists; read permissions for the objects.
Create as-built documentationInventoryJoin cluster, host, storage and network information by ID.
Document firewall rulesFlow & CategoriesCollect configured policies, groups and references; collect traffic separately.
Automate a changeETag / Request-ID / TasksSchema, permissions and completion checks for the specific operation.
Understand a failed requestHTTP / DNS / RBACCheck transport, authentication, API version and payload separately.
Operate NKP and NAINKP / NAIDistinguish Prism integration, Kubernetes API and inference API.
Reading guide: “Documented” refers to a public source. “Field observation” describes a bounded collection result. “Check” identifies a version, role or product prerequisite. Editorial source review: 28 October 2026. The code examples were not run against a customer environment as part of this review.

Developer Portal ↗ · v4 introduction ↗

02 · API generations and version selection

InterfaceAddressingUse
v4/api/{namespace}/{version}/…For new integrations, choose the supported GA version of the required namespace.
v3/api/nutanix/v3/…Existing intent integrations, often POST list operations with kind, length and offset.
v2 / v1/PrismGateway/services/rest/v2.0/…
/PrismGateway/services/rest/v1/…
Resource-specific legacy integration; PC and PE expose different capabilities.

The Prism Central product version and API version are different values. v4.0, v4.1 and v4.2 identify namespace revisions. Multiple revisions may coexist. A successful vmm request does not establish identical availability for files or microseg. EA/RC suffixes identify development releases and should not be appended to GA paths.

  • Pin a supported version per namespace; record PC, AOS and additional product versions.
  • Record SDK package versions separately from API path versions. REST clients can use a namespace version configuration.
  • An HTTP 404 suggests a path, version, object or visibility issue. It does not establish that the product lacks the feature.
The Developer Portal announces legacy v0.8/v1/v2/v3 deprecation with an AOS/PC upgrade release planned for Q4 2027. Use this to plan migration of existing integrations, taking the current lifecycle notice and your support status into account.

Versioning ↗ · GA status & lifecycle ↗

03 · Connectivity, authentication and roles

Prism Central is the usual entry point for v4, typically https://pc.example.com:9440 for local installations. Prism Element addresses an individual cluster. First check DNS, routing, port access, certificate chain and time synchronization. Use the documented endpoint or approved virtual address.

MethodUsagePrerequisite
HTTP BasicAuthorization: Basic …A user or suitable directory account with the required role and object scope.
IAM API keyX-Ntnx-Api-Key: …Supported IAM version, a service account and an associated authorization policy. An API key does not replace permission assignment.
TLS trustverify="/path/to/ca-bundle.pem"Configure the internal CA or use a certificate with a trusted chain.

Start inventory collection with the read permissions it requires. Whether a particular Viewer role covers every chapter depends on the resource and scope. IAM, licensing and protected objects may require additional permissions. Configure PC and PE authentication separately; an account valid on PC is not automatically available on every PE.

Service accounts make automation identity and credential rotation easier to manage. Obtain secrets at runtime from a prompt or secret store. Snapshots and logs should contain application data and sanitized errors. Protect Kubernetes Secrets appropriately; Base64 is not encryption.

API key walkthrough ↗ · IAM reference ↗

Secure API access: identity, role and scope

Give a collector its own identity and the minimum required read permissions. An IAM role describes operations; authorization policies connect identities and roles to a scope. A list of roles alone therefore does not establish effective access. Check API availability, roles and versions in the applicable IAM reference before use.

Verify the TLS certificate and hostname rather than disabling verification globally. Keep credentials and API keys out of sample files, logs, URLs and exports. Even read-only inventory can contain internal names, addresses and security configuration.

Nutanix IAM API ↗

04 · Responses, pagination and queries

ElementBehavior and handling
dataAn array or object according to the operation; distinguish a missing field from a successfully read empty list.
metadataMay include totals, links and flags. Interpret the response type of the operation.
extIdExternal reference in its API context; preserve it unchanged. Not every identifier should be parsed as a bare UUID.
$page / $limitv4 lists normally start at page 0. Limits are endpoint-specific; common defaults are 50 with a maximum of 100.
$filter / $orderby / $select / $expandUse supported fields and operators only. Expansion and projection support varies by resource.
$objectTypeType information, especially relevant to polymorphic payloads. Preserve required types; remove read-only fields according to the request schema.

An inventory list is complete only after all pages have been read. Bound page counts, runtime and retries, and explicitly report incomplete collection. Data may change during collection; multiple requests do not form a transactional snapshot. Include collection time, PC identity and API versions for comparisons.

params = {
    "$page": 0,
    "$limit": 50,
    "$filter": "startswith(name, 'demo-')",
    "$orderby": "name asc",
}
# Pass params to the HTTP client; check supported fields in the endpoint reference.

Addresses may use IPv4, IPv6 or FQDN structures. Convert byte values to GiB only for display. Keep missing, empty and numeric zero values distinct. Join references to categories, subnets, clusters or hosts by ID.

Query and response guide ↗ · Networking models ↗

05 · Clusters, hosts, CVMs and hardware

clustermgmt is the main namespace for infrastructure inventory. Paths below use v4.0, a revision used in many existing integrations; select the supported revision for your target. Detail fields are a working selection from references and previous collections, rather than required fields for every hardware platform.

Clusters and Prism Central identification

GET /api/clustermgmt/v4.0/config/clusters
GET /api/clustermgmt/v4.0/config/clusters/{clusterExtId}
GET /api/prism/v4.0/config/domain-managers
GET /api/prism/v4.0/management/domain-managers/{extId}/backup-targets
InformationField or relationship
IdentityextId, name
Software and functionconfig.buildInfo.version, config.clusterSoftwareMap[], config.clusterFunction[]
Redundancy and hypervisorconfig.redundancyFactor, config.hypervisorTypes[]
VIP / DNS / NTPnetwork.externalAddress, network.nameServerIpList[], network.ntpServerIpList[]
Node detailsnodes.nodeList[], nodes.numberOfNodes
Operational configurationconfig.timezone, config.isRemoteSupportEnabled, config.isPasswordRemoteLoginEnabled

Field observation: a cluster list can include an entry with PRISM_CENTRAL in config.clusterFunction. Treat it as a management instance rather than blindly querying it for AOS hosts. The domain-manager API describes the PC instance; backup targets are separate resources.

Hosts, CVMs and disks

GET /api/clustermgmt/v4.0/config/clusters/{clusterExtId}/hosts
GET /api/clustermgmt/v4.0/config/clusters/{clusterExtId}/cvms
GET /api/clustermgmt/v4.0/config/disks
ObjectUseful fieldsInterpretation
HostextId, hostName, hypervisor.type, hypervisor.version, hypervisor.externalAddress, controllerVm.externalAddress, ipmi.ipDocument each network role; an IPMI address is not a hypervisor address.
Host hardwareblockModel, blockSerial, cpuModel, numberOfCpuSockets, numberOfCpuCores, memorySizeBytesCollect model, CPU and memory details; assign a collection status to optional fields.
CVMextId, nodeExtId, name, ipAddress, numVcpus, memorySizeBytesJoin through the node reference; check the address structure in the schema.
DisknodeExtId, serialNumber, vendor, model, firmwareVersion, storageTier, diskSizeBytes, physicalCapacityBytes, status, storagePoolExtIdJoin by host ID and storage pool; distinguish boot, capacity and health information.

Add LCM inventory for BIOS, BMC or HBA information. A legacy field empty on one hardware platform does not establish general API coverage. Physical NIC and LLDP details may need a targeted PE request; use an optional collector with separate authentication.

Cluster Management ↗ · Prism ↗

06 · Subnets, virtual switches and VPCs

GET /api/networking/v4.0/config/subnets
GET /api/networking/v4.0/config/virtual-switches
GET /api/networking/v4.0/config/vpcs
ResourceUseful fieldsPrerequisite or boundary
SubnetextId, name, subnetType, networkId, clusterReference, ipConfig[]Interpret networkId in the context of subnetType; for VLAN subnets it identifies the VLAN. Handle overlay networks separately.
IPv4 IPAMipConfig[].ipv4.ipSubnet.ip.value, ipConfig[].ipv4.ipSubnet.prefixLengthRead every IP configuration. Missing IPAM does not imply that VMs have no addresses.
Virtual Switchclusters[].extId, clusters[].hosts[].hostNics[]Process every cluster/host association. The first entry does not represent a multi-cluster environment.
VPCVPC reference and associated subnets according to the target revision.VLAN-only environments may return an empty list. Collect routes, external networks and policies through their corresponding resources.

Field observation: earlier collectors assumed ipConfig was an object and clusterReference was {extId: …}. Collected responses used an array and an ID string. The parser should follow the selected schema. Report an unexpected entity individually while retaining data already collected.

Networking reference ↗ · Nutanix networking SDK models ↗

07 · AHV VMs, images and volume groups

GET /api/vmm/v4.0/ahv/config/vms
GET /api/vmm/v4.0/ahv/config/vms/{extId}
GET /api/vmm/v4.0/content/images
GET /api/volumes/v4.0/config/volume-groups
AreaFields and relationships
Identity and placementextId, name, description, powerState, cluster.extId, host.extId, projectExtId, ownershipInfo.owner.extId
CPU / RAMnumSockets, numCoresPerSocket, numThreadsPerCore, numNumaNodes, memorySizeBytes
Boot and securitymachineType, bootConfig, vtpmConfig, categories[].extId
Disks and CD-ROMdisks[].backingInfo, disks[].diskAddress, cdRoms[]
GPUgpus[].name, vendor, mode, frameBufferSizeBytes
NIC configurationnics[].networkInfo, nics[].backingInfo
IP configuration and learned IPsnetworkInfo.ipv4Config, networkInfo.ipv4Info.learnedIpAddresses[]
Image metadataextId, name, type, sizeBytes, clusterLocationExtIds[]

Report configured addresses separately from learned guest addresses. Either may be absent or differ. Support aliases such as nicNetworkInfo only when present in the revisions you use. Calculate CPU counts according to the VM revision’s semantics rather than multiplying every topology value indiscriminately.

An image becomes usable after import completes. For ISO workflows, check the documented image state, cluster access and an appropriate VM CD-ROM device. VM/iSCSI attachments and protection relationships are separate dependencies of volume groups. Finding a volume group does not establish that it is unused.

VMM ↗ · Volumes ↗ · Legacy-to-v4 mapping ↗

08 · Storage, data protection and licensing

TaskAPI mappingWhat it establishes
Storage containersclustermgmt · …/config/storage-containersInventory and configuration in supported v4 revisions. Observe cluster context and operation permissions.
Storage poolsclustermgmt · Version-dependent resources in the API catalog.Check the reference for the deployed revision. Legacy v1 is a compatibility option, not the universal only route.
Protection policiesdatapoliciesPolicy and planning objects. Match the required function to its reference.
Recovery points and recovery actionsdataprotectionProtection and recovery resources. An existing recovery point does not replace a restore test.
Legacy protection domains / remote sitesPE context where needed for the existing version.PC policies, PE protection domains and NDK are different models; migration requires more than renaming fields.
Licenses and entitlementslicensing · …/config/licensesLicense resources, compliance and feature entitlements through their available operations. A license list alone is not a complete compliance report.
An earlier HTTP 404 from /api/storage/… does not establish a lack of v4 storage support: storage containers belong to clustermgmt. Likewise, an empty license value and a negative compliance status are different results. Report missing data with its source and collection status.

Cluster Management SDK ↗ · Data Policies ↗ · Data Protection ↗ · Licensing ↗

09 · LCM, Files, alerts and IAM

LCM inventory and firmware

GET /api/lifecycle/v4.0/resources/entities

Useful fields include entityClass, entityModel, entityVersion, targetVersion, entityType, clusterExtId and locationInfo. Use locationType and uuid to relate inventory to a node or product instance. This can add BIOS, BMC, HBA and Files software versions to documentation. Include inventory age and failed collection status; targetVersion is not the installed version.

Files and mount targets

GET /api/files/v4.0/config/file-servers
GET /api/files/v4.0/config/file-servers/{extId}/mount-targets

Mount targets expose protocol-dependent names, paths, state, capacity and SMB/NFS settings. Examples include protocol, state, maxSizeGB, smbProperties and nfsProperties. Available fields depend on Files, Files Manager and the API revision.

Field observation: a previous collection returned file-server objects consisting mainly of extId, name and links. An API link identifies an API resource; its host address must not be used as the file server’s data IP. If a network address is absent, use an appropriate Files network source or report it as not collected.

Alerts, events, tasks and IAM

PathCollection
/api/monitoring/v4.0/serviceability/alertsSeverity, status, timestamps, affected entities and cause/KB references. Distinguish active, acknowledged and resolved states.
/api/monitoring/v4.0/serviceability/eventsEvent type, timestamp and affected objects; useful for timeline analysis.
/api/prism/v4.0/config/tasksStatus, progress, affected entities and failure results of asynchronous actions.
/api/iam/v4.0/authn/users
/api/iam/v4.0/authz/roles
Identities and roles. A role list alone does not establish effective permissions; include authorization policies and scope.

LCM ↗ · Files ↗ · Monitoring ↗ · IAM ↗

Field check: treat servers and mount targets separately

In a read-only query in October 2026, the environment returned file-server and mount-target objects. A mount target references its server through fileServerExtId; fields such as protocol, state and isReadOnly help describe it. SMB and NFS details depend on protocol and version. The query does not establish file contents or individual users’ effective access.

10 · Flow rules and communication documentation

GET /api/prism/v4.0/config/categories
GET /api/microseg/v4.0/config/policies
GET /api/microseg/v4.0/config/policies/{extId}
GET /api/microseg/v4.0/config/service-groups
GET /api/microseg/v4.0/config/address-groups

Collect policies, rule types, categories, service groups and address groups together for a traceable rule overview. List operations may return summaries; retrieve rules through detail operations or their documented subresource as needed. Resolve references before rendering and flag unresolved IDs in the report.

ElementUseful information
Policyname, type, state, scope, securedGroups
RuleRule type, direction, sources, destinations, service references, logging and action according to the schema.
CategoriesextId → key:value
Service groupsHandle TCP/UDP ranges, ICMP specifications and all-protocol rules separately.
Reference resolutionCategory ↔ VM, subnet ↔ network range, service group ↔ port/protocol.
Three data views: A configured policy describes rules. A communication plan describes required connections. Observed traffic describes measured communication over a period. These views can be combined, but need separate sources and labels. A management port matrix is not a measured traffic analysis.

For NutaFlow, this supports a diagram of required relationships and a traceable rule matrix for documentation or Excel. State each rule’s scope. Do not automatically extend application VM policies to CVM, AHV or other management traffic. Use separate parsers for v3 network_security_rules and v4 microseg, then normalize both into a shared model.

Flow Management ↗ · Categories ↗

Field check: 404 on the policy query

An earlier read-only request to /api/microseg/v4.0/config/network-security-policies returned HTTP 404. This path differs from the config/policies path in the examples above, so the 404 establishes neither its behavior nor an empty policy inventory. The policy path shown was not directly executed in this review. Check the documented path for the installed version, Prism Central version and available service; permissions and licensing are also relevant. A 404 is not an empty policy inventory.

Microseg SDK: policy operations ↗

11 · Changes: request ID, ETag and task

v4 provides mechanisms for repeatable changes and concurrency control. Use the headers, request model and task response defined by the specific operation. A POST to a legacy list operation is logically read-only; the HTTP verb alone does not describe its effect.

StepProcedure
1 · GETRead the current resource and ETag when the operation changes an existing object.
2 · BodyUse the request schema; preserve required $objectType values. Do not blindly return read-only fields. Observe documented PUT replacement semantics.
3 · HeadersSet If-Match to the documented, unmodified ETag. Generate Ntnx-Request-Id per new logical change where required.
4 · RetryFor a retry of the same idempotent request, reuse its request ID and payload. After a concurrency conflict, read again and reassess the change.
5 · TaskFollow the task reference or documented Location header. Poll with a deadline until terminal status and retain sanitized error details.
6 · ErgebnisRead the object again and confirm the intended state. Request acceptance is not operation completion.
# Header structure only; the request body is operation-specific.
from uuid import uuid4

request_id = str(uuid4())  # New logical operation
headers = {"Ntnx-Request-Id": request_id, "If-Match": etag}
# Reuse request_id only when retrying this same operation and payload.
# Do not split or decode etag; use the endpoint's documented representation.

SDKs manage request IDs and provide ETag helpers and typed models. Header requirements vary by operation. On a conflict, do not trim the ETag or try alternate formats. VM power actions use routes such as …/vms/{extId}/$actions/power-on; power-off and guest shutdown have different effects.

Request ID explanation ↗ · ETag retrieval ↗ · SDK code examples ↗

12 · A read-only Python client

This REST client makes authentication, pagination and bounded retries explicit. Official SDKs are a suitable alternative for larger integrations. Prerequisites: Python with httpx, a reachable PC, configured TLS trust and read permissions. Set PC_URL and optionally PC_CA_BUNDLE; adapt namespace versions to the target.

import os
import time
from getpass import getpass
from email.utils import parsedate_to_datetime
from datetime import datetime, timezone
from urllib.parse import urlsplit
import httpx

pc_url = os.environ.get("PC_URL", "https://pc.example.com:9440").rstrip("/")
if urlsplit(pc_url).scheme != "https":
    raise ValueError("PC_URL must use HTTPS")
username = input("Prism Central user: ")
password = getpass("Prism Central password: ")
ca_file = os.environ.get("PC_CA_BUNDLE")
client = httpx.Client(base_url=pc_url, auth=(username, password),
                      verify=ca_file if ca_file else True,
                      timeout=httpx.Timeout(30.0), follow_redirects=False)
VERSIONS = {ns: "v4.0" for ns in ("clustermgmt", "vmm", "networking", "prism")}

def path_for(namespace, resource):
    return f"/api/{namespace}/{VERSIONS[namespace]}/{resource.lstrip('/')}"

def retry_delay(value, attempt):
    if value:
        try:
            return max(0.0, float(value))
        except ValueError:
            try:
                return max(0.0, (parsedate_to_datetime(value) -
                    datetime.now(timezone.utc)).total_seconds())
            except (ValueError, TypeError, OverflowError):
                pass
    return min(2 ** attempt, 16)

def get_json(path, params=None):
    deadline = time.monotonic() + 120
    for attempt in range(4):
        response = client.get(path, params=params)
        if response.status_code not in (429, 502, 503, 504):
            response.raise_for_status()
            return response.json()
        if attempt == 3:
            response.raise_for_status()
        delay = retry_delay(response.headers.get("Retry-After"), attempt)
        if delay > 60 or time.monotonic() + delay > deadline:
            raise TimeoutError("Retry budget exceeded; collection incomplete")
        time.sleep(delay)

def v4_list(path, params=None, max_pages=500, max_seconds=900):
    items, seen = [], set()
    deadline = time.monotonic() + max_seconds
    for page in range(max_pages):
        if time.monotonic() >= deadline:
            raise TimeoutError("Collection incomplete: time limit exceeded")
        query = {**(params or {}), "$page": page, "$limit": 50}
        body = get_json(path, query)
        data = body.get("data")
        meta = body.get("metadata") or {}
        total = meta.get("totalAvailableResults")
        if data is None and total == 0:
            return items
        if not isinstance(data, list):
            raise ValueError("Expected a v4 list response; collection incomplete")
        if not data:
            if isinstance(total, int) and len(items) < total:
                raise ValueError("Empty page before reported total was reached")
            return items
        ids = [item.get("extId") for item in data if isinstance(item, dict)]
        if any(ext_id in seen for ext_id in ids if ext_id):
            raise ValueError("Repeated entity: retry collection against a stable inventory")
        seen.update(ext_id for ext_id in ids if ext_id)
        items.extend(data)
        if isinstance(total, int) and len(items) >= total:
            return items
    raise RuntimeError("Collection incomplete: page limit exceeded")
The example retries selected read-only GET requests. It returns 401 and 403 immediately. An incomplete collection raises an error instead of appearing complete. The time budget is checked between requests; individual calls also use the HTTP timeout. Call client.close() after running the examples.

Download Python example collection ↓

Nutanix code samples ↗

13 · Practical examples to copy

The Python examples build on the client in chapter 12 and can run in the order shown. They illustrate building blocks for NutaDoc, NutaView and NutaFlow. “All” means all objects visible to the account.

List all visible VMs

vms = v4_list(path_for("vmm", "ahv/config/vms"))
for vm in vms:
    print(vm.get("name"), vm.get("powerState"),
          (vm.get("cluster") or {}).get("extId"),
          (vm.get("host") or {}).get("extId"))

List all visible subnets

subnets = v4_list(path_for("networking", "config/subnets"))
for subnet in subnets:
    cidrs = []
    for config in subnet.get("ipConfig") or []:
        ip_subnet = (config.get("ipv4") or {}).get("ipSubnet") or {}
        address = (ip_subnet.get("ip") or {}).get("value")
        prefix = ip_subnet.get("prefixLength")
        if address is not None and prefix is not None:
            cidrs.append(f"{address}/{prefix}")
    print(subnet.get("name"), subnet.get("subnetType"),
          subnet.get("networkId"), ", ".join(cidrs))

List clusters with host counts

clusters = v4_list(path_for("clustermgmt", "config/clusters"))
for cluster in clusters:
    config = cluster.get("config") or {}
    if "PRISM_CENTRAL" in (config.get("clusterFunction") or []):
        continue
    hosts = v4_list(path_for("clustermgmt",
        f"config/clusters/{cluster['extId']}/hosts"))
    version = (config.get("buildInfo") or {}).get("version")
    print(cluster.get("name"), version, len(hosts))

Resolve categories for VM names

categories = v4_list(path_for("prism", "config/categories"))
labels = {c["extId"]: f"{c.get('key')}:{c.get('value')}"
          for c in categories if c.get("extId")}
for vm in vms:
    assigned = [labels.get(c.get("extId"), c.get("extId"))
                for c in vm.get("categories") or []]
    print(vm.get("name"), ", ".join(str(x) for x in assigned))

Export VM inventory as CSV for Excel

import csv
with open("vm-inventory.csv", "w", encoding="utf-8-sig", newline="") as output:
    writer = csv.writer(output, delimiter=";")
    writer.writerow(["Name", "PowerState", "MemoryGiB", "ClusterExtId"])
    for vm in vms:
        writer.writerow([vm.get("name"), vm.get("powerState"),
            round(vm["memorySizeBytes"] / 1024**3, 2)
                if vm.get("memorySizeBytes") is not None else "",
            (vm.get("cluster") or {}).get("extId")])

Save inventory as a versioned snapshot

import json
from datetime import datetime, timezone
snapshot = {
    "schema_version": "1.0", "source": pc_url,
    "collected_at": datetime.now(timezone.utc).isoformat(),
    "api_versions": VERSIONS,
    "resources": {"vms": vms, "subnets": subnets},
    "collection_status": {"vms": "complete", "subnets": "complete"},
}
with open("inventory.json", "w", encoding="utf-8") as output:
    json.dump(snapshot, output, ensure_ascii=False, indent=2)
client.close()

The CSV example uses UTF-8 with BOM and a semicolon separator. Define a spreadsheet formula-handling policy for user-editable names before sharing. The snapshot is a simplified selection; production collectors export required fields and sanitize sensitive metadata before distribution.

cURL: read one list page

# curl prompts for the password; this example returns one page only.
curl --fail-with-body --cacert /path/to/ca-bundle.pem \
  --user readonly-user --get \
  --data-urlencode '$page=0' --data-urlencode '$limit=50' \
  'https://pc.example.com:9440/api/vmm/v4.0/ahv/config/vms'

PowerShell 7: paginate a VM list

$Pc = 'https://pc.example.com:9440'
$Credential = Get-Credential
$All = [System.Collections.Generic.List[object]]::new()
$Complete = $false
for ($Page = 0; $Page -lt 500; $Page++) {
    $Uri = '{0}/api/vmm/v4.0/ahv/config/vms?$page={1}&$limit=50' -f $Pc, $Page
    $Response = Invoke-RestMethod -Uri $Uri -Authentication Basic `
        -Credential $Credential -TimeoutSec 30 -ErrorAction Stop
    $Rows = @($Response.data | Where-Object { $null -ne $_ })
    $Total = $Response.metadata.totalAvailableResults
    if ($Rows.Count -eq 0) {
        if ($null -eq $Total -or $All.Count -lt $Total) {
            throw 'Response incomplete or unexpected'
        }
        $Complete = $true; break
    }
    foreach ($Row in $Rows) { $All.Add($Row) }
    if ($null -ne $Total -and $All.Count -ge $Total) {
        $Complete = $true; break
    }
}
if (-not $Complete) { throw 'Collection incomplete: page limit exceeded' }
$All | Select-Object name, powerState, extId
# Trust your CA in the OS certificate store before running this example.

The PowerShell example stops on HTTP errors and has no automatic retry. For JSON snapshots, choose an appropriate ConvertTo-Json -Depth and check that structures have not been truncated. Export large inventories selectively.

List Files servers and shares

First list servers, then query mount targets for each server using its extId. This example uses the client from chapter 12. Check the Files API reference for version and permission requirements.

VERSIONS["files"] = "v4.0"  # choose the version supported by your PC and Files
servers = v4_list(path_for("files", "config/file-servers"))
for server in servers:
    server_id = server.get("extId")
    if not server_id:
        continue
    targets = v4_list(path_for("files", f"config/file-servers/{server_id}/mount-targets"))
    for target in targets:
        print(server.get("name"), target.get("name"),
              target.get("protocol"), target.get("state"))

Nutanix Files API ↗

14 · Design collectors and tools

Documentation benefits from separate collection and rendering: the collector queries Prism, normalizes references and saves a snapshot. The renderer consumes that snapshot. HTML, Word and diagrams can then share one data set and compare two collection times.

  • Maintain collection status and sanitized errors per namespace or chapter. Distinguish empty, unauthorized, unsupported and incomplete.
  • Use IDs for joins. Preserve timestamps, API versions and provenance; names can change or repeat.
  • Use a server-side backend or local JSON import for browser UIs. Direct access depends on CORS and TLS and is usually unsuitable when client secrets are involved.
  • Inventories may contain sensitive data. Explicitly implement field selection and anonymization; never store credentials or authentication headers.
  • Bundle assets for offline customer networks. Pin SDKs and dependencies; limit concurrency and handle 429.

NutaDoc can produce as-built documentation, NutaView can visualize inventory and NutaFlow can document policies or required connections. Separating the data model from presentation also simplifies later API migrations.

Official SDKs ↗ · Terraform provider ↗

15 · Diagnose errors systematically

SignalCheck firstNext step
DNS / TLS / TimeoutResolution from the affected client or pod, routing, CA chain and proxy.Browser connectivity does not prove pod connectivity.
400Path parameters, payload type, required headers, query operators and field names.Read validation errors; compare the request to its specific revision.
401Account/key, validity, lock status and PC/PE target.Stop retries and inspect credentials at the originating client.
403Operation, role, authorization policy, project and object scope.Grant the required operation deliberately; do not assume full admin access is necessary.
404 / 501Namespace, revision, spelling, resource and supported function.Compare the reference to the target version; avoid guessing routes.
409 / 412Conflict, ETag, resource state and API-specific error body.Read again and reassess. A legacy 412 can also mean an action is not supported on PC.
429Retry-After, concurrency and request volume.Wait within bounds, retry GET and reduce unnecessary detail requests.
5xxError body, task, service health and timeline.For writes, inspect task/resource state first; a timeout can occur after a change was accepted.

An empty value does not explain its cause. Field examples include internal service names failing to resolve after a successful login and missing LCM inventory leaving firmware fields empty. Record observations, hypotheses and confirmed causes separately. A blank UI after an upgrade has no universal single cause.

Namespace error references ↗ · Pod diagnostics ↗

16 · Integrate and migrate legacy APIs

v3: lists and read-modify-write

POST /api/nutanix/v3/vms/list
{"kind":"vm","length":100,"offset":0}

GET /api/nutanix/v3/vms/{uuid}
PUT /api/nutanix/v3/vms/{uuid}

v3 lists commonly return entities[] and their own metadata. Read further pages with offset and length; filtering differs from v4 OData. For VM updates, submit the documented request parts from api_version, metadata and spec. Preserve the current metadata.spec_version for concurrency control; status is not an update request.

v2/v1: resources and target system

ExampleContext and collection
/hosts/{uuid}/host_nics/PE host NICs and, where available, LLDP details. Check availability and permissions on PE.
/protection_domains/ · /remote_sites/Legacy cluster functions at the documented PE endpoint; do not assume PC visibility.
/storage_containers/ · /storage_poolsSeparate existing collectors by response schema and target. Check v4 equivalents first.
/cluster/ · /cluster/smtpLegacy configuration in selected versions. Filter response fields before snapshots/logging; configuration may include secrets.

Legacy pagination is resource-specific: parameters may include count/offset, page/count or others. A shared client can provide separate adapters; it should not apply v4 termination rules to every legacy list. Record the purpose, target version and intended v4 replacement of each dependency.

Migrate in steps: inventory operations → map v4 resources and permissions → compare data models → compare read results in parallel → validate writes and tasks → switch over. Assess semantic differences among PC policies, PE protection domains and newer product models.

Legacy API overview ↗ · v3 reference ↗

17 · Field notes for platform operations

These patterns summarize operational experience without identifying a customer installation. Use them as diagnostic paths; establish the specific cause from events, logs and versions in the affected environment.

ObservationRelationshipApproach
Repeated 401 / account lockoutA controller may continue authenticating with an outdated secret. A lockout alone does not confirm this cause.Identify the client, interrupt retries in a controlled way, correct the secret at its source and restore the service deliberately.
PVC Bound, pod not startingProvisioning, attachment and mount are separate storage stages.Check pod events, VolumeAttachment, CSI controller/node and Prism authentication. Bound alone does not establish a successful mount.
Catalog app remains pendingAppDeployment → Kustomization → HelmRelease → workload can form a dependency chain.Read the first unready dependency and its message. Compare unknown HelmRelease fields with CRD and controller versions.
CrashLoopBackOffRepeated container termination with Kubernetes backoff; not a root-cause diagnosis.Inspect previous logs, exit code, OOM, probes, configuration and dependencies.
Files reachable by IP, SMB from pod failsSMB/DFS may return additional target names. Access to one IP can therefore be insufficient.Check DNS for share names and referral targets from the workload network. Manage conditional forwarding centrally.
kubectl config current-context
kubectl get nodes -o wide
kubectl get pods -A
kubectl get events -A --sort-by=.metadata.creationTimestamp
kubectl get kustomizations.kustomize.toolkit.fluxcd.io -A
kubectl get helmreleases.helm.toolkit.fluxcd.io -A
kubectl get ocirepositories.source.toolkit.fluxcd.io -A

# Replace placeholders after selecting the correct cluster context.
kubectl -n <namespace> describe pod <pod>
kubectl -n <namespace> logs <pod> -c <container> --previous --tail=200
kubectl -n <namespace> describe pvc <claim>
kubectl explain helmrelease.spec.install --api-version=helm.toolkit.fluxcd.io/v2

Secret names and namespaces depend on version and installation. CSI, CCM and CAPX may use different identities or formats; do not copy a working credential indiscriminately into every secret. Update platform controllers and CRDs through the supported NKP lifecycle. Destructive cleanup or namespace deletion is not a general repair step.

For NAI, after platform validation test model listing, a short text request and streaming separately. Image models may report usage differently from text models; do not turn missing token counts into zero. Check endpoint tokens, routing, model state and GPU capacity separately.

Flux HelmRelease schema ↗ · Kubernetes pod troubleshooting ↗ · CoreDNS forwarding ↗

NKP: discover available Kubernetes APIs

Prism APIs and the Kubernetes API are separate interfaces. Read-only discovery on an NKP cluster showed NKP, Cluster API, Flux and storage resources among others. Availability depends on the cluster, installed components and access. Discovery alone does not establish permission to read individual objects.

kubectl version
kubectl api-versions
kubectl api-resources --verbs=list
kubectl explain appdeployment --api-version=apps.kommander.d2iq.io/v1alpha3
kubectl auth can-i list pods --namespace YOUR_NAMESPACE

Remove names, addresses, IDs and other environment details before sharing output. Do not read secrets or their contents for public documentation.

Kubernetes API discovery ↗

NKP security: query individual permissions

These SelfSubjectAccessReview queries check individual actions for the current identity. They could be performed in the default namespace of the examined environment. A “yes” for secrets is a reason to review the identity and its scope; it does not mean secrets were read. Kubernetes discovery lists offered resources and verbs, not an individual identity’s permissions.

# Ask about the current identity; no objects or secret values are retrieved.
kubectl auth can-i list pods -n YOUR_NAMESPACE
kubectl auth can-i get pods --subresource=log -n YOUR_NAMESPACE
kubectl auth can-i list secrets -n YOUR_NAMESPACE
kubectl auth can-i list networkpolicies.networking.k8s.io -n YOUR_NAMESPACE

Kubernetes authorization ↗ · Kubernetes RBAC ↗

18 · Everyday queries

Fourteen read-only queries for everyday operations. All except example 10 use the client from chapter 12 and can be run independently. Results include only objects visible to the account. Check missing fields and permissions.

01 · How many VMs are visible?

vms = v4_list(path_for("vmm", "ahv/config/vms"))
print("VMs:", len(vms))

02 · How are VMs distributed by power state?

from collections import Counter
vms = v4_list(path_for("vmm", "ahv/config/vms"))
for state, count in Counter(vm.get("powerState") or "UNKNOWN" for vm in vms).items():
    print(state, count)

03 · Which VMs are powered off?

vms = v4_list(path_for("vmm", "ahv/config/vms"))
for vm in vms:
    if vm.get("powerState") == "OFF":
        print(vm.get("name"), vm.get("extId"))

04 · Which VMs have at least 16 GiB of RAM?

vms = v4_list(path_for("vmm", "ahv/config/vms"))
for vm in vms:
    memory = vm.get("memorySizeBytes")
    if memory is not None and memory >= 16 * 1024**3:
        print(vm.get("name"), round(memory / 1024**3, 1), "GiB")

05 · How many VMs belong to each cluster?

from collections import Counter
vms = v4_list(path_for("vmm", "ahv/config/vms"))
clusters = v4_list(path_for("clustermgmt", "config/clusters"))
names = {c.get("extId"): c.get("name") for c in clusters}
counts = Counter((v.get("cluster") or {}).get("extId") for v in vms)
for cluster_id, count in counts.items():
    print(names.get(cluster_id) or cluster_id or "unassigned", count)

06 · Which hosts belong to each cluster?

clusters = v4_list(path_for("clustermgmt", "config/clusters"))
for cluster in clusters:
    if "PRISM_CENTRAL" in ((cluster.get("config") or {}).get("clusterFunction") or []):
        continue
    hosts = v4_list(path_for("clustermgmt", f"config/clusters/{cluster['extId']}/hosts"))
    print(cluster.get("name"), len(hosts))
    for host in hosts:
        print("  ", host.get("name"), host.get("extId"))

07 · Which subnets and VLAN IDs exist?

subnets = v4_list(path_for("networking", "config/subnets"))
for subnet in subnets:
    print(subnet.get("name"), subnet.get("subnetType"), subnet.get("networkId"))

08 · Which categories are assigned to each VM?

vms = v4_list(path_for("vmm", "ahv/config/vms"))
categories = v4_list(path_for("prism", "config/categories"))
labels = {c["extId"]: f"{c.get('key')}:{c.get('value')}" for c in categories if c.get("extId")}
for vm in vms:
    assigned = [labels.get(c.get("extId"), c.get("extId")) for c in vm.get("categories") or []]
    print(vm.get("name"), ", ".join(str(x) for x in assigned))

09 · Which VMs have no host assigned?

A missing host is not necessarily an error; check the state and schema.

vms = v4_list(path_for("vmm", "ahv/config/vms"))
for vm in vms:
    if not (vm.get("host") or {}).get("extId"):
        print(vm.get("name"), vm.get("powerState"), vm.get("extId"))

10 · How many VM snapshots does a cluster have?

This legacy v2 request goes directly to Prism Element, not Prism Central. It counts snapshot objects returned for this cluster; check access, response completeness and version on the target. Other recovery points and protection objects are not automatically included. Nutanix API schema ↗

import httpx
from getpass import getpass
# Replace the URL with the Prism Element address; trust its CA.
pe_url = "https://pe.example.com:9440"
user = input("Prism Element user: ")
password = getpass("Prism Element password: ")
with httpx.Client(base_url=pe_url, auth=(user, password), verify=True, timeout=30) as pe:
    response = pe.get("/api/nutanix/v2.0/snapshots/")
    response.raise_for_status()
    body = response.json()
    print("Snapshots returned:", len(body["entities"]))

11 · Which images are in the image store?

The state and access from the target cluster help determine whether an image can be used.

images = v4_list(path_for("vmm", "content/images"))
for image in images:
    print(image.get("name"), image.get("type") or image.get("imageType"), image.get("state"))

12 · Which storage containers are visible?

Availability and cluster context depend on the API version and permissions.

containers = v4_list(path_for("clustermgmt", "config/storage-containers"))
for container in containers:
    print(container.get("name"), container.get("extId"))

13 · Which tasks are running or have failed?

Prism Central may limit the available time range; this is not a complete long-term log.

tasks = v4_list(path_for("prism", "config/tasks"))
for task in tasks:
    if task.get("status") in {"RUNNING", "QUEUED", "FAILED"}:
        print(task.get("extId"), task.get("status"))

14 · Which Flow policies are configured?

Requires Flow, a supported API version and read permissions. The list shows configured objects, not observed traffic.

VERSIONS["microseg"] = "v4.0"
policies = v4_list(path_for("microseg", "config/policies"))
for policy in policies:
    print(policy.get("name"), policy.get("type"), policy.get("state"))

19 · Sources and further reading

Begin implementation research with the API reference for the target system. Vendor blogs provide walkthroughs, the Nutanix Cloud Bible provides architectural context, and upstream projects explain Kubernetes components. Publication date and version scope determine whether an example applies. The selection below was editorially reviewed on 28 October 2026.

SourcePurpose and scope
Nutanix Developer Portal ↗Version-specific API, SDK and error references.
Nutanix.dev · v4 introduction ↗GA status, product prerequisites and legacy lifecycle.
Nutanix.dev · API user guide ↗REST/SDK introduction and general API concepts.
Nutanix.dev · versioning ↗Namespace revisions and EA/RC/GA identification.
Nutanix.dev · request IDs ↗Idempotency explained with an older EA example; select current paths from the reference.
Nutanix.dev · ETags ↗ETag access and SDK helpers; observe the revision.
Nutanix.dev · API keys ↗Service accounts, API keys and authorization policies.
NutanixDev · code samples ↗Vendor examples in multiple languages; check README and version.
Nutanix · Go SDK source ↗Typed models and methods; choose a matching release.
Nutanix · Terraform provider ↗Declarative infrastructure and supported resource examples.
Nutanix · API MCP server ↗Integrating v4 tools with AI clients; configure permissions and tool scope.
The Nutanix Cloud Bible · NKP ↗Architecture and background. The chapter identifies an older NKP release; do not use it as a 2.19 upgrade procedure.
Nutanix Community · NKP 2.19 ↗Release overview with changed upgrade and catalog requirements.
Nutanix Portal · NAI on NKP ↗Version-specific NAI upgrade procedure; portal sign-in may be required.
CAPX upstream ↗Nutanix infrastructure provider for Cluster API.
Flux · HelmRelease ↗Upstream schema, conditions and dependencies; use the version shipped with NKP.
Flux · troubleshooting ↗Diagnosing sources, kustomizations and Helm releases.
Kubernetes · pod diagnostics ↗Events, container state and previous logs.
CoreDNS · forward ↗Conditional DNS zone forwarding.