Reference library

Cloud + Python

Cloud SDK patterns — storage, serverless handlers, secrets, and deployment helpers.

39 matches
Cloud + Python easy

How to Mock Pulumi Stack Outputs in Python

Create a dict-like mock of Pulumi stack outputs for local testing and scripts without running pulumi.

pulumi mock cloud
Python
from collections import defaultdict

class StackOutputMock:
    def __init__(self, outputs: dict):
        self.outputs = dict(outputs)
    
    def export(self):
        return self.outputs
    
    def get(self, key: str, default=None):
        return self.outputs.get(key, default)
    
    def keys(self):
        r…
12 0 Open
Cloud + Python easy

How to Paginate a List with a Generator in Python

Define a generator that yields list items in fixed-size pages, simulating pagination for cloud resource APIs.

generator pagination cloud
Python
from typing import List, Iterator

def paginate_generator(items: List[str], page_size: int = 3) -> Iterator[List[str]]:
    """Yield items in fixed-size chunks with a mock pagination pattern."""
    for i in range(0, len(items), page_size):
        yield items[i:i + page_size]

if __name__ == "__main__":
    resources…
13 0 Open
Cloud + Python easy

How to Parse Cloud JSON Data in Python

A helper function that safely parses JSON payloads from cloud services into a clean dict with defaults and error handling.

json cloud parsing
Python
import json
from typing import Dict, Any

