Build: Local EC2 Testing with Moto and Python

Build: Local EC2 Testing with Moto and Python
When you’re building Python tools
that work with AWS services, you don’t always want to reach into the cloud
during development. It’s slow. It’s expensive. And it’s dangerous if your
code’s not fully baked. That’s where Moto comes in — it mocks AWS
APIs locally so you can simulate behavior and write repeatable, offline tests.
Here’s a real-world walkthrough that uses Moto to fake EC2 instances, test a Python script, and return real JSON output — no AWS account required.
Here’s a real-world walkthrough that uses Moto to fake EC2 instances, test a Python script, and return real JSON output — no AWS account required.
Step 1: Set Up Your Working Directory
Start by creating a new folder:
Then navigate into it:
We’ll isolate our dependencies:
(MacOS and Linux) Now activate the virtual environment:
We’ll pin Moto to a known working version for EC2 support. Install both:
Step 4: Create the Test Script
Create a file named test_ec2_reporter.py:
Paste the following code:
Now ensure that the Python script is executable:
Now test it locally:
Step 6: Deactivate the Virtual Environment
Run this command the exit the virtual environment:
Final Thoughts
This is a clean pattern you can reuse for mocking any supported AWS service: S3, DynamoDB, Lambda, and more. Moto keeps your testing fast, cheap, and entirely local. When you’re ready to step into real cloud behavior — IAM, networking, multi-service flows — that’s when you graduate to LocalStack Pro.
And yes, we’ll go wild with pytest and unittest soon. But for today, this is real progress.
This is a clean pattern you can reuse for mocking any supported AWS service: S3, DynamoDB, Lambda, and more. Moto keeps your testing fast, cheap, and entirely local. When you’re ready to step into real cloud behavior — IAM, networking, multi-service flows — that’s when you graduate to LocalStack Pro.
And yes, we’ll go wild with pytest and unittest soon. But for today, this is real progress.
Need AWS Expertise?
We'd love to help you with your AWS projects. Feel free to reach out to us at info@pacificw.com.
Written by Aaron Rose, software engineer and technology writer at Tech-Reader.blog.
Comments
Post a Comment