Search code examples
terraform

Terraform converting to list: "A reference to a resource type must be followed by at least one attribute access, specifying the resource name"


I have an attribute "my_code" in my terraform code. For this currently, users provide the input like this

my_code = "15"

but we want to change it from a number to a list so that users can provide either the number which they are doing right now (so that it remains backward compatible) like above or they can provide a list of numbers like below

my_code = ["15", "20"]

Currently my terraform code looks like below

my_code = lookup(all_operations, "my_code", null)

I was thinking of doing something like below so that it takes both values. If it's a number it will convert it to a list and if it's already a list it will keep it as it is.

my_code = can(list, lookup(all_operations, "my_code", null)) ? [lookup(all_operations, "my_code", null)] : lookup(all_operations, "my_code", null)

But with this error I am getting below error

my_code = can(list, lookup(all_operations, "my_code", null)) ? [lookup(all_operations, "my_code", null)] : lookup(all_operations, "my_code", null)
│ 
│ A reference to a resource type must be followed by at least one attribute
│ access, specifying the resource name

Tried like below

my_code = type(lookup(all_operations, "my_code", null)) == list(any) ? lookup(all_operations, "my_code", null) : [lookup(all_operations, "my_code", null)]

got the same error

my_code = type(lookup(all_operations, "my_code", null)) == list(any) ? lookup(all_operations, "my_code", null) : [lookup(all_operations, "my_code", null)]
│ 
│ A reference to a resource type must be followed by at least one attribute
│ access, specifying the resource name

Any help would be greatly appreciated. Thanks in advance


Solution

  • You can use flatten to generate an array of elements for both cases:

    • my_code contains a single value such as "15"
    • my_code contains an array such as ["15", "20"]

    Example:

    variable "my_code" {
    }
    
    locals {
      # square brackets [] are required in order to convert var.my_code to an array
      #
      # If var.my_code is already an array that's ok, as flatten(...) will return 
      # a flattened sequence of elements for single or multi-dimensional arrays
      my_codes = flatten([var.my_code])
    }
    
    output "my_codes" {
      value = local.my_codes
    }
    

    Running terraform plan with single string value (mycode = "15"):

    Changes to Outputs:
      + my_codes = [
          + "15",
        ]
    

    Running terraform plan with an array of strings (mycode = ["15", "20"]):

    Changes to Outputs:
      + my_codes = [
          + "15",
          + "20",
        ]