英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论