Cloud / IaC · Freelance

Per-Client WordPress Hosting with Packer, Terraform and Ansible

A Makefile toolchain bakes an AMI with Packer, builds shared infrastructure with Terraform, and onboards or removes clients through Ansible-generated Terraform.

  • Packer
  • Ansible
  • Terraform
  • ALB
  • Auto Scaling
  • EFS
  • RDS
  • Route 53

// Why this matters

Multi-tenant WordPress hosting on AWS looks easy until you have twenty clients. One shared instance means one noisy site can take down the rest and every plugin update is a gamble. One full stack per client means twenty load balancers and a bill nobody enjoys. The middle path is a shared front door with isolated back ends.

The business goal was fast, repeatable onboarding: a sales call ends and a working site exists within the hour, built the same way every time, and removing a client who leaves is as cheap and safe as adding one. That only works if the process is a single command rather than a runbook.

This post walks through the toolchain I built for a freelance client: image build, base stack, per-client module and the thin Makefile and Ansible layer that ties them together. Names and sizes are placeholders.

// The problem

WordPress is stateful in two ways: a database and a content directory (uploads, themes, plugins). Scaling it horizontally means moving both off the instance. If you do not, adding a second node gives you two sites that disagree about which images exist.

The infrastructure also splits into two lifecycles that are easy to conflate. The load balancer, listeners, certificate and log bucket change rarely and are shared. The target group, rule, scaling group, file system, database and DNS record exist once per client and appear and disappear often. Putting both in one Terraform state means every onboarding runs a plan against everything, and a mistake in one client can touch another.

Finally, configuration that is only known after the database exists, like its endpoint, has to reach the running instances without baking it into the image. Otherwise you need a different image per client, which defeats the point of baking.

// The solution

Split the work by how often it changes. Packer produces an immutable AMI with the web server stack and the WordPress container definition. The base Terraform stack builds the shared ALB with an HTTPS listener that returns a fixed response by default, so an unknown hostname never reaches a client. The client module attaches a host-header listener rule, a target group and an Auto Scaling group to that listener.

State is separate per client. The Ansible role copies a client template into client-terraform/<subdomain>/, fills in the subdomain, and runs Terraform there. A client directory therefore has its own backend key and its own plan. Destroying one is terraform destroy in that directory followed by deleting it. I rejected a single module with a for_each over a client map because it is neater but couples every client to every apply; one bad variable breaks onboarding for all.

Runtime configuration travels through user data. The database is created first, and the launch configuration interpolates its endpoint into the boot script, which writes an env file and starts the container. The shared file system is mounted at boot through the EFS mount helper, so every node in the group sees the same uploads. A sticky load-balancer cookie keeps admin sessions stable.

Alternatives I weighed: containers on ECS (good, but the client already had WordPress hardened in a VM-style image), a managed WordPress platform (rejected on control and cost), and one ALB per client (rejected on cost). The shared ALB with host-based routing was the cheapest design that still isolated compute, storage and data. The same split of fixed versus repeating infrastructure shows up in Five-Minute Customer Onboarding: Forms, Workspaces and a Subnet Allocator and Demolition in Dependency Order: Safe, Re-runnable Offboarding.

How it flows flow1. Bake image → 2. Base stack → 3. Onboard client → 4. Template → 5. Client infra → 6. Runtime config → 7. Scale → 8. Offboard01Bake image02Base stack03Onboard client04Template05 · GATEClient infra06Runtime config07Scale08Offboard
How it flows. End-to-end flow. Dashed pink nodes are gates: points where a human or a check must pass before the next stage runs.
  1. Bake imagePacker and Ansible build the AMI
  2. Base stackshared ALB, listeners, logging bucket, IAM
  3. Onboard clientone make command with a subdomain
  4. TemplateAnsible role copies the client Terraform into its own directory
  5. Client infra gatetarget group, host rule, ASG attachment, file system, database, DNS
  6. Runtime configuser data injects the database endpoint
  7. Scalenodes share content on the file system
  8. Offboarddestroy and remove the directory
Per clientTarget groupHost-header ruleASG + launch templateEFSRDS MariaDBDNS recordShared baseVPCALB + HTTPS listenerLog bucketSecurity groupsIAMImagePacker buildAnsible provisionerWordPress runtimeToolingMakefileAnsible roleRemote state
Fixed and repeating infrastructure. The base stack is applied once; the client module is applied once per tenant with its own state.
OperatorMakeAnsibleTerraformAWSdeploy_new_client subdomain=acmerun play with subdomainrender client-terraform/acme and initcreate DB, EFS, target group, rule, ASG, DNSoutputs: endpoint, target groupsite live at acme.example.com
Onboarding one client. One command creates a directory and an isolated stack.

// Before you start

  • An AWS account, a VPC with public and private subnets (or let the base stack create one), and a Route 53 hosted zone for your domain.
  • An ACM certificate for the wildcard of your client domain in the load balancer region.
  • Packer 1.9+, Terraform 1.5+, Ansible 2.14+ and GNU make on the machine that runs onboarding.
  • Credentials supplied through the standard AWS environment or an assumed role; never in the Makefile.
  • A remote state backend (S3 plus a lock table) that supports per-client keys.

