Creating a Modulo Distribution of EC2 Instances with EL2

Just use   -var 'az=0'. That's it.

The EL2 modulo distribution feature enables you to use just a single launch invocation to spread out instances across Availability Zones(AZs) with the round robin like property of modulo arithmetic; resulting in an as even as possible instance distribution and making it far simpler to use the most fundamental resiliency feature of the AWS offering.

If there are 3 AZs in a given AWS Region and your launch invocation requests 6 instances, specifying   -var 'az=0' will result in 2 instances in each AZ (assuming the launch is successful). Similarly a request of 9 instances, would result in 3 instances in each AZ. A request of 5 instances would result in an instance distribution of 2, 2 and 1 across each of AZs 'a', 'b' and 'c', respectively. To target just AZ 'a' for all instances, specify  -var 'az=1', or for AZ 'b' use a value of 2, and so on.

Here's how a full command line looks for a modulo distribution of instances in Europe (London):


terraform apply -var 'region=eu-west-2' -var 'access_key=...' -var 'secret_key=...' -var 'instance_type=t4g.nano' -var 'instances=3' -var 'az=0' -var 'linux_distro=debian9stretch' -auto-approve

As the launch request output in the left split pane shows, this single command line invocation has resulted in each of the 3 instances being placed in a different Availability Zone and subnet. The right split pane shows all associated resources being taken down afterwards.

Stateful Availability Zone selection is also possible with the  az_all_states  parameter, which is described in detail in vars.tf.