Cloud + Python
Cloud SDK patterns — storage, serverless handlers, secrets, and deployment helpers.
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.
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…
How to Convert Python Dict to JSON and Back
Convert Python dictionaries to JSON text and back with a simple helper that serializes and deserializes data structures.
import json
from datetime import datetime, timezone
def convert_data(data, source_format=None, target_format="json"):
"""
Convert Python data structures to txt/json and back.
For beginners: shows how to serialize/deserialize.
"""
if source_format == "json" and target_format == "dict":
ret…
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.
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",
…
How to Evaluate IAM Policy Allow vs Deny in Python
Evaluate an AWS-style IAM policy dict with explicit deny overriding allow and default deny.
import json
def evaluate_policy(action, resource, policy):
"""Evaluate an IAM-like policy dict.
Explicit deny wins over allow. Default is deny.
"""
for statement in policy.get("Statement", []):
effect = statement.get("Effect")
actions = statement.get("Action", [])
resources = …
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.
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…
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.
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…
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.
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…
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.
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…
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.
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…
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.
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…
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.
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…
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.
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…
How to mock boto3 S3 upload in Python
Shows how to mock the boto3 S3 client with unit tests and wrap an upload function to return a dictionary with status details.
import boto3
from unittest.mock import Mock, patch
class S3Uploader:
def __init__(self, bucket_name):
self.bucket_name = bucket_name
self.s3 = boto3.client("s3", region_name="us-east-1")
def upload_file(self, local_path, s3_key):
self.s3.upload_file(local_path, self.bucket_name, s3_ke…
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.
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…
Mock ECS Task Run Stop Status Dict in Python
Build a mock ECS task status dictionary with RUNNING/STOPPED states using the standard library.
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…
Mock Lambda handler event context dict in Python
Simulates an AWS Lambda invocation by passing a mock event dict and context object to a handler, then prints the response.
import json
def lambda_handler(event, context):
"""
A mock AWS Lambda handler that processes an event dict and context object.
Demonstrates the typical Lambda function signature and basic event/context usage.
"""
print("Received event:", json.dumps(event, indent=2))
print("Function name:", co…
Mock SNS publish subscribe fanout in Python
Simulates AWS SNS publish/subscribe with an in-memory topic-to-endpoints dict that fans out messages to all subscribers.
class SNSMock:
def __init__(self):
self.topics = {}
def create_topic(self, name):
if name not in self.topics:
self.topics[name] = []
return f"arn:aws:sns:us-east-1:123456789012:{name}"
def subscribe(self, topic_name, endpoint):
self.topics.setdefault(topic_name…
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.