如何使Terraform用默认值替换空值? [英] How can I make Terraform replace a null value with a default value?

查看:13
本文介绍了如何使Terraform用默认值替换空值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Terraform文档表明这应该已经发生:

https://www.terraform.io/docs/language/expressions/types.html

NULL:表示缺勤或遗漏的值。如果将资源或模块的参数设置为NULL,则Terraform的行为就像您已将其完全省略一样-如果参数有默认值,它将使用该参数的默认值,如果该参数是必需的,则会引发错误。

我正在调用一个具有以下变量文件的";foo";模块:

variable "bar" {
  type    = string
  default = "HelloWorld"
}

示例1

当我使用此代码调用它时:

module "foo" {
  source = "../modules/foo"
  bar = null
}

结果为错误。";str";参数的值无效:参数不能为空。正在使用条形图时触发。

示例2

当我使用此代码调用它时(省略它,而不是将它设为空):

module "foo" {
  source = "../modules/foo"
  # bar = null
}

结果是它起作用了。";bar";变量默认为";HelloWorld";。

这似乎是其他人也提出但未解决的Terraform中的错误。 https://github.com/hashicorp/terraform/issues/27730

有人知道解决方案或解决办法吗?

版本信息:

Terraform v1.0.5
on linux_amd64
+ provider registry.terraform.io/hashicorp/google v3.51.0
+ provider registry.terraform.io/hashicorp/null v3.1.0
+ provider registry.terraform.io/hashicorp/random v3.1.0
+ provider registry.terraform.io/hashicorp/time v0.7.2

解决办法

基于@Matt Schuchard的评论和一些研究,有一个使用条件检查的难看的解决方案:

variable "foo" {
  type    = string
  default = "HelloWorld"
}
locals {
  foo = var.foo == null ? "HelloWorld" : var.foo
}

为什么

我的用例是尝试避免重复代码。我有2个非常相似的模块,一个是另一个的子集。我使用的解决方案是将模块按顺序依次调用,即祖级、父级和子级。

我希望";祖父母";可以使用变量,但如果省略了这些变量,那么";子代";下面的模块应该使用默认值设置它们,例如";HelloWorld";。但是,要将这些变量一直公开到族谱中,我必须将它们包含在所有模块和高级模块(祖父母和父辈)中,我希望将它们默认为NULL,从而允许它们是可选的,但仍会导致它们在子代中设置为默认值。

.我想我需要一张图表。

推荐答案

从Terraform 1.1.0开始,variable声明现在支持nullable argument。默认为true以保留现有行为。但是,任何nullable=false未指定的或设置为null的变量将改为分配默认值。

main.tf

variable "nullable" {
  type    = string
  default = "Used default value"
}

output "nullable" {
  value = coalesce(var.nullable, "[null]")
}

variable "non_nullable" {
  type     = string
  default  = "Used default value"
  nullable = false
}

output "non_nullable" {
  value = coalesce(var.non_nullable, "[null]")
}

terraform.tfvars

nullable     = null
non_nullable = null

请注意输出块中coalesce的用法。TerraForm省略所有设置为null的输出,因此这可确保任何null值仍在输出中显示某些内容。

应用此配置后,通过运行terraform output我们可以看到,当nullable=true(默认值)变量保留显式设置的null值,而使用nullable=false时,将忽略任何null值,而支持default

# terraform output
non_nullable = "Used default value"
nullable = "[null]"

这篇关于如何使Terraform用默认值替换空值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