Reference library

Cloud + Python

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

29 matches
Cloud + Python easy

Generate Mock CloudFormation Stack Events in Python

Generate a list of mock AWS CloudFormation stack events with random resources, statuses, and timestamps, and print them as JSON.

cloudformation mock aws
Python
import json
import random
from datetime import datetime, timedelta

def generate_mock_stack_events(stack_name="MyTestStack", num_events=10):
    """Generate a list of mock CloudFormation stack events."""
    resources = [
        ("AWS::S3::Bucket", "MyBucket"),
        ("AWS::EC2::Instance", "MyInstance"),
        ("…
15 0 Open
Cloud + Python easy

Generate an Idempotency-Key header mock with UUID in Python

This code provides a mock idempotency service that generates a UUID-based Idempotency-Key header token and validates it, useful for simulating production API behavior in tests.

uuid idempotency mock
Python
import uuid

class MockIdempotencyService:
    def __init__(self):
        self._tokens = {}

    def get_token(self, header_name="Idempotency-Key"):
        token = str(uuid.uuid4())
        self._tokens[header_name] = token
        return token

    def validate(self, header_name="Idempotency-Key"):
        return s…
11 0 Open
Cloud + Python easy

How to Build a Budget Alert Threshold with Mock Notifications in Python

This code calculates budget usage percentage and triggers a mock alert notification when the usage exceeds a defined threshold.

budget alert threshold
Python
budget = 500.0
spent = 620.0
alert_threshold = 0.8

def mock_notify(percent_used):
    if percent_used >= alert_threshold:
        return f"ALERT: Budget usage at {percent_used * 100:.1f}% — over {alert_threshold * 100:.0f}% threshold!"
    return f"OK: Budget usage at {percent_used * 100:.1f}% — under threshold."

pe…
13 0 Open
Cloud + Python easy

How to Calculate Cloud Cost Estimates with a Python Dictionary

Mocks a cloud pricing calculator using a dictionary of service rates and computes total estimated cost for given service hours.

cost-estimate dictionary mock
Python
def estimate_cost(service, hours, rate_table=None):
    if rate_table is None:
        rate_table = {
            "basic": 50,
            "standard": 75,
            "premium": 100
        }
    if service not in rate_table:
        raise ValueError(f"Unknown service: {service}")
    return rate_table[service] * hour…
13 0 Open
Cloud + Python easy

How to Create a Mock STS AssumeRole Credentials Dict in Python

Build a realistic AWS STS AssumeRole response dict with temporary credentials, expiry time, and assumed role ARN for local testing.

aws sts mocking
Python
import json
from datetime import datetime, timedelta, timezone


def mock_sts_credentials(role_arn, session_name, duration=3600):
    now = datetime.now(timezone.utc)
    expiration = now + timedelta(seconds=duration)

    credentials = {
        "Credentials": {
            "AccessKeyId": "ASIAEXAMPLEACCESSKEY",
    …
14 0 Open
Cloud + Python easy

How to Evaluate Mock NACL Rules in Python

Simulate numbered AWS Network ACL rule evaluation with HMAC integrity checks on request payloads.

cloud network nacl
Python
import base64
import json
import hmac
import hashlib

def evaluate_mock_rule(rule_number, request_data, secret):
    """
    Simulates evaluating an NACL-like numbered rule by:
    1. Checking if the rule number exists in the mock policy.
    2. Computing an HMAC over the request payload for integrity.
    """
    # M…
16 0 Open
Cloud + Python easy

How to Generate a Mock EKS Kubeconfig in Python

Generate a minimal kubeconfig dict with a mock EKS cluster entry and dump it to YAML using PyYAML.

kubeconfig eks yaml
Python
import yaml
from pathlib import Path


def mock_eks_kubeconfig(cluster_name: str) -> dict:
    """Return a minimal kubeconfig dict with a mock EKS cluster entry."""
    return {
        "apiVersion": "v1",
        "kind": "Config",
        "clusters": [
            {
                "name": f"arn:aws:eks:us-east-1:123…
14 0 Open
Cloud + Python easy

How to Implement Region Failover Config in Python with Primary and Secondary Mock

This Python class simulates regional failover: it tracks active region, switches to secondary on primary failure, and allows manual recovery.

failover cloud region
Python
import time

class RegionFailoverConfig:
    def __init__(self, primary, secondary):
        self.primary = primary
        self.secondary = secondary
        self.active = primary
        self.failover_count = 0
        self.healthy = True

    def check_health(self):
        """Mock health check - returns True if ac…
15 0 Open
Cloud + Python easy

How to Mock AWS Secrets Manager in Python

Create a lightweight mock of AWS Secrets Manager's get_secret_value API to test secret retrieval without cloud dependencies.

aws secrets-manager mock
Python
import json
from typing import Optional


class MockSecretsManager:
    """A simple mock of AWS Secrets Manager's get_secret_value API."""

    def __init__(self):
        self._secrets: dict[str, str] = {}

    def create_secret(self, secret_id: str, secret_value: str) -> None:
        """Store a secret value under a…
14 0 Open
Cloud + Python easy

How to Mock Auto Scaling Policy Scale Out in Python

Define a mock auto-scaling function that scales out capacity by a factor up to a max, simulating AWS-like events.

auto-scaling cloud simulation
Python
def mock_scale_out(current_capacity: int, max_capacity: int, scale_factor: int = 1) -> tuple:
    """
    Mock auto-scaling policy: scales out by the specified factor
    if capacity allows, capped at max_capacity.
    """
    if current_capacity >= max_capacity:
        return current_capacity, False
    
    new_cap…
14 0 Open
Cloud + Python easy

How to Mock Azure Service Bus Queue in Python

A lightweight in-memory mock of the Azure Service Bus queue API for local testing without cloud dependencies.

azure service-bus mock
Python
import json
import time
from collections import deque

class ServiceBusQueueMock:
    def __init__(self, queue_name):
        self.queue_name = queue_name
        self._messages = deque()
        self._dead_letter_queue = deque()
        self._message_counter = 0

    def send_message(self, body, message_id=None, prop…
14 0 Open
Cloud + Python easy

How to Mock CloudFront Invalidation Paths in Python

Build a sorted, deduplicated list of CloudFront invalidation paths from a set of file paths, adding implicit index.html entries.

cloudfront aws cli
Python
import argparse

def build_invalidation_paths(files, include_index=True):
    """
    Create CloudFront invalidation paths from a list of files.
    Converts file names to root-relative paths and optionally adds /index.html.
    """
    paths = []
    for f in files:
        f = f.strip()
        if not f:
           …
15 0 Open
Cloud + Python easy

How to Mock DynamoDB with a Simple Dict Store in Python

A lightweight in-memory DynamoDB mock that stores items in a dict and supports put, get, and query-by-value operations for local testing.

dynamodb mock testing
Python
import json
from typing import Any, Dict, Optional


class MockDynamoDB:
    def __init__(self) -> None:
        self._store: Dict[str, Dict[str, Any]] = {}

    def put_item(self, table_name: str, item: Dict[str, Any]) -> None:
        key = str(item.get("id"))
        if table_name not in self._store:
            se…
14 0 Open
Cloud + Python easy

How to Mock ELB Target Health Status in Python

Simulate AWS Elastic Load Balancer target health checks with a Python dict that mutates status and healthy host counts.

elb mock healthcheck
Python
from random import randint

def elb_target_mock_status(target_id, healthy=True):
    targets = {
        1: {"Id": "i-001", "Status": "healthy", "Port": 80, "HealthyHostCount": 1},
        2: {"Id": "i-002", "Status": "unhealthy", "Port": 80, "HealthyHostCount": 0},
        3: {"Id": "i-003", "Status": "healthy", "Por…
13 0 Open
Cloud + Python easy

How to Mock GCP Cloud Functions HTTP Events in Python

Simulate a GCP Cloud Functions HTTP event with a Python mock handler that constructs a realistic event payload and returns a JSON response.

gcp cloud-functions mock
Python
import json
from datetime import datetime, timezone


def mock_http_event(data):
    """Simulate a GCP Cloud Function HTTP event."""
    event = {
        "event_id": "mock-event-12345",
        "timestamp": datetime.now(timezone.utc).isoformat(),
        "event_type": "google.cloud.functions.http",
        "resource"…
13 0 Open
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…
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 mock EC2 describe-instances tag filtering in Python

Simulate AWS EC2 describe-instances with tag-based filtering using a mock dataset and conditional list comprehension.

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


def mock_describe_instances(tag_key: str, tag_value: str) -> list[dict]:
    """Simulate EC2 describe-instances with tag filtering."""
    all_instances = [
        {"InstanceId": "i-0abc123", "State": "running", "Tags": [{"Key": "Name", "Value": "web-server"}, {"K…
15 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 easy

Mock Azure Blob Upload and Download in Python

Simulate Azure Blob Storage upload and download operations with a lightweight in-memory mock class for testing.

azure mock testing
Python
import io
import json
from datetime import datetime, timezone

class MockBlob:
    def __init__(self, name):
        self.name = name
        self.content = b""
        self.properties = {
            "last_modified": datetime.now(timezone.utc).isoformat(),
            "size": 0,
        }

    def upload(self, data, …
14 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 ECS Task Run Stop Status Dict in Python

Build a mock ECS task status dictionary with RUNNING/STOPPED states using the standard library.

aws ecs mocking
Python
from datetime import datetime, timezone


def mock_ecs_task_status(task_id: str, state: str = "RUNNING") -> dict:
    """Return a mock ECS task status dictionary."""
    return {
        "taskArn": f"arn:aws:ecs:us-east-1:123456789012:task/cluster/{task_id}",
        "taskDefinition": "arn:aws:ecs:us-east-1:1234567890…
15 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.