跳至主要内容

nonsensitive 函数

nonsensitive 接受一个敏感值,并返回该值的副本,其中敏感标记已移除,从而暴露敏感值。

通常,OpenTofu 会跟踪您何时使用表达式从标记为敏感的值派生新值,以便结果也可以标记为敏感。

但是,您可能希望编写表达式,这些表达式从敏感值派生非敏感结果。例如,如果您根据特定系统及其威胁模型的详细信息知道,特定敏感值的 SHA256 哈希安全地包含在 OpenTofu 输出中,您可以使用 nonsensitive 函数来指示这一点,从而覆盖 OpenTofu 的正常保守行为

代码块
output "sensitive_example_hash" {
value = nonsensitive(sha256(var.sensitive_example))
}

另一个例子可能是,如果原始值仅部分敏感,并且您已编写表达式来分离敏感部分和非敏感部分

代码块
variable "mixed_content_json" {
description = "A JSON string containing a mixture of sensitive and non-sensitive values."
type = string
sensitive = true
}

locals {
# mixed_content is derived from var.mixed_content_json, so it
# is also considered to be sensitive.
mixed_content = jsondecode(var.mixed_content_json)

# password_from_json is derived from mixed_content, so it's
# also considered to be sensitive.
password_from_json = local.mixed_content["password"]

# username_from_json would normally be considered to be
# sensitive too, but system-specific knowledge tells us
# that the username is a non-sensitive fragment of the
# original document, and so we can override OpenTofu's
# determination.
username_from_json = nonsensitive(local.mixed_content["username"])
}

当您使用此函数时,您有责任确保作为其参数传递的表达式将从其依赖的敏感值中移除所有敏感内容。通过将值传递给 nonsensitive,您声明 OpenTofu 您已完成所有必要的步骤以确保结果值不包含敏感内容,即使它源自敏感内容。如果由于您模块中对 nonsensitive 的不当调用,敏感值出现在 OpenTofu 的输出中,那么这就是您模块中的错误,而不是 OpenTofu 本身中的错误。谨慎使用此函数,并仅在必要时使用。

nonsensitive 允许传递未标记为敏感的值,即使此类调用可能是多余的,并且可能对您模块的未来维护者造成混淆或误解。

考虑在您的调用旁边添加注释,向未来的维护者解释哪些因素使使用安全,以及他们在未来修改时必须注意哪些不变式。

示例

以下示例来自在上述示例的上下文中运行的 tofu console,其中包含 variable "mixed_content_json" 和本地值 mixed_content,并将有效的 JSON 字符串分配给 var.mixed_content_json

代码块
> var.mixed_content_json
(sensitive value)
> local.mixed_content
(sensitive value)
> local.mixed_content["password"]
(sensitive value)
> nonsensitive(local.mixed_content["username"])
"zqb"
> nonsensitive("clear")
"clear"

但请注意,您始终有责任仅在安全的情况下使用 nonsensitive。如果您使用 nonsensitive 处理应被视为敏感的内容,那么该内容将被公开

代码块
> nonsensitive(var.mixed_content_json)
<<EOT
{
"username": "zqb",
"password": "p4ssw0rd"
}
EOT
> nonsensitive(local.mixed_content)
{
"password" = "p4ssw0rd"
"username" = "zqb"
}
> nonsensitive(local.mixed_content["password"])
"p4ssw0rd"