如何在 terraform 中提取敏感的输出变量?

How to extract sensitive output variables in terraform?

我有一个 terraform 配置,它创建一个带有访问密钥的 AWS IAM 用户,我将 id 和 secret 都分配给输出变量:

...

resource "aws_iam_access_key" "brand_new_user" {
  user = aws_iam_user.brand_new_user.name
}

output "brand_new_user_id" {
  value = aws_iam_access_key.brand_new_user.id
}

output "brand_new_user_secret" {
  value     = aws_iam_access_key.brand_new_user.encrypted_secret
  sensitive = true
}

这里brand_new_user_secret声明为敏感,所以terraform output显然不打印。

有什么办法可以不用解析整个状态文件就可以得到它的输出值吗? 尝试直接访问它 (terraform output brand_new_user_secret) 不起作用(导致错误 "The output variable requested could not be found in the state file...")。

Terraform 版本:0.12.18

我没试过,但文档似乎建议如果你想输出 encrypted_secret,你必须向 aws_iam_access_key 资源提供 pgp_key

  • pgp_key - (Optional) Either a base-64 encoded PGP public key, or a keybase username in the form keybase:some_person_that_exists, for use in the encrypted_secret output attribute.

  • encrypted_secret - The encrypted secret, base64 encoded, if pgp_key was specified. ~> NOTE: The encrypted secret may be decrypted using the command line, for example: terraform output encrypted_secret | base64 --decode | keybase pgp decrypt.

https://www.terraform.io/docs/providers/aws/r/iam_access_key.html

我曾希望避免它,但到目前为止我没有找到比解析地形状态更好的方法:

terraform state pull | jq '.resources[] | select(.type == "aws_iam_access_key") | .instances[0].attributes'

这将导致类似于以下的结构:

{
  "encrypted_secret": null,
  "id": "....",
  "key_fingerprint": null,
  "pgp_key": null,
  "secret": "....",
  "ses_smtp_password": "....",
  "ses_smtp_password_v4": null,
  "status": "Active",
  "user": "...."
}

我在这里使用了一个像这样的 hacky 解决方法...

resource "aws_iam_access_key" "brand_new_user" {
  user = aws_iam_user.brand_new_user.name
}

output "brand_new_user_id" {
  value = aws_iam_access_key.brand_new_user.id
}

data "template_file" "secret" {
  template = aws_iam_access_key.brand_new_user.encrypted_secret
}

output "brand_new_user_secret" {
  value     = data.template_file.secret.rendered
}

要以交互方式查看敏感值,即出于 analyzing/debugging 状态的目的,您可以使用 Terraform 的 console command and nonsensitive() 函数:

$ terraform console

> nonsensitive(aws_iam_access_key.brand_new_user.encrypted_secret)

您可能需要在打印之前使用其他函数 decode/manipulate 该值。

如果指定了单个输出,output 命令会打印敏感输出。这是使用 Terraform v1.1.7 和 0.14.8

terraform output brand_new_user_secret

未指定属性名称时得到的响应是:

brand_new_user_secret = (sensitive)

而问题说这会产生错误,因此行为可能自 0.12 以来已发生变化。

https://www.terraform.io/cli/commands/output