Using Terraform Maps
In my example, I am using the Paris region (eu-west-3) but what if I need to add new regions like Dublin (eu-west1) for instance !?
The above code will deploy an EC2 instance to a single region.
In order to seolve this problem, the first step to follow here, is finding the AMI we want to use (depending on the region) and then create a variable with the type “map”:
variable "my_ami" {
type = "map"
default = {
eu-west-1 = "ami-f90a4880"
eu-west-3 = "ami-0e55e373"
}
description = "I added only 2 regions: Paris and Dublin. You can use as many regions as you want."
}
According to the used region Terraform should create an EC2 machine with a different AMI.
This is done by changing the old AMI line by changing ami = "ami-0e55e373"
to ami = "${lookup(var.my_ami, var.region)}"
.
To test this, type terraform plan
and you will get this output:
+ aws_instance.web
id: <computed>
ami: "ami-0e55e373"
associate_public_ip_address: <computed>
availability_zone: <computed>
ebs_block_device.#: <computed>
ephemeral_block_device.#: <computed>
get_password_data: "false"
instance_state: <computed>
instance_type: "t1.micro"
ipv6_address_count: <computed>
ipv6_addresses.#: <computed>
key_name: <computed>
network_interface.#: <computed>
network_interface_id: <computed>
password_data: <computed>
placement_group: <computed>
primary_network_interface_id: <computed>
private_dns: <computed>
private_ip: <computed>
public_dns: <computed>
public_ip: <computed>
root_block_device.#: <computed>
security_groups.#: <computed>
source_dest_check: "true"
subnet_id: <computed>
tags.%: "1"
tags.Name: "eralabs"
tenancy: <computed>
volume_tags.%: <computed>
vpc_security_group_ids.#: <computed>
If you manually change the region to eu-west-1
, you will notice that terraform plan
will use the other AMI:
+ aws_instance.web
id: <computed>
ami: "ami-f90a4880"
associate_public_ip_address: <computed>
availability_zone: <computed>
ebs_block_device.#: <computed>
ephemeral_block_device.#: <computed>
get_password_data: "false"
instance_state: <computed>
instance_type: "t1.micro"
ipv6_address_count: <computed>
ipv6_addresses.#: <computed>
key_name: <computed>
network_interface.#: <computed>
network_interface_id: <computed>
password_data: <computed>
placement_group: <computed>
primary_network_interface_id: <computed>
private_dns: <computed>
private_ip: <computed>
public_dns: <computed>
public_ip: <computed>
root_block_device.#: <computed>
security_groups.#: <computed>
source_dest_check: "true"
subnet_id: <computed>
tags.%: "1"
tags.Name: "eralabs"
tenancy: <computed>
volume_tags.%: <computed>
vpc_security_group_ids.#: <computed>