Snapshot automation against the Tintri REST API goes wrong in three predictable ways: version negotiation done in the URL instead of the login body, pagination ignored so the audit silently covers a fraction of the estate, and a lock operation attempted with a role that cannot perform it. All three are documented behaviours, and all three produce confident wrong answers rather than obvious failures.
A correction to earlier posts on this site. I previously suggested that a 404 on an API call means you should change the URL to a fully qualified version path such as
/api/v310.203/. That is not the documented mechanism. The base path stays/api/v310and you request a specific version by settingfullApiVersionin the login body. I have corrected the approach here and the scripts below use it.
01. Version negotiation, the documented way
Login is a POST to the session resource. The body carries the credentials type, the username and password, and optionally fullApiVersion. A session cookie comes back and is used on every subsequent call.
POST https://vmstore.example.com/api/v310/session/login
{
"typeId": "com.tintri.api.rest.vcommon.dto.rbac.RestApiCredentials",
"username": "readonly-svc",
"password": "REDACTED",
"fullApiVersion": "v310.191"
}
-> HTTP 200, plus the user role name in the body
Logout is a GET on /api/v310/session/logout and returns HTTP 204.
The version you request has to exist on the appliance, and the mapping is fixed. This matters when you are scripting across a fleet that is not all on the same release.
| API version | TXOS | TGC | Notable |
|---|---|---|---|
| v310.101 | 4.6.0.x | 5.0.0 | Oldest still supported |
| v310.111 | 5.0.0.x | 5.0.1 | |
| v310.121 | 5.1.0.x | 5.2.x | |
| v310.131 | 5.2.0.x | 5.3.x | |
| v310.141 | 5.3.0.x | 5.3.x | |
| v310.151 | 5.4.x | 5.4.x | |
| v310.171 | 5.4.2 | 5.5.x | |
| v310.181 | 5.5.1.x | 5.5.3.x | |
| v310.183 | 5.5.2.x | 5.5.4.x | Snapshot lock and unlock appear here |
| v310.191 | 5.6.0 | 5.6.0 | IPv6 requires this or later |
| v310.193 | 5.6.1 | 5.6.1 | |
| v310.201 | 6.0.0 | 6.0.0 | |
| v310.203 | 6.0.1 | 6.0.1 | Current at time of writing |
Two consequences worth designing around. Versions below v310.101 are deprecated from TXOS and TGC 5.6.0.1 onward. And from that same release only TLS 1.2 is supported, so an old client library that negotiates TLS 1.0 or 1.1 will fail to connect with an error that looks like a network problem rather than a policy one.
02. Pagination: the default that quietly truncates your audit
GET endpoints that return collections return a Page object, not a bare list. The default limit is 2000 items. An estate with more snapshots than that, which is most estates with any retention policy at all, will return a first page and nothing to indicate you are missing the rest unless you read the metadata.
| Page field | What it tells you |
|---|---|
items | The objects on this page |
absoluteTotal | Everything in the entity, including deleted, before any filter |
filteredTotal | How many match your filter. Compare this to what you collected |
limit | Page size. Default 2000 |
offset | Where this page started |
next | Query string for the next page |
offsetMatchFound | Whether the requested offset resolved |
completedIn | Server-side milliseconds. Useful for spotting an overloaded appliance |
The correct loop follows next until it is absent, then asserts that the number collected equals filteredTotal. That assertion is the whole point: without it a truncated audit and a complete one look identical.
03. Filters
Filtering follows RFC 6570 query-string conventions. For snapshots the documented example combines type, consistency and VM:
GET /api/v310/snapshot
?type=SCHEDULE_SNAPSHOT
&consistency=CRASH_CONSISTENT
&vmId=5CFC98F0-731C-2474-FE84-0BC2C3A28543-VIM-0000000000000020
type SCHEDULE_SNAPSHOT created by a protection policy
USER_GENERATED_SNAPSHOT created by a person or a script
consistency CRASH_CONSISTENT no guest quiescing
VM_CONSISTENT guest quiesced before the snapshot
vmId restrict to one VM
Filter server-side. Pulling every snapshot and filtering in Python
works on a lab and falls over on an estate with six figures of them.
The type distinction is the one that makes a sprawl audit useful. Scheduled snapshots are supposed to exist and will be aged out by their policy. User-generated snapshots with no expiry, taken during a change window that closed two years ago, are the ones actually holding capacity that nobody has claimed.
04. Error handling: what each status actually means here
Tintri returns a TintriError object on failure, and it is worth parsing rather than printing the raw body.
{
"typeId": "com.tintri.api.rest.v310.dto.domain.beans.TintriError",
"code": "ERR-API-8001",
"message": "Failed to find requested resource of type VirtualMachine with id: 'xxxxddd'",
"causeDetails": "",
"title": "Resource not found"
}
| Status | Meaning in this API | How a script should treat it |
|---|---|---|
| 200 / 204 | Success, with or without a body | 204 is success. Do not treat an empty body as failure |
| 400 | Request validation failed | Your filter or payload is malformed. Not retryable |
| 401 | Not authorised | Session expired or never established. Re-login once, then give up |
| 403 | Invalid credentials or licensing | Not always a credentials problem. Some calls require a licence |
| 404 | API not found | The endpoint does not exist at this version. Check the matrix |
| 409 | Object already exists | Treat as idempotent success where that is safe |
| 501 | Supported by VMstore but not TGC | Skip that appliance, do not fail the run |
| 503 | External service unavailable, often temporary | Retryable. Back off and try again |
501 is the one that matters for fleet scripts. Snapshot lock and unlock are VMstore-only. Point a fleet-wide locking script at a TGC and it will return 501, which is the API correctly telling you the operation does not exist there. A script that treats any non-200 as an error will report a healthy TGC as broken on every run.
05. RBAC: which role can actually do this
| Role | Read | Write | Lock snapshot | Escalate |
|---|---|---|---|---|
| Read Only | Yes | No | No | No |
| System Admin | Yes | Yes | No | No |
| Admin | Yes | Yes | No | No |
| DBA | Yes | Yes | No | No |
| Data Protection Admin | Yes | Yes | Yes | No |
| Data Protection Escalation Admin | Yes | Yes | No | Yes |
This surprises people: Admin cannot lock a snapshot. Only the Data Protection Admin role can. Unlocking, removing the lock feature from a schedule or a service group, disabling the feature and resuming snapshot deletion are restricted further, and require a DPA whose privileges have been escalated by a Data Protection Escalation Admin, with an expiry time.
That separation is deliberate. It means an administrator whose credentials are compromised cannot remove immutability from your snapshots, which is the entire point of the feature. Design your automation around it rather than trying to route past it: audit with a Read Only account, lock with a DPA account, and never put a DPEA credential in a script.
06. Script one: paginated snapshot audit
#!/usr/bin/env python3
"""tintri_snapshot_audit.py - snapshot inventory with correct pagination.
Demonstrates the three things most scripts get wrong:
* fullApiVersion negotiated in the login body, not the URL path
* every page followed, then collected count asserted against filteredTotal
* server-side filtering rather than pulling everything and filtering locally
Read only. A Read Only role account is sufficient.
"""
import argparse, os, sys, time
from collections import Counter, defaultdict
from datetime import datetime, timezone
import requests, urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
CREDS_TYPE = "com.tintri.api.rest.vcommon.dto.rbac.RestApiCredentials"
BASE_PATH = "/api/v310" # stays v310; the version is requested at login
class TintriError(RuntimeError):
def __init__(self, status, path, body):
self.status = status
self.code = self.title = self.detail = None
if isinstance(body, dict):
self.code = body.get("code")
self.title = body.get("title")
self.detail = body.get("message")
super().__init__(f"HTTP {status} on {path}: "
f"{self.code or ''} {self.title or ''} "
f"{self.detail or body}".strip())
class NotImplementedHere(TintriError):
"""501: valid API, wrong appliance type (VMstore-only call on a TGC)."""
class Tintri:
def __init__(self, host, user, pwd, full_version=None, timeout=60):
self.host, self.timeout = host, timeout
self.base = f"https://{host}{BASE_PATH}"
self.s = requests.Session()
self.s.verify = False
self.role = self._login(user, pwd, full_version)
def _login(self, user, pwd, full_version):
body = {"typeId": CREDS_TYPE, "username": user, "password": pwd}
if full_version:
body["fullApiVersion"] = full_version
r = self.s.post(f"{self.base}/session/login", json=body,
timeout=self.timeout)
if r.status_code != 200:
raise TintriError(r.status_code, "/session/login", self._body(r))
return (r.text or "").strip().strip('"')
@staticmethod
def _body(r):
try:
return r.json()
except ValueError:
return r.text
def get(self, path, params=None, retries=3):
for attempt in range(retries + 1):
r = self.s.get(f"{self.base}{path}", params=params,
timeout=self.timeout)
if r.status_code in (200, 204):
return self._body(r) if r.content else {}
if r.status_code == 501:
raise NotImplementedHere(501, path, self._body(r))
if r.status_code == 503 and attempt < retries:
# documented as usually temporary and worth retrying
time.sleep(2 ** attempt)
continue
raise TintriError(r.status_code, path, self._body(r))
def paginate(self, path, params=None, limit=1000):
"""Yield every item, then verify nothing was silently dropped."""
params = dict(params or {})
params["limit"] = limit
params["offset"] = 0
collected = 0
expected = None
while True:
page = self.get(path, params)
if not isinstance(page, dict):
return
items = page.get("items") or []
if expected is None:
expected = page.get("filteredTotal")
for it in items:
yield it
collected += len(items)
if not page.get("next") or not items:
break
params["offset"] = collected
if expected is not None and collected != expected:
sys.stderr.write(
f"WARNING {path}: collected {collected} of "
f"filteredTotal {expected}. Audit is incomplete.\n")
def logout(self):
try:
self.s.get(f"{self.base}/session/logout", timeout=15)
except Exception:
pass
def parse_ts(v):
if v in (None, ""):
return None
if isinstance(v, (int, float)):
return datetime.fromtimestamp(v / 1000, tz=timezone.utc)
try:
dt = datetime.fromisoformat(str(v).replace("Z", "+00:00"))
return dt if dt.tzinfo else dt.replace(tzinfo=timezone.utc)
except ValueError:
return None
def main():
p = argparse.ArgumentParser()
p.add_argument("--host", required=True)
p.add_argument("--user", default=os.environ.get("TINTRI_USER"))
p.add_argument("--password", default=os.environ.get("TINTRI_PASS"))
p.add_argument("--api-version", default="v310.191",
help="fullApiVersion sent at login; must exist on the box")
p.add_argument("--type", choices=["SCHEDULE_SNAPSHOT",
"USER_GENERATED_SNAPSHOT"],
help="server-side filter")
p.add_argument("--consistency", choices=["CRASH_CONSISTENT",
"VM_CONSISTENT"])
p.add_argument("--vm-id", help="restrict to one VM")
p.add_argument("--older-than-days", type=float, default=30.0)
p.add_argument("--page-size", type=int, default=1000)
a = p.parse_args()
if not a.user or not a.password:
sys.exit("set TINTRI_USER and TINTRI_PASS")
t = Tintri(a.host, a.user, a.password, a.api_version)
print(f"connected to {a.host} as role: {t.role}")
params = {}
if a.type:
params["type"] = a.type
if a.consistency:
params["consistency"] = a.consistency
if a.vm_id:
params["vmId"] = a.vm_id
if params:
print(f"server-side filter: {params}")
now = datetime.now(timezone.utc)
by_type = Counter()
by_consistency = Counter()
per_vm = defaultdict(lambda: {"count": 0, "oldest": None,
"manual": 0, "locked": 0})
total = 0
try:
for snap in t.paginate("/snapshot", params, a.page_size):
total += 1
stype = snap.get("type") or "UNKNOWN"
by_type[stype] += 1
by_consistency[snap.get("consistency") or "UNKNOWN"] += 1
vm = (snap.get("vmName") or snap.get("vmId")
or snap.get("vmUuid") or "unknown")
ts = parse_ts(snap.get("createTime") or snap.get("creationTime"))
e = per_vm[vm]
e["count"] += 1
if stype == "USER_GENERATED_SNAPSHOT":
e["manual"] += 1
if snap.get("isLocked") or snap.get("locked"):
e["locked"] += 1
if ts:
age = (now - ts).total_seconds() / 86400
e["oldest"] = age if e["oldest"] is None else max(e["oldest"], age)
finally:
t.logout()
print(f"\nsnapshots examined : {total}")
print("by type : " +
", ".join(f"{k}={v}" for k, v in by_type.most_common()))
print("by consistency : " +
", ".join(f"{k}={v}" for k, v in by_consistency.most_common()))
rows = [(v["oldest"] or 0, k, v) for k, v in per_vm.items()]
rows.sort(reverse=True)
print(f"\n{'VM':<42}{'SNAPS':>7}{'MANUAL':>8}{'LOCKED':>8}{'OLDEST(d)':>11}")
print("-" * 76)
for oldest, vm, e in rows[:30]:
print(f"{str(vm)[:41]:<42}{e['count']:>7}{e['manual']:>8}"
f"{e['locked']:>8}{oldest:>11.1f}")
stale = [(o, v, e) for o, v, e in rows
if o >= a.older_than_days and e["manual"] > 0]
if stale:
print(f"\nRECLAIM CANDIDATES: user-generated, older than "
f"{a.older_than_days} days")
for oldest, vm, e in stale:
print(f" {str(vm)[:41]:<42} {e['manual']} manual, "
f"oldest {oldest:.1f} days"
+ (f" ({e['locked']} LOCKED, cannot delete)"
if e["locked"] else ""))
return 0 if not stale else 2
if __name__ == "__main__":
sys.exit(main())
07. Script two: snapshot locking, with the guard rails the API implies
The lock endpoints are POST /v310/snapshot/{snapshotTintriUuid}/lock and the matching /unlock, available from v310.183 and VMstore only. This script locks a set of snapshots, and everything defensive in it exists because of a documented behaviour rather than paranoia.
#!/usr/bin/env python3
"""tintri_snapshot_lock.py - lock snapshots, carefully.
Requires the Data Protection Admin role. Admin is NOT sufficient.
VMstore only: a TGC returns 501 and is skipped rather than failing the run.
Requires fullApiVersion v310.183 or later.
Defaults to a dry run. --commit is required to change anything.
"""
import argparse, os, sys
from tintri_snapshot_audit import (Tintri, TintriError,
NotImplementedHere, parse_ts)
MIN_VERSION = "v310.183"
ALLOWED_ROLES = {"DATA_PROTECTION_ADMIN"}
def version_ok(requested):
"""Crude but sufficient ordering check on the vNNN.NNN scheme."""
def key(v):
return tuple(int(x) for x in v.lstrip("v").split("."))
try:
return key(requested) >= key(MIN_VERSION)
except ValueError:
return False
def main():
p = argparse.ArgumentParser()
p.add_argument("--host", required=True)
p.add_argument("--user", default=os.environ.get("TINTRI_DPA_USER"))
p.add_argument("--password", default=os.environ.get("TINTRI_DPA_PASS"))
p.add_argument("--api-version", default="v310.191")
p.add_argument("--vm-id", help="only snapshots of this VM")
p.add_argument("--type", default="SCHEDULE_SNAPSHOT",
choices=["SCHEDULE_SNAPSHOT", "USER_GENERATED_SNAPSHOT"])
p.add_argument("--consistency", choices=["CRASH_CONSISTENT",
"VM_CONSISTENT"])
p.add_argument("--max", type=int, default=25,
help="safety ceiling on how many to lock in one run")
p.add_argument("--commit", action="store_true",
help="actually lock. Without this it is a dry run")
a = p.parse_args()
if not a.user or not a.password:
sys.exit("set TINTRI_DPA_USER and TINTRI_DPA_PASS")
if not version_ok(a.api_version):
sys.exit(f"snapshot lock requires {MIN_VERSION} or later; "
f"you requested {a.api_version}")
t = Tintri(a.host, a.user, a.password, a.api_version)
print(f"connected to {a.host}, role reported: {t.role}")
# fail early and clearly rather than at the first 403
if t.role and t.role.upper().replace(" ", "_") not in ALLOWED_ROLES:
t.logout()
sys.exit(f"role {t.role} cannot lock snapshots. "
"The Data Protection Admin role is required; "
"Admin and System Admin are not sufficient.")
params = {"type": a.type}
if a.vm_id:
params["vmId"] = a.vm_id
if a.consistency:
params["consistency"] = a.consistency
targets = []
try:
for snap in t.paginate("/snapshot", params):
if snap.get("isLocked") or snap.get("locked"):
continue # already locked, skip silently
uuid = (snap.get("uuid") or {}).get("uuid") \
if isinstance(snap.get("uuid"), dict) else snap.get("uuid")
uuid = uuid or snap.get("tintriUuid") or snap.get("id")
if not uuid:
continue
targets.append((uuid,
snap.get("vmName") or snap.get("vmId") or "?",
snap.get("description") or ""))
if len(targets) > a.max:
print(f"{len(targets)} candidates exceeds --max {a.max}. "
"Narrow the filter or raise the ceiling deliberately.")
targets = targets[:a.max]
print(f"\n{'ACTION':<10}{'VM':<38}SNAPSHOT")
print("-" * 92)
locked = failed = skipped = 0
for uuid, vm, desc in targets:
if not a.commit:
print(f"{'DRY-RUN':<10}{str(vm)[:37]:<38}{uuid}")
continue
try:
r = t.s.post(f"{t.base}/snapshot/{uuid}/lock",
timeout=t.timeout)
if r.status_code in (200, 204):
print(f"{'LOCKED':<10}{str(vm)[:37]:<38}{uuid}")
locked += 1
elif r.status_code == 501:
print("501 Not Implemented: this is a TGC, not a VMstore. "
"Snapshot lock is VMstore only. Stopping.")
break
elif r.status_code == 409:
skipped += 1 # already in the desired state
elif r.status_code == 403:
print(f"{'DENIED':<10}{str(vm)[:37]:<38}{uuid}")
print(" 403 can mean licensing as well as privilege. "
"Confirm the Lock Snapshot feature is enabled.")
failed += 1
else:
print(f"{'FAILED':<10}{str(vm)[:37]:<38}{uuid} "
f"HTTP {r.status_code}")
failed += 1
except NotImplementedHere:
print("appliance does not implement snapshot lock; stopping")
break
except TintriError as e:
print(f"{'ERROR':<10}{str(vm)[:37]:<38}{e}")
failed += 1
if not a.commit:
print(f"\nDRY RUN: {len(targets)} snapshot(s) would be locked. "
"Re-run with --commit to apply.")
else:
print(f"\nlocked {locked}, already-locked {skipped}, "
f"failed {failed}")
if locked:
print("\nNOTE: unlocking requires a Data Protection Admin "
"whose privileges have been escalated by a Data "
"Protection Escalation Admin, with an expiry time. "
"That is deliberate. Do not lock speculatively.")
finally:
t.logout()
return 0
if __name__ == "__main__":
sys.exit(main())
Why the dry run is the default. Locking is not symmetric with unlocking. Locking needs a DPA. Unlocking needs a DPA whose privileges have been escalated by a separate DPEA account, and that escalation expires. A script that locks a thousand snapshots by accident has created work that requires two roles and a time window to undo. Default to showing what it would do.
08. PowerShell equivalent for the audit
#requires -Version 7.0
<#
tintri-snapshot-audit.ps1
Paginated snapshot audit using the documented Page object.
Read only. A Read Only role account is sufficient.
#>
param(
[Parameter(Mandatory)][string]$Host,
[Parameter(Mandatory)][pscredential]$Credential,
[string]$FullApiVersion = 'v310.191',
[ValidateSet('SCHEDULE_SNAPSHOT','USER_GENERATED_SNAPSHOT')][string]$Type,
[ValidateSet('CRASH_CONSISTENT','VM_CONSISTENT')][string]$Consistency,
[string]$VmId,
[int]$PageSize = 1000,
[double]$OlderThanDays = 30
)
$base = "https://$Host/api/v310"
$body = @{
typeId = 'com.tintri.api.rest.vcommon.dto.rbac.RestApiCredentials'
username = $Credential.UserName
password = $Credential.GetNetworkCredential().Password
fullApiVersion = $FullApiVersion
} | ConvertTo-Json
$role = Invoke-RestMethod -Method Post -Uri "$base/session/login" -Body $body `
-ContentType 'application/json' -SkipCertificateCheck `
-SessionVariable ws -TimeoutSec 30
Write-Host "connected to $Host as role: $role"
try {
$query = @()
if ($Type) { $query += "type=$Type" }
if ($Consistency) { $query += "consistency=$Consistency" }
if ($VmId) { $query += "vmId=$VmId" }
$all = [System.Collections.Generic.List[object]]::new()
$offset = 0
$expected = $null
do {
$q = ($query + @("limit=$PageSize", "offset=$offset")) -join '&'
$page = Invoke-RestMethod -Uri "$base/snapshot?$q" -WebSession $ws `
-SkipCertificateCheck -TimeoutSec 60
if ($null -eq $expected) { $expected = $page.filteredTotal }
foreach ($i in @($page.items)) { $all.Add($i) }
$offset = $all.Count
$more = $page.next -and @($page.items).Count -gt 0
} while ($more)
if ($expected -and $all.Count -ne $expected) {
Write-Warning "collected $($all.Count) of filteredTotal $expected; audit incomplete"
}
Write-Host "snapshots examined: $($all.Count)`n"
$now = Get-Date
$report = $all | Group-Object { $_.vmName ?? $_.vmId } | ForEach-Object {
$snaps = $_.Group
$times = $snaps | ForEach-Object {
$t = $_.createTime ?? $_.creationTime
if ($t -is [long] -or $t -is [int]) {
[DateTimeOffset]::FromUnixTimeMilliseconds($t).LocalDateTime
} elseif ($t) { [datetime]$t }
} | Where-Object { $_ }
[pscustomobject]@{
VM = $_.Name
Snapshots = $snaps.Count
Manual = @($snaps | Where-Object { $_.type -eq 'USER_GENERATED_SNAPSHOT' }).Count
Locked = @($snaps | Where-Object { $_.isLocked -or $_.locked }).Count
OldestDays = if ($times) { [math]::Round(($now - ($times | Sort-Object)[0]).TotalDays, 1) } else { $null }
}
}
$report | Sort-Object OldestDays -Descending |
Format-Table VM, Snapshots, Manual, Locked, OldestDays -AutoSize
$stale = $report | Where-Object { $_.OldestDays -ge $OlderThanDays -and $_.Manual -gt 0 }
if ($stale) {
Write-Host "`nRECLAIM CANDIDATES (user-generated, over $OlderThanDays days)" -ForegroundColor Yellow
$stale | ForEach-Object {
$note = if ($_.Locked) { " ($($_.Locked) LOCKED, cannot delete)" } else { '' }
" {0,-42} {1} manual, oldest {2} days{3}" -f $_.VM, $_.Manual, $_.OldestDays, $note
}
}
}
finally {
Invoke-RestMethod -Uri "$base/session/logout" -WebSession $ws `
-SkipCertificateCheck -TimeoutSec 15 | Out-Null
}
09. What to take from this
- Negotiate the version at login with
fullApiVersion, and check the version matrix against the release each appliance is running. - Always compare your collected count to
filteredTotal. A truncated audit and a complete one look identical without that assertion. - Filter server-side. The parameters exist; use them rather than pulling everything.
- Treat 501 as a skip and 503 as a retry. Neither is a failure of your script.
- Check the role before attempting a privileged operation, so the script tells you which account you need instead of returning 403 forty times.
- Default destructive or hard-to-reverse operations to a dry run. Locking is far easier than unlocking, by design.
Endpoint paths, status code semantics, the Page object, filter parameters, the role matrix and the API version matrix in this post are taken from the published Tintri REST API reference. Response field names on individual DTOs still vary, so dump one snapshot object on your build and confirm before scheduling anything. Nothing here is official guidance from any vendor.
Leave a Reply