gpt4 book ai didi

terraform - 是否可以使用 terraform 为变量添加别名?

转载 作者:行者123 更新时间:2023-12-02 23:54:08 26 4
gpt4 key购买 nike

要获取当前的 AWS id,我需要执行以下操作:

data "aws_caller_identity" "current" { }

这使得它可以在 data.aws_caller_identity.current.account_id 中使用。有什么方法可以让它仅作为 account_id 使用吗?我尝试过:

variable "account_id" {
default = "${data.aws_caller_identity.current.account_id}"
}

但它说我无法在变量中进行字符串插值。

最佳答案

0.10.3 ,您可以使用locals解决缺少变量插值的问题。

这允许您为可能需要插值的各种事物定义一个“友好”名称。

在您的情况下,您只需使用:

locals {
account_id = "${data.aws_caller_identity.current.account_id}"
}

但是您可以组合任意数量的插值和函数:

variable "foo" {}
variable "bar" {}

locals {
account_id = "${data.aws_caller_identity.current.account_id}"
foo_BAR = "${var.foo}_${upper(var.bar)}"
}
<小时/>

旧答案

正如 Terraform 在错误中指出的那样,尽管有 known hacky workarounds 但不能直接进行变量插值。当您需要某种形式的变量插值时。

不幸的是,所有这些都涉及模块、模板或 null_resourcenull_data_source 的稍微复杂的使用,这仍然会让您以一种尴尬的方式访问变量。

一个可能更适合您的选择是将一堆数据源包装到一个模块中,如下所示:

data "aws_caller_identity" "current" {}
output "account_id" { value = "data.aws_caller_identity.current.account_id" }

data "aws_availability_zones" "zones" {}
output "zones" { value = "data.aws_availability_zones.zones.names }

然后像这样访问这些:

module "data_sources" {
source = "path/to/data-sources-module.tf"
}

...
account_id = "${module.data_sources.account_id}"
...
availability_zone = "${module.data_sources.zones[0]}"

但不幸的是,这并没有真正使这些值像中间变量一样容易暴露。

关于terraform - 是否可以使用 terraform 为变量添加别名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39687615/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com