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.

Easy Python 3.9+ Aug 9, 2026 Production deployment patterns 13 views 0 copies

Python code

29 lines
Python 3.9+
import 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

stdout
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

  1. Use a dataclass with `@dataclass` for a more concise definition
  2. 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

Run this sample

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

Open editor

More from Production deployment patterns

Related tutorials and quizzes for this topic.