0
0
Terraformcloud~30 mins

Collection functions (length, flatten, merge) in Terraform - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Collection Functions in Terraform
📖 Scenario: You are managing infrastructure configurations using Terraform. You need to organize and analyze lists and maps of server names and their attributes.
🎯 Goal: Build a Terraform configuration that uses collection functions length, flatten, and merge to work with lists and maps.
📋 What You'll Learn
Create a variable with a nested list of server names
Create a variable with two maps of server attributes
Use length to find the number of servers in the flattened list
Use flatten to convert the nested list into a single list
Use merge to combine the two maps into one
💡 Why This Matters
🌍 Real World
Managing infrastructure often requires organizing lists of servers and their properties. Terraform collection functions help simplify this management.
💼 Career
Understanding how to manipulate collections in Terraform is essential for infrastructure as code roles, enabling efficient and scalable configuration management.
Progress0 / 4 steps
1
Create a nested list of server names
Create a variable called server_names with the nested list value [["web1", "web2"], ["db1", "db2"]].
Terraform
Need a hint?

Use variable "server_names" { default = ... } to define the nested list.

2
Create two maps of server attributes
Create two variables called server_attrs1 and server_attrs2 with these exact maps: { web1 = "active", db1 = "active" } and { web2 = "inactive", db2 = "active" } respectively.
Terraform
Need a hint?

Define each variable with variable "name" { default = { ... } } syntax.

3
Use length and flatten functions
Create a local variable called flat_servers that uses flatten(var.server_names). Then create another local variable called server_count that uses length(local.flat_servers).
Terraform
Need a hint?

Use locals { flat_servers = flatten(var.server_names) } and then server_count = length(local.flat_servers).

4
Merge the two server attribute maps
Add a local variable called all_server_attrs that merges var.server_attrs1 and var.server_attrs2 using the merge function.
Terraform
Need a hint?

Use all_server_attrs = merge(var.server_attrs1, var.server_attrs2) inside the locals block.