Reference library

Cloud + Python

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

21 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

How to Build a Multi-Cloud Config Loader with Provider Switching in Python

Load cloud provider configurations (AWS, Azure, GCP) from JSON files using a provider dispatch pattern in Python.

cloud config json
Python
import json
from pathlib import Path
from dataclasses import dataclass
from typing import Dict, Any


@dataclass
class CloudConfig:
    provider: str
    region: str
    settings: Dict[str, Any]


class ConfigLoader:
    def __init__(self, config_dir: str = "configs"):
        self.config_dir = Path(config_dir)
      …
12 0 Open
Cloud + Python easy

How to Calculate VPC Subnet CIDR Details in Python

Compute network address, broadcast address, address count, prefix length, and netmask for any IPv4 CIDR using the Python standard library's ipaddress module.

ipaddress cidr vpc
Python
import ipaddress


def subnet_details(cidr: str) -> dict:
    network = ipaddress.ip_network(cidr, strict=False)
    return {
        "network_address": str(network.network_address),
        "broadcast_address": str(network.broadcast_address),
        "num_addresses": network.num_addresses,
        "prefix_length": ne…
11 0 Open
Cloud + Python easy

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.

aws scp json
Python
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…
14 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 Enforce Tag Policies on AWS Resources in Python

Build a reusable Python class that checks AWS resources against a required-tag policy and reports compliance with missing tags.

aws tagging compliance
Python
import json
from dataclasses import dataclass, field
from typing import Dict, List


@dataclass
class Resource:
    arn: str
    tags: Dict[str, str] = field(default_factory=dict)


class TagPolicyEnforcer:
    def __init__(self, required_tags: List[str]):
        self.required_tags = set(required_tags)

    def enfor…
15 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 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 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 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 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 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

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 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
Cloud + Python easy

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.

lambda aws mock
Python
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…
14 0 Open
Cloud + Python easy

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.

aws sns pub-sub
Python
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…
13 0 Open
Cloud + Python easy

Mock SSM Parameter Store Get Parameters by Path in Python

This code implements a simple mock of the AWS SSM Parameter Store get_parameters_by_path API, returning parameters under a given path with recursive and non-recursive options.

aws ssm parameter-store
Python
import json

class MockSSM:
    def __init__(self, parameters):
        self.parameters = parameters

    def get_parameters_by_path(self, path, recursive=True):
        result = []
        for key, value in self.parameters.items():
            if recursive:
                if key.startswith(path):
                   …
16 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.