How to Simulate a Packer AMI Build in Python
A simple Python class that mimics a Packer AMI build lifecycle — creates a build object, transitions its state to completed, and prints a JSON snapshot.
Python code
29 linesimport json
class PackerBuildMock:
def __init__(self, name, ami_id, region="us-east-1", state="pending"):
self.name = name
self.ami_id = ami_id
self.region = region
self.state = state
def build(self):
if self.state == "pending":
self.state = "completed"
return f"Packer built AMI {self.ami_id} ({self.name}) in {self.region}"
return f"Build for {self.name} already finished"
def snapshot(self):
return {
"name": self.name,
"ami_id": self.ami_id,
"region": self.region,
"state": self.state,
}
if __name__ == "__main__":
build = PackerBuildMock("ubuntu-22.04", "ami-0c55b159cbfafe1f0")
print(build.build())
print(json.dumps(build.snapshot(), indent=2))
Output
Packer built AMI ami-0c55b159cbfafe1f0 (ubuntu-22.04) in us-east-1
{
"name": "ubuntu-22.04",
"ami_id": "ami-0c55b159cbfafe1f0",
"region": "us-east-1",
"state": "completed"
}
How it works
The PackerBuildMock class stores build metadata like name, AMI ID, region, and state. The build() method simulates the build process by changing the state from pending to completed and returning a confirmation message. The snapshot() method returns a dictionary of the build's current attributes, which is then serialized to JSON with json.dumps for readable output. Using a class allows you to track and update build state, making it easy to mock complex build tools in tests or demos.
Common mistakes
- Forgetting to import `json` before using `json.dumps`
- Assuming state resets to pending after a build, which the mock does not support
- Using a real AWS call instead of mocking for simple demonstrations
Variations
- Use a dataclass with `@dataclass` for a more concise definition
- Add a `clone()` method to duplicate builds before state changes
Real-world use cases
- In CI pipelines, simulating AMI builds before actual AWS provisioning to test deployment logic.
- During development, mocking Packer builds to validate configuration management scripts without cloud costs.
- In integration tests, standing in for image builder tools to verify downstream provisioning steps.
Sponsored
More from Production deployment patterns
- Auto Rollback on Error Rate Exceeded in Python medium
- Automate Semantic Versioning with Conventional Commits in Python medium
- Design a Data Helper for Beginners in Python easy
- Docker healthcheck CMD mock in Python easy
- Generate a Mock Artifact Version Tag in Python easy
- Generate a docker-compose.yml with mock services in Python easy
Keep learning
Related tutorials and quizzes for this topic.