gpt4 book ai didi

terraform - 如果映射变量不是空对象,则模块调用中的可选参数

转载 作者:行者123 更新时间:2023-12-02 03:33:34 27 4
gpt4 key购买 nike

我有以下模块来创建私有(private)存储桶。当我在模块调用中定义非空 logging 参数时,我只想使用日志记录:

variable "tags" {
description = "A mapping of tags to assign to the bucket."
type = "map"
default = {}
}

variable "logging" {
description = "A mapping of logging to assign to the bucket."
type = "map"
default = {}
}

resource "aws_s3_bucket" "private_bucket" {
bucket = "${var.bucket}"
acl = "private"
policy = "${data.aws_iam_policy_document.policy.json}"
tags = "${var.tags}"
# logging = "${var.logging}"
logging = "${length(keys(var.logging)) > 0 ? var.logging : null}"

# ...

# This block is replaced by the argument
/* logging {
target_bucket = "${var.logging_bucket}"
target_prefix = "s3/${local.bucket_id}/"
} */

# ...
}

但是这不起作用。我这样调用模块:

module "private_bucket" {
source = "modules/private-bucket"
bucket = "${local.private_bucket_name}"

tags {
Name = "Serverless stack private bucket"
Environment = "${local.stage}"
}
}

为什么顶级 if-else 没有在 Terraform 中实现?是否有其他方法可以使用条件来初始化模块/资源中的变量,而不仅仅是它的值?

编辑:

这是一个伪代码,我想要实现的目标:

resource "aws_s3_bucket" "private_bucket" {
bucket = "${var.bucket}"
acl = "private"
policy = "${data.aws_iam_policy_document.policy.json}"
tags = "${var.tags}"

# if var.logging is not an empty object,
# then initialize logging with the object
if (var.logging != {}) {
logging = "${var.logging}"
}

# ...
}

最佳答案

您不能在 then 或 else 部分中使用映射。我认为 Terraform 0.12 可能更灵活。

我在 Azure 上做了同样的事情,最终使用了 locals{} 部分中的合并函数,var.tags 默认为 {}:

tags    = "${merge(data.azurerm_resource_group.env.tags, var.tags)}"

然后我对资源 block 使用 ${local.tags}

关于terraform - 如果映射变量不是空对象,则模块调用中的可选参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51100245/

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