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.

Easy Python 3.9+ Aug 9, 2026 Cloud + Python 15 views 0 copies

Python code

41 lines
Python 3.9+
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"),
        ("AWS::IAM::Role", "MyRole"),
        ("AWS::SNS::Topic", "MyTopic"),
        ("AWS::Lambda::Function", "MyFunction")
    ]
    statuses = ["CREATE_IN_PROGRESS", "CREATE_COMPLETE", "UPDATE_IN_PROGRESS", "UPDATE_COMPLETE"]
    logical_ids = [f"{resource_type.split('::')[-1]}{idx}" for idx, (resource_type, _) in enumerate(resources)]
    
    events = []
    start_time = datetime.utcnow() - timedelta(minutes=num_events)
    
    for i in range(num_events):
        resource_type, resource_name = random.choice(resources)
        event = {
            "StackName": stack_name,
            "EventId": f"{stack_name}-{i:04d}-{random.randint(1000, 9999)}",
            "LogicalResourceId": random.choice(logical_ids),
            "PhysicalResourceId": f"arn:aws:{resource_name.lower()}:{random.randint(10000, 99999)}",
            "ResourceType": resource_type,
            "Timestamp": (start_time + timedelta(minutes=i)).isoformat() + "Z",
            "ResourceStatus": random.choice(statuses),
            "ResourceStatusReason": "User Initiated" if i % 2 == 0 else "Resource creation successful"
        }
        events.append(event)
    
    for event in events:
        print(json.dumps(event, indent=2))
    
    return events

if __name__ == "__main__":
    stack_events = generate_mock_stack_events("ProductionStack", 5)
    print(f"\nGenerated {len(stack_events)} stack events.")

Output

stdout
{
  "StackName": "ProductionStack",
  "EventId": "ProductionStack-0000-1234",
  "LogicalResourceId": "Bucket0",
  "PhysicalResourceId": "arn:aws:mybucket:12345",
  "ResourceType": "AWS::S3::Bucket",
  "Timestamp": "2023-01-01T00:00:00Z",
  "ResourceStatus": "CREATE_IN_PROGRESS",
  "ResourceStatusReason": "User Initiated"
}
... (more events) ...

Generated 5 stack events.

How it works

The function uses random.choice to pick from resource and status lists, and timedelta to create sequential timestamps. The event dictionary includes realistic CloudFormation fields like LogicalResourceId and PhysicalResourceId. A formatted JSON dump makes the output readable. The code prints each event with indent=2 for clarity, and returns the list for further use.

Common mistakes

  • Using `datetime.now()` instead of `datetime.utcnow()` for consistent UTC timestamps.
  • Forgetting to add 'Z' suffix to the ISO timestamp, making it non-UTC.
  • Hardcoding the same resource for all events instead of using `random.choice`.

Variations

  1. Use `random.seed()` for reproducible mock data.
  2. Generate events as a JSON string for direct API response simulation.

Real-world use cases

  • Simulating CloudFormation events in local development to test event processing code without AWS.
  • Creating test fixtures for unit tests of infrastructure monitoring or change detection scripts.
  • Building dashboards or visualizations that need sample event data for UI development.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Cloud + Python

Related tutorials and quizzes for this topic.