Flatten
Sometimes we have to work with very complex data structures, but module only requires a simple list of objects or a map. Falltern functions helps us with converting complex data structures into lists.
Let's start by creating a a file with the name ssm-parameters\variables.tf
,
variable "parameters" {
type = list(object({
prefix = string
parameters = list(object({
name = string
value = string
}))
}))
default = []
}
In here, I define a variable with name 'parameter', and I also provide the data types of the object. Set it's default value to an empty list.
Next let's create a file with the name ssm-parameters\ssm-parameter.tf
,
locals {
parameters = flatten([
for parameters in var.parameters: [
for keyvalues in parameters.parameters:
{
"name" = "${parameters.prefix}/${keyvalues.name}"
"value" = keyvalues.value
}
]
])
}
resource "aws_ssm_parameter" "parameter" {
for_each = { for keyvalue in local.parameters: keyvalue.name => keyvalue.value }
name = each.key
type = "String"
value = each.value
}
In here, the local defines how the flatten should be used on the passed parameters.
Next let's create a file with the name provider.tf
,
provider "aws" {
region = "eu-west-1"
}
Finally a file with the name parameters.tf
,
locals {
my_parameters = [
{
"prefix" = "/myprefix"
"parameters" = [
{
"name" = "myparameter"
"value" = "myvalue"
},
{
"name" = "environment"
"value" = "dev"
}
]
},
{
"prefix" = "/myapp"
"parameters" = [
{
"name" = "environment"
"value" = "prod"
}
]
}
]
}
module "parameters" {
source = "./ssm-parameter"
parameters = local.my_parameters
}
In here the complex data structure is defined as a local variable and this will be transformed by the flatten function defined in the local of the module.
Last updated
Was this helpful?