来自当地人的 terraform 变量默认值插值 [英] terraform variable default value interpolation from locals
问题描述
我有一个用例,我需要两个 AWS 提供商来提供不同的资源.默认 aws
提供程序在主模块中配置,该模块使用另一个定义附加 aws
提供程序的模块.
I have a use case where I need two AWS providers for different resources. The default aws
provider is configured in the main module which uses another module that defines the additional aws
provider.
默认情况下,除非明确覆盖,否则我希望两个提供商使用相同的 AWS 凭证.
By default, I'd like both providers to use the same AWS credentials unless explicitly overridden.
我想我可以做这样的事情.在主模块中:
I figured I could do something like this. In the main module:
locals {
foo_cloud_access_key = aws.access_key
foo_cloud_secret_key = aws.secret_key
}
variable "foo_cloud_access_key" {
type = string
default = local.foo_cloud_access_key
}
variable "foo_cloud_secret_key" {
type = string
default = local.foo_cloud_secret_key
}
where variable
s foo_cloud_secret_key
和 foo_cloud_access_key
然后会像这样传递给子模块:
where variable
s foo_cloud_secret_key
and foo_cloud_access_key
would then be passed down to the child module like this:
module foobar {
...
foobar_access_key = var.foo_cloud_access_key
foobar_secret_key = var.foo_cloud_secret_key
...
}
module foobar
然后配置它的附加是提供这些变量:
Where module foobar
would then configure its additional was provide with these variables:
provider "aws" {
alias = "foobar_aws"
access_key = var.foobar_access_key
secret_key = var.foobar_secret_key
}
当我运行 init terraform
时会吐出这个错误(对于两个变量):
When I run the init terraform
spits out this error (for both variables):
Error: Variables not allowed
on variables.tf line 66, in variable "foo_cloud_access_key":
66: default = local.foo_cloud_access_key
Variables may not be used here.
是否有可能在 terraform
中实现类似的功能,或者还有其他方法可以实现吗?
Is it possible to achieve something like this in terraform
or is there any other way to go about this?
推荐答案
拥有复杂的、计算的变量默认值是可能的,但只有一种解决方法:
Having complex, computed default values of variables is possible, but only with a workaround:
- 为变量定义一个虚拟的默认值,例如
null
- 定义一个局部变量,它的值要么是变量的值,要么是实际的默认值
variable "something" {
default = null
}
locals {
some_computation = ... # based on whatever data you want
something = var.something == null ? local.some_computation : var.something
}
然后只使用 local.something
而不是 var.something
在其余的 terraform 文件中.
And then only only use local.something
instead of var.something
in the rest of the terraform files.
这篇关于来自当地人的 terraform 变量默认值插值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!