1

I want to take a map such as this that is passed in as a variable

cidrs = {
  A = [1.1.1.1]
  B = [2.2.2.2, 3.3.3.3]
  Group1 = {
    C = [4.4.4.4]
    D = [5.5.5.5]
  }
}

and then within the locals section i want to sanitize it to the following

cidrs_sanitized = {
  A = [1.1.1.1]
  B = [2.2.2.2, 3.3.3.3]
  Group1 = [4.4.4.4, 5.5.5.5]
  C = [4.4.4.4]
  D = [5.5.5.5]
}

I have tried various methods of looping

everything i've tried so far has led to me trying to get each set of values as seperate variables and then merge them together example:

single = { A = [1.1.1.1], B = [2.2.2.2, 3.3.3.3] }
groups = { Group1 = [4.4.4.4, 5.5.5.5] }
grouped = { C = [4.4.4.4], D = [5.5.5.5] }
cidrs_sanitized = merge(single, groups, grouped)

and here's some of the stuff i've tried but failed to succeed with

groups = flatten([ for range, value in var.cidrs: tomap({ range = values(value) }) if !can(element(value, 0)) ])
single = flatten([ for range, value in var.cidrs: tomap({ range = value }) if can(element(value, 0)) ])

and

groups = {
  for range, value in var.ranges :
    range => can(values(value)) ? values(value) : null
}
grouped = flatten([for range in var.ranges : [
  for cidr_key, cidr in range : {
    cidr_key => cidr
  } if length(cidr) > 0
] if can(values(range)) ])

The merge always fails as it tells me the output are tuples and i can't figure out how to get terraform to show me the values of the locals grouped, groups and single when calling it as a module

Any help or points in the right direction would be appreciated, thanks.

1

Following the documentation a map is a collection of key/values with a constraint:

"...accepts any element type as long as every element is the same type" source

So the input map you have declared, is already an invalid map for Terraform 0.12 (at least)

Below the example of the error produced:

variable "cidrs" {
  description = ""
  type        = map
  default = [
    ["1.1.1.1"],
    ["2.2.2.2", "3.3.3.3"],
    {
      C = ["4.4.4.4"]
      D = ["5.5.5.5"]
    }]
}

When validating an error is raised:

$> terraform validate

Error: Invalid default value for variable

  on vars.tf line 65, in variable "cidrs":
  65:   default = [
  66:     ["1.1.1.1"],
  67:     ["2.2.2.2", "3.3.3.3"],
  68:     {
  69:       C = ["4.4.4.4"]
  70:       D = ["5.5.5.5"]
  71:     }]

This default value is not compatible with the variable's type constraint: map
of any single type required.

Been that said, if we can generalize A and B as "values which are lists" and Group1 as "values which are maps" and the input is a fixed type ordered we can use a tuple or an object, this can be solve in a more readable (and maintainable) way. If so, let us know so we can extend this answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.