// Step-by-step implementation

  1. 01 A Makefile that is the only interface

    The point of the Makefile is that operators never run Packer, Terraform or Ansible directly. It also forces every command through the same environment. Credentials are read from the environment (or an assumed role), never written into the file. The original version of this kind of file tends to accumulate keys; keep it clean from the first commit.

  2. 02 Bake the image with Packer and an Ansible provisioner

    Use the HCL2 format. The source filter finds the newest official Ubuntu LTS image from the vendor account, so you inherit security patches every time you rebuild. The Ansible provisioner installs Docker, the EFS mount helper prerequisites and writes the compose file that runs WordPress.

    Keep the image generic. No client names, no database endpoints and no secrets; those arrive at boot.

  3. 03 Base stack: shared ALB, HTTPS listener and log bucket

    The base stack changes rarely. The listener answers 404 for any host that has no rule, which is the safe default for a multi-tenant front door. Access logs go to a bucket so you can attribute traffic per client by host header later.

  4. 04 Client module part 1: data layer and shared files

    Each client gets a MariaDB instance in private subnets and an EFS file system with mount targets in each subnet. The database password is generated by Terraform and written to Secrets Manager; it is never typed by a human and never appears in the Makefile or Ansible.

    EFS gives every node in the client Auto Scaling group the same uploads directory. Encrypt it at rest and restrict the mount targets to the client security group.

  5. 05 Client module part 2: target group, host rule and Auto Scaling group

    The target group health-checks the site root and uses a load-balancer cookie for stickiness. The listener rule matches the client hostname and forwards to that group. Every rule needs a unique priority; derive it from a hash of the client name or pass it as a variable, or the second client fails to create.

    The launch template carries user data that mounts EFS and writes the database endpoint to the env file before starting the container. The instance role needs permission to read the client secret.

  6. 06 The Ansible role that renders a client directory

    The role is intentionally dumb. It validates the subdomain, creates the directory, renders a backend config so the state key is unique to the client, writes a small variables file and runs Terraform apply in place. All logic stays in Terraform.

    Validating the subdomain matters because it becomes part of resource names, a DNS label and a state key. Reject anything that is not lowercase alphanumeric with hyphens.

  7. 07 Onboard, scale and offboard a client

    With the base applied and an image built, onboarding is one command. To scale a single client, change its ASG variables in its directory and apply; nothing else is touched. Offboarding destroys that directory state and removes it, keeping a final database snapshot.

// How to verify it works

  • curl -sI https://acme.example.com returns 200 or a WordPress redirect; curl -sI https://unknown.example.com returns the fixed 404 from the listener.
  • aws elbv2 describe-target-health for the client target group shows all instances healthy within the grace period.
  • Upload an image in the client admin, then check it exists on the second instance under the content directory, proving EFS is shared.
  • Terraform state for acme exists under its own key and terraform plan in another client directory shows no changes.
  • After make delete_client, the DNS record, rule, ASG and file system are gone and a final snapshot exists.

// Design decisions and trade-offs

  • Fixed and repeating infrastructure are split.
  • Separate Terraform state per client limits blast radius.
  • A shared ALB with host-based routing reduces cost.

// Pitfalls and lessons learned

  • Listener rule priorities must be unique across the listener. The second client fails with an obscure error unless priority is generated or passed in.
  • Target group names are limited to 32 characters. Truncate or hash the client name so long subdomains do not break the plan.
  • Credentials baked into a Makefile are a classic leak. Read them from the environment or use a role, and rotate anything that was ever committed.
  • An Auto Scaling group with ELB health checks and a short grace period kills instances while WordPress is still starting. Give it at least a few minutes.
  • Database creation can outlast a naive CI timeout. Run onboarding where a long apply is acceptable, and keep state locking on.
  • Deleting a client that has no final snapshot is irreversible. Make the snapshot mandatory in the module.

// Frequently asked questions

How do I host many WordPress sites on AWS with isolation per client?

Use a shared Application Load Balancer with host-header routing, and give each client its own Auto Scaling group, EFS file system and database, created from a Terraform module with its own state.

Why separate Terraform state per client?

It limits the blast radius. A plan or apply for one client cannot change another, and a failed onboarding leaves nothing half-built in a shared state.

Why bake an AMI instead of configuring at boot?

Baked images start fast and are identical on every node. Only values that differ per client, such as the database endpoint, are injected through user data.

Should I use ECS instead of Auto Scaling groups?

ECS or EKS is a fine choice for new builds. The VM approach here suited an existing hardened image and a team more comfortable with instances.

How is the database password handled?

Terraform generates it with a random password resource and writes it to Secrets Manager. Instances read it by name; nobody types it.

// The outcome

Client onboarding reduced to a single command.

// Where to take it next

  • Add a Lambda or pipeline that rebuilds the AMI on a schedule and rolls clients to the new image one at a time.
  • Attach WAF to the shared listener and add per-client rate rules keyed on the host header.
  • Move static media to S3 and CloudFront so EFS only holds plugins and themes.
  • Apply the same fixed versus repeating split to a data platform, as in Five-Minute Customer Onboarding: Forms, Workspaces and a Subnet Allocator.

// Keep reading