定义部分默认值

huangapple go评论45阅读模式
英文:

Defining Partial Default Values

问题

I am defining a variable in Terraform as:

定义一个Terraform变量如下:

variable 'var_a' {
   type = object({
      name = string
      enabled = bool
   })
   default = {
      name = "the_name"
      enabled = true
   }
}

If no value is passed to generate this variable, it would be populated with the values of "the_name" and true. However, I want to be able to still execute this code if only certain values of the variable object are provided.

如果没有传递任何值来生成此变量,它将使用“the_name”和true的值进行填充。但是,如果只提供了变量对象的某些值,我仍希望能够执行此代码。

For example, if I pass this as a variable:

例如,如果我将以下内容作为变量传递:

var_a = {
   name = "another_name"
}

I would still like the enabled attribute to be set to true, based on the default value. When I try to use this code, it fails as it is expecting me to declare the enabled attribute.

我仍然希望根据默认值将enabled属性设置为true。当我尝试使用此代码时,它失败了,因为它期望我声明enabled属性。

英文:

I am defining a variable in Terraform as:

variable 'var_a' {
   type = object({
      name = string
      enabled = bool
   })
   default = {
      name = "the_name"
      enabled = true
   }
}

If no value is passed to generate this variable, it would be populated with the values of "the_name" and true. However, I want to be able to still execute this code if only certain values of the variable object are provided.

For example, if I pass this as a variable:

var_a = {
   name = "another_name"
}

I would still like the enabled attribute to be set to true, based on the default value. When I try to use this code, it fails as it is expecting me to declare the enabled attribute.

答案1

得分: 1

使用可选关键字(可选对象类型属性)可以解决我的情况。

这允许您指定变量对象属性是否可选,并为该可选属性提供默认值。

关于上面的示例,使用可选关键字如下:

变量定义:

variable "var_a" {
   type = object({
      name = string
      enabled = optional(bool, true)
   })
}

用法:

var_a = {
   name = "another_name"
}

变量值:

{name = "another_name", enabled = true}

这将产生变量的预期结果,将提供的默认值填充到可选值中。

英文:

After some additional research, the answer for my case is to use the optional keyword (Optional Object Type Attributes).

This allows one to specify whether the variable object attribute is optional, and provide a default value for that optional attribute.

Using optional with regard to the example above would look like:

Variable Definition:

variable "var_a" {
   type = object({
      name = string
      enabled = optional(bool, true)
   })
}

Usage:

var_a = {
   name = "another_name"
}

Variable Value:

{name = "another_name", enabled = true}

This yields the intended result for the variable, populating optional values with provided defaults.

huangapple
  • 本文由 发表于 2023年6月12日 19:04:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/76456033.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定