来自本地的 terraform 变量默认值插值 [英] terraform variable default value interpolation from locals

查看:24
本文介绍了来自本地的 terraform 变量默认值插值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用例,我需要两个 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
}

variables foo_cloud_secret_keyfoo_cloud_access_key 会像这样传递给子模块:

where variables 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
}

然后在其余的 terraform 文件中只使用 local.something 而不是 var.something.

And then only only use local.something instead of var.something in the rest of the terraform files.

这篇关于来自本地的 terraform 变量默认值插值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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