Cloud + Python
Cloud SDK patterns — storage, serverless handlers, secrets, and deployment helpers.
Create a Cloud Storage Helper Class in Python
Build a simple local file-based helper class that mimics cloud storage operations like save, load, and list JSON objects.
import datetime
import json
from pathlib import Path
class CloudDataHelper:
"""Simple helper for reading/writing JSON files in a cloud-style folder."""
def __init__(self, base_dir: str = "cloud_storage"):
self.base_dir = Path(base_dir)
self.base_dir.mkdir(exist_ok=True)
def save_json(se…
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.
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"),
("…
How to Check an SCP Deny List in Python
Load a JSON SCP policy file, extract the deny_list, and check if a target ARN is denied.
import json
from pathlib import Path
def evaluate_scp_deny_list(policy_path: Path, target_path: str) -> bool:
policy = json.loads(policy_path.read_text())
deny_list = policy.get("deny_list", [])
return target_path in deny_list
if __name__ == "__main__":
policy_file = Path("scp_policy.json")
pol…
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 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.
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:
…
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.
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"…
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.
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…
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.
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…
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 EC2 describe-instances tag filtering in Python
Simulate AWS EC2 describe-instances with tag-based filtering using a mock dataset and conditional list comprehension.
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…
Mock S3 List Objects Paginator in Python
This code implements a mock S3 paginator that yields pages of object keys, mimicking the behavior of boto3's list_objects_v2 paginator for local testing.
import json
from datetime import datetime, timezone
class MockS3Paginator:
"""A mock S3 list_objects_v2 paginator returning pages of keys."""
def __init__(self, bucket, all_keys, page_size=1000):
self.bucket = bucket
self.all_keys = all_keys
self.page_size = page_size
def pagina…
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.
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…
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.