Cloud API automation
Start with a complete inventory
Imagine a fictional bookstore with two test VMs. The first inventory response contains vm-a and a continuation token; the second contains vm-a and vm-b. A script that reads only the first page undercounts resources. A script that treats an incomplete result as empty may propose deleting or recreating resources that already exist. The goal is to return an inventory plus an explicit completeness status, not merely a list.
A resource identifier is an address within a provider's resource model. Store provider, environment, account or subscription or project, service, region or zone if relevant, and the full identifier. Names alone are often ambiguous. AWS ARNs and service-specific IDs, Azure ARM resource IDs, and Google Cloud resource names/self-links are different formats. Keep opaque identifiers intact; avoid deriving privileges from a name or guessing a missing scope.
Interfaces and version contracts
REST APIs expose operations through documented requests and responses. A CLI is a command-line wrapper; an SDK adds language-specific client objects, serializers, authentication, retries and sometimes paginators and operation pollers. A successful CLI exit or HTTP response can mean a request was accepted rather than that the desired resource is ready. SDK package versions and service API versions are separate; an upgrade in one may change defaults without changing the other.
Pin supported client dependencies and lockfiles, record API version and scope, and run schema/contract tests before upgrades. Handle documented optional fields and unknown enum values deliberately. Validate types and required fields before using results. Never interpret an unknown state as success. JSON output is easier to parse reliably than human-oriented tables; check exit status and error channel as well. Structured output can contain sensitive data, so redact before storing.
| Provider | Client family | Structured interface |
|---|---|---|
| AWS | AWS SDKs and aws CLI | Service operations, JSON output and service-specific pagination |
| Azure | Azure SDKs and az CLI | ARM API versions, resource IDs, paged collections and operation pollers |
| Google Cloud | Cloud Client Libraries and gcloud CLI | Service-specific resource paths, paging and operation objects |
These are comparisons, not interchangeable APIs. No real CLI commands are executed here.
Authentication and credential provider chains
The client authenticates as an identity; authorization decides whether that identity can act on the target. For AWS many requests use Signature Version 4, generated by the supported SDK or CLI; signing binds request components to credentials and time. Azure Resource Manager normally accepts a Microsoft Entra access token; Google Cloud client libraries commonly obtain OAuth access tokens through Application Default Credentials (ADC). Other services or endpoints may differ.
Credential chains try configured sources such as workload identity, managed identity or development credentials according to language and version. AWS standardized providers, Azure Identity and Google ADC do not have identical search order. A developer login may accidentally select a different tenant than the intended workload. Prefer short-lived workload credentials, explicit approved scope and least privilege; never log tokens, signed URLs, headers or credential configuration. Let maintained libraries handle refresh, and reuse clients where supported. Verify expected identity and scope in an authorized environment before any write. This lab does not inspect any environment or credentials.
Pagination and asynchronous states
Treat a continuation token as opaque; pass it to the same operation with the same filters and scope. SDK paginators may fetch more requests lazily, and a CLI may aggregate multiple pages. Distinguish page size, total item limits and page count. A page may be empty yet provide a token. Bound total requests, records and elapsed time. Detect repeated cursors, malformed data and missing pages. Deduplicate stable IDs when appropriate, but a changing collection is not necessarily a consistent snapshot; use service-supported snapshot or version semantics if required.
A mutation can return an operation ID rather than a finished resource. Store the operation reference and scope before polling. Azure ARM may supply Azure-AsyncOperation or Location and Retry-After; Google Compute Engine uses scoped operation resources; AWS APIs vary, with some offering SDK waiters for resource state. Poll with a deadline, respect documented intervals, and distinguish failed, pending, succeeded and unknown. A terminal operation may contain an error. Verify actual postconditions separately: a resource state can converge before application readiness, and some reads may be stale. Do not retry creation merely because polling timed out.
Offline pagination and polling lab
Run the following Python 3 snippet locally; it uses only dictionaries and lists, with no network or credentials. The invented response contract uses items and next, with missing next treated like null; this is not a provider SDK. The page bound is three calls and the poll bound three observations. In a real client also bound item count and wall-clock time; malformed output never authorizes a write.
def inventory(pages, limit=3): token = "start" seen, ids = set(), set() for _ in range(limit): if token in seen or token not in pages: return "incomplete", sorted(ids) seen.add(token) page = pages[token] if not isinstance(page, dict): return "malformed", sorted(ids) items, following = page.get("items"), page.get("next") if (not isinstance(items, list) or any(not isinstance(i, str) or not i for i in items) or (following is not None and (not isinstance(following, str) or not following))): return "malformed", sorted(ids) ids.update(items) if following is None: return "complete", sorted(ids) token = following return "incomplete", sorted(ids)
def poll(responses, operation_id, limit=3): for response in responses[:limit]: if not isinstance(response, dict) or response.get("id") != operation_id: return "unknown" state = response.get("state") if state == "failed": return "failed" if state == "done": return "succeeded" if response.get("error") is None else "failed" if state != "pending": return "unknown" return "unknown"
pages = {"start": {"items": ["vm-a"], "next": "p2"}, "p2": {"items": ["vm-a", "vm-b"], "next": None}}print(inventory(pages))print(poll([{"id": "op-1", "state": "pending"}, {"id": "op-1", "state": "done"}], "op-1"))Expected output:
('complete', ['vm-a', 'vm-b'])succeededThe set deduplicates IDs while sorted makes the output deterministic. Try a page pointing back to start, a missing second page, an empty page with a valid continuation, and a done response with an error. The inventory can return partial IDs, but only complete means the local enumeration reached its end; neither proves a snapshot. A poll result of unknown requires reconciliation, not a new mutation.
Operational checklist
Record scope, client/API version, request ID, operation ID and sanitized outcome. Distinguish read-only inventory from writes and note even reads may incur cost or expose sensitive metadata. Never pass arbitrary URL, method, credentials or command arguments from a learner into a cloud proxy. Use fixed offline fixtures. For real deployments, require reviewed adapters, approved operations, resource limits, least privilege and a documented owner. Test against the selected service version before release.
Review official evidence in the V58 source register for AWS credential chains and CLI pagination, Azure SDK paging and ARM operations, and Google Cloud ADC and Compute operations. Provider examples are conceptual, not live-tested.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Cloud API automation — knowledge check
Choose the best answer for each offline scenario.
A page contains no items but a continuation token. What should a bounded inventory do?
A terminal operation includes an error. What is the result?
Why record full resource scope?
Which credential practice is safest?
What does a complete paginated inventory prove?