random access memories

Using Terraform to create multiple copies of instances in multiple regions

I needed to be able create multiple copies of a instance in multiple regions.

For example if I needed to create two copies of this instance in three different regions. This would mean a total of six different instances.


local {
	  regions        = ["us-west", "us-east", "eu-central"]
	  count_per      = 2
	  ssh_public_key = chomp(file(pathexpand("~/.ssh/id_rsa.pub")))

resource "linode_instance" "edge" {
	  label           = "edge-${element(local.regions,floor(count.index / local.count_per))}-${format("%02g", (count.index % local.count_per) + 1)}"
	  region          = element(local.regions, floor(count.index / local.count_per))
	  count           = local.count * length(local.regions)
	  type            = "g6-nanode-1"
	  image           = "linode/ubuntu20.04"
	  root_pass       = random_password.root_password.result
	  authorized_keys = [local.ssh_public_key]

Interesting Bits

count generates to total number of instances to be created.

region chooses which region to create the instance in by dividing how many instances have been created into the total number of instances per region using the count_per local variable. The function floor is used to ensure that whole numbers are given to the element function.

label names the instances as edge-us-west-01, edge-us-west-02, etc.