0
votes

myvar should be a list of security groups.

variable "myvar" {
  default     = null
}

If users specify it that list is concatenated with the default security group (pulled in from the data source).

If it's not specified just use the default security group.

This is not working:

local {
    test = var.myvar != null ? concat(tolist(data.aws_security_group.data.id), var.myvar) : tolist(data.aws_security_group.data.id)
}

But this does work:

  aaa = var.myvar != null ? concat(["aaaa"], ["bbbbb","ccccccc"]) : ["aaaa"]

So how to I convert a string to a scalar array/list? It seems like that's what Terraform needs and tolist() is not working.

3

3 Answers

1
votes

Based on the given requirements, I think the most straightforward solution would be to set the default for the variable to [] and avoid the need for conditionals at all:

variable "additional_security_group_ids" {
  type    = list(string)
  default = []
}

locals {
  security_group_ids = concat(
    [data.aws_security_group.default.id],
    var.additional_security_group_ids,
  )
}

Concatenating an empty list just produces the same list, so leaving the variable unset in the above would cause local.security_group_ids to contain only the default security group id.

Setting the default to null is useful when the absence of a value for that variable disables some feature entirely, or if the logic you need can't be conveniently expressed via defaults, but I'd always recommend using specific default values where possible because the result will tend to be easier to read and understand for future maintainers.

1
votes

Is this what you're looking for?

value = var.myvar != null ? concat([data.aws_security_group.data.id], var.myvar) : [data.aws_security_group.data.id]
0
votes

Proposing this as answer, but hoping there is a less crazy way

local {
    test = var.myvar != null ? flatten(concat(tolist([data.aws_security_group.data.id]), [var.myvar])) : tolist([data.aws_security_group.data.id])
}