Modular Approach: Terraform 0.13
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:
- Module-focused development using
depends_on,
count
andfor_each
features of the Terraform. - 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. - Custom variable validation is now added as production ready feature.
- 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[*].idvpc_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
}