Using contextual defaults with Terraform

We've seen how to declare and use default values in our Terraform code, such as the Ubuntu AMI for our region or our VM size. An interesting feature in Terraform is the ability to declare and use maps of values, so, depending on a key, the variable can have a different value. We'll see how it applies to the correct AMI of the corresponding AWS.

Getting ready

To step through this recipe, you will need the following:

  • A working Terraform installation
  • An AWS provider and an EC2 instance (using a SSH key pair and a security group), all configured in Terraform (refer to the previous recipes)
  • An Internet connection

How to do it…

Here's how we simply declared the AMI we wanted for the eu-west-1 region in the variables.tf file:

variable "ami" {
  default = "ami-ee6b189d"
}

We accessed it easily like this in the instances.tf file:

ami = "${var.ami}"

A similar, but more explicit way would be to use a map, so we know which region the value refers to:

variable "ami" {
  default = {
    eu-west-1 = "ami-ee6b189d"
  }
}

Here's how we access the same value in a map:

ami = "${var.ami["eu-west-1"]}"

Now let's add more valid AMI IDs for other regions:

variable "ami" {
  default = {
    eu-west-1 = "ami-ee6b189d"
    us-east-1 = "ami-4f680658"
    us-west-1 = "ami-68a9e408"
  }
}

The ami variable can now be valid for either of the three regions if accessed correctly in the instances.tf file:

ami = "${var.ami["us-east-1"]}"

Now is a good time to start managing the AWS region directly in the code, for better portability. Add the following to variables.tf to use eu-west-1 as a default region:

variable "aws_region" {
  default = "eu-west-1"
}

You can now use this variable in the provider.tf file to set the region:

provider "aws" {
  region = "${var.aws_region}"
}

Now the region variable is globally available, let's use it to access our map in instances.tf:

ami = "${var.ami["${var.aws_region}"]}"

We now have an easily geographically deployable infrastructure that anyone in your team can launch close to him or her without the need to change code.

There's more…

We can perform the same dynamic access to a map using the lookup() function in Terraform:

ami = "${lookup(var.ami, var.aws_region)}"
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.219.191.233