We have a script which adds values into google secret manager, some of these values might be strings others are more complex structures which we would represent in json.
Within terraform is there a way to check if a value is a string or a map so I can conditionally encode to json if needed. If there is not what method of accomplishing this have people used?
data = {
value1 = "abcdefg"
value2 = {
user = "abc"
another_value = "defg"
}
}
resource "google_secret_manager_version" "..." {
...
for_each = var.data
secret_value = if <each.value> == string ? each.value : jsonencode(each.value)
}
Hi @matt.envelop,
If you would be willing to accept the other primitive types (number and bool) also being classified as “strings” for the purpose of this rule, you could perhaps try converting to string and use can
to convert its success or failure into a boolean result:
secret_value = can(tostring(each.value)) ? each.value : jsonencode(each.value)
Varying behavior based on types is not a typical thing to do in Terraform because the language has a number of automatic type conversion rules and so behaviors can get confusing if you are too “fussy” about types.
The approach above will treat numbers and booleans as strings because there is an available conversion from both of those types to string (true
becomes "true"
, for example), but that is consistent with what would happen automatically if you had assigned a number or bool value directly to secret_value
here (because that argument itself expects a string, AFAIK), and so it seems like a justified compromise to me. In effect, this is saying “if this value wouldn’t normally be accepted for this argument, then JSON encode it to make it acceptable”.