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.
Python code
41 linesimport 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
{
"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
- Use `random.seed()` for reproducible mock data.
- 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
More from Cloud + Python
- Build a URL Shortener Client with Python medium
- Create a Cloud Storage Helper Class in Python easy
- Create a Data Helper Class for Beginners in Python easy
- Cross Account Role Chaining Mock Credentials in Python medium
- Exponential Backoff with Jitter for Cloud API Calls in Python medium
- Generate a Mock Presigned URL in Python with HMAC medium
Keep learning
Related tutorials and quizzes for this topic.