Modular Approach: Terraform 0.13

Sagar Kharab
2 min readAug 9, 2020

Hashicorp has launched their preview release of Terraform 0.13rc. It has brought one of the most awaiting feature that will complete the missing block of modular approach with Terraform.

Terrafrom is a great tool for cloud infrastructure provisioning. It’s ability to work with various Cloud providers, high level IaaC syntax and simplicity of dependencies set it right in front of the queue as an Enterprise level as well as low level cloud infra provisioning.

The highlights of the new version are:

  1. Module-focused development using depends_on, count and for_each features of the Terraform.
  2. It brings new required providers syntax. This change also goes in sync with improvements and updates to the Terraform Provider Registry. For the beta release, it’s more focused on the ability to find and initialize community providers from the Registry. These are believed to be major improvements to provider ecosystem and provider interaction. To further simplify the installation of community providers, Terrafrom can now differentiate between the official HashiCorp-supported providers and HashiCorp partner-supported providers.
  3. Custom variable validation is now added as production ready feature.
  4. The terraform login command connects a CLI user to the Terraform Cloud app, where they can generate and copy an API token.

Since Terraform has been focusing module structure of Infra provisioning, it’s been very easy to create, maintain and destroy cloud resources.

In order to install terraform 0.13 from here.

Let’s discuss #1 in order to achieve modularization with Terraform.

Module-Driven Code

Let’s take an example below how can we easily use depends_on, count and for_each in module-driven development with terraform.

variable "environment_names" {
type = type("string")
default = ["prod", "sit", "uat", "dev"]
}

module "env_service_alb" {
source = "tf-modules-aws/alb"
count = length(var.environment_names)
vpc_id = var.vpc_id
}

locals {
resources = {
prod = "prod-ecs"
dev = "qa-ecs"
sit = "dev-ecs"
uat = "dev-ecs"
}
}

module "ecs_cluster" {
source = "tf-modules-aws/ecs"
for_each = local.resources
cluster_name = each.value
subnets = local.public_subnets[*].id
vpc_id = var.vpc_id
depends_on = [module.env_service_alb]
}

It’s important to notice here that to access modules resources (i.e. as outputs) created by using count or for_each, we need to use either tuple or map syntax. Examples:

output "alb_uat" {
value = module.env_service_alb[2].target_group_arn
}
output "cluster_prod_id" {
value = module.ecs_cluster["prod"].cluster_id
}

--

--

Sagar Kharab

Software Developer by profession. Chef by chance. Runner by choice. Sums it all.