本文介绍了如何使用 Consul 中定义的默认值在 Terraform 中定义可选变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Terraform 脚本,其中包含从 Consul 填充的一些变量.我想在两种不同的场景中使用这个脚本:

I have a Terraform script with some variables populated from Consul. I want to use this script in two different scenarios:

  • 场景 1. 使用 Consul 的默认值一切正常.
  • 场景 2.我需要覆盖一些变量.

我检查了 Terraform 文档并注意到我不能将 Consul 中定义的变量用作其他变量的默认值.所以我最终得到了以下解决方法:

I've checked Terraform documentation and noticed that I can't use a variable defined in Consul as a default value for some another variable. So I ended up with following workaround:

## vars.tf
## emulating undefined value using "null" string
variable "my_optional_variable" { default = "null" }

## main.tf
my_optional_variable = "${var.my_optional_variable == "null" ? data.consul_keys.my_optional_variable : var.my_optional_variable}"

有人可以告诉我一个更好的方法吗?如何避免使用null"字符串进行破解?

Can somebody show me a better way to do it? How to avoid a hack with a "null" string?

谢谢

推荐答案

另一个选项是 coalesce 它适用于空字符串,因此比您的 "null" 字符串稍好.

Another option is coalesce which works with empty strings so is slightly better than your "null" string.

给定您的场景或具有两个变量/数据源的类似案例

Given your scenario or a similar case with two variables/data sources

variable "my_default_value" {
  default = "CentOS 7"
}
variable "my_optional_variable" {
  default = ""
}

您可以从给定的参数中取第一个非空值.必须提供至少两个参数."

You can take the "first non-empty value from the given arguments. At least two arguments must be provided."

data "openstack_images_image_v2" "bastion_image" {
  name = "${coalesce(var.my_optional_variable, var.my_default_value)}"
}

这篇关于如何使用 Consul 中定义的默认值在 Terraform 中定义可选变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 20:38