def parse_cloud_data(payload: str) -> Dict[str, Any]:
    """Parse a JSON payload from a cloud service into a clean dict."""
    try:
        data = json.loads(payload)
        return {
            "status": data.get("status", "unknown"),
            "region": data.get("region…
15 0 Open
Cloud + Python easy

How to Parse Terraform Output JSON in Python

Parse Terraform's JSON output into a flat dictionary of values using the standard library json module.

terraform json cloud
Python
import json

def parse_terraform_output(raw_output):
    """Parse Terraform JSON output into a flat dict of values."""
    try:
        data = json.loads(raw_output)
    except json.JSONDecodeError as e:
        raise ValueError(f"Invalid JSON: {e}")

    return {key: value["value"] for key, value in data.items()}


i…
11 0 Open
Cloud + Python easy

How to Parse an AWS API Gateway Proxy Event in Python

Extract and parse common fields from a mock API Gateway proxy event, turning the JSON body into a native Python dict.

aws lambda api-gateway
Python
import json
from typing import Any, Dict, Optional


def parse_proxy_event(event: Dict[str, Any]) -> Dict[str, Any]:
    """Extract and parse common fields from an API Gateway proxy event."""
    body = event.get("body", "")
    if isinstance(body, str):
        body = json.loads(body) if body else {}
    elif body is…
13 0 Open
Cloud + Python easy

How to Validate AWS Security Group Ingress Rules in Python

Validates AWS security group ingress rules (protocol, port ranges, CIDR, description) and returns a list of errors or OK.

aws security-groups validation
Python
from dataclasses import dataclass
from typing import List, Optional

@dataclass
class SecurityGroupRule:
    protocol: str
    port_range: tuple
    cidr: str
    description: str = ""

def validate_ingress_rule(rule: SecurityGroupRule) -> List[str]:
    """Validate a security group ingress rule against common AWS pat…
11 0 Open
Cloud + Python easy

How to Validate Data Fields and Types in Python

Validate required fields and type correctness in a Python dictionary with small helper functions, returning a list of clear error messages.

validation data dict
Python
import json
from typing import Any, Dict, List


def validate_data(data: Dict[str, Any], required_fields: List[str]) -> List[str]:
    """Check required fields exist and are non-empty. Return list of errors."""
    errors = []
    for field in required_fields:
        value = data.get(field)
        if value is None o…
13 0 Open
Cloud + Python easy

How to plan reserved capacity from a CSV in Python

Read a CSV of workloads with csv.DictReader and compute a mock reserved capacity plan with headroom per service.

csv capacity-planning cloud
Python
import csv
import io


def plan_reserved_capacity(workloads_csv: str) -> list[dict]:
    """Read a CSV of workloads and return a plan for reserved capacity per service."""
    reader = csv.DictReader(io.StringIO(workloads_csv))
    plan = []
    for row in reader:
        service = row["service"]
        avg_load = fl…
11 0 Open
Cloud + Python easy

Mock AWS Spot Instance Interruption Handler in Python

A Python class that simulates AWS Spot instance interruption checks, handling the 10% chance of termination, logging state-saving, and storing notice details.

aws spot-instances simulation
Python
import time
import random

class SpotInstanceHandler:
    def __init__(self, instance_id):
        self.instance_id = instance_id
        self.interruption_notices = []

    def start(self):
        print(f"Spot instance {self.instance_id} started")

    def check_interruption(self):
        # Simulate random interrup…
13 0 Open
Cloud + Python medium

Mock CDK Synth Output in Python for Template Testing

Simulate AWS CDK synth output with MagicMock to test or preview CloudFormation templates without running a real CDK app.

aws cdk cloudformation
Python
import json
from unittest.mock import MagicMock

def mock_cdk_synth() -> dict:
    """Simulate AWS CDK synth output for a simple S3 bucket."""
    cdk_app = MagicMock()
    cdk_app.synth.return_value.template = {
        "Resources": {
            "MyBucket": {
                "Type": "AWS::S3::Bucket",
              …
12 0 Open
Cloud + Python easy

Mock CloudWatch put_metric_data in Python

Simulate AWS CloudWatch put_metric_data with validation and formatted output for local testing without AWS.

cloudwatch aws mock
Python
import json
from datetime import datetime, timezone


def put_metric_data(namespace, metric_data_list):
    """
    Mock AWS CloudWatch put_metric_data.
    Validates and prints the metrics that would be sent.
    """
    timestamp = datetime.now(timezone.utc).isoformat()
    print(f"[MockCloudWatch] Received request …
15 0 Open
Cloud + Python easy

Mock GCP Secret Manager access version in Python

A minimal mock of GCP Secret Manager that stores secret versions, retrieves payloads by version, and logs access timestamps.

gcp secret-manager mock
Python
import json
import time
from datetime import datetime, timezone


class MockSecretManager:
    """Minimal mock of GCP Secret Manager access/version behavior."""

    def __init__(self):
        self._secrets = {}
        self._access_log = []

    def create_secret(self, secret_id: str, payload: str) -> dict:
        …
15 0 Open
Cloud + Python medium

Mock GCP storage bucket blob upload in Python

Simulate uploading a blob to a GCP Storage bucket for testing without hitting the cloud.

gcp mock storage
Python
import io
from datetime import datetime
from unittest.mock import MagicMock, patch


class MockBlob:
    """Simulates a GCP storage blob for unit testing."""
    def __init__(self, name):
        self.name = name
        self.uploaded_at = None
        self.content = b""

    def upload_from_file(self, file_obj):
    …
14 0 Open
Cloud + Python medium

Mock S3, GCS, and Azure storage with a Python abstract interface

Define an abstract Storage interface and implement a local, filesystem-backed mock so S3, GCS, and Azure code can be tested without cloud dependencies.

storage abstraction testing
Python
from abc import ABC, abstractmethod
from pathlib import Path


class Storage(ABC):
    @abstractmethod
    def put(self, name: str, data: bytes) -> None:
        pass

    @abstractmethod
    def get(self, name: str) -> bytes:
        pass


class LocalStorage(Storage):
    def __init__(self, base_dir: str = "mock_sto…
14 0 Open
Cloud + Python easy

Pick a Random Region with Mock Carbon Intensity in Python

Selects a random region from a list and generates a mock carbon intensity value using Python's random module.

random mock-data cloud
Python
import random

def pick_region_intensity(regions, seed=42):
    random.seed(seed)
    selected = random.choice(regions)
    intensity = random.randint(1, 10)
    return selected, intensity

if __name__ == "__main__":
    regions = ["North", "South", "East", "West"]
    selected, intensity = pick_region_intensity(regio…
14 0 Open

Browse by section

Each section groups closely related Python snippets.

Cloud + Python — Python code examples

What you will find here

This page collects cloud + python snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.

Samples vs tutorials and challenges

Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.