Martin Schulze
Martin Schulze

Reputation: 2171

How to assign default values to map(object()) input in Terraform?

When defining a complex input variable:

variable "s3_shares" {
  type = map(object({
    s3_bucket_arn         = string
    client_list           = list(string)
    read_only             = bool
    default_storage_class = string
  }))
}

How can one deal with read_only and default_storage_class being mutually exclusive? In other words, when using the module and defining an s3_share with read_only = true the default_storage_class could be omitted.

Upvotes: 1

Views: 4249

Answers (1)

Will
Will

Reputation: 2410

Using validation{} block and alltrue() function :

variable "s3_shares" {
  type = map(object({
    s3_bucket_arn         = string
    client_list           = list(string)
    read_only             = bool
    default_storage_class = string
  }))
default = {
  "one" = {
    s3_bucket_arn         = "foo"
    client_list           = ["foo","bar"]
    read_only             = false
    default_storage_class = "bar" # IS OK
}
  "two" = {
    s3_bucket_arn         = "foo"
    client_list           = ["foo","bar"]
    read_only             = false
    default_storage_class = "" # IS OK
}}
  "three" = {
    s3_bucket_arn         = "foo"
    client_list           = ["foo","bar"]
    read_only             = true
    default_storage_class = "" # IS OK
}}
  "four" = {
    s3_bucket_arn         = "foo"
    client_list           = ["foo","bar"]
    read_only             = true
    default_storage_class = "bar" # IS KO
}}

validation {
  condition = alltrue([
     for o in var.s3_shares : !(o.read_only && length(o.default_storage_class) > 0)])
     error_message = "Read_only and default_storage_class are exclusive."     
   }
}

Mind the use case "two" where read_only is set to false and default_storage_class is empty : this will return true. This might not be the behavior you are looking for.

Upvotes: 2

Related Questions