You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Terraform 1.1.4中如何结合条件判断使用heredoc输出内容

解决Terraform 1.1.4中带条件判断的Heredoc输出问题

你遇到的核心问题是Terraform的条件表达式语法不支持直接在三元运算符中嵌入跨多行的Heredoc结构,导致你尝试的写法无法被正确解析。下面提供两种可行的解决办法:

方法一:将Heredoc内容定义为局部变量

先把需要输出的多行内容单独定义在locals块中,再在输出的条件表达式里引用这个变量,既保留Heredoc的可读性,又符合Terraform语法规范:

locals {
  file_output_content = <<EOF
---
creation_rules:
  - kms: ${aws_kms_replica_key.this[0].arn}
EOF
}

output "my_created_file" {
  description = "Output of the newly created file with a KMS arn in it."
  value       = var.enable_file_creation ? local.file_output_content : "[INFO] This file was skipped."
}

方法二:用join函数构造多行文本

如果不想额外定义局部变量,可以用join配合换行符拼接多行字符串,同样能实现条件输出的需求:

output "my_created_file" {
  description = "Output of the newly created file with a KMS arn in it."
  value       = var.enable_file_creation ? join("\n", [
    "---",
    "creation_rules:",
    "  - kms: ${aws_kms_replica_key.this[0].arn}"
  ]) : "[INFO] This file was skipped."
}

两种方法都能在Terraform 1.1.4版本中正常工作,可根据代码风格偏好选择。

内容的提问来源于stack exchange,提问作者display name: terraform_practitioner

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 08:50:29