简体   繁体   English

Terraform for_each 用于 GCP 秘密,append 带有 random_ID 后缀

[英]Terraform for_each for GCP secret, append with random_ID suffix

I've been trying to find a way to make my terraform files a bit slicker, I have to create around 15 google secret resources, and their respective secret versions, for our production and staging environments.我一直在努力寻找一种方法让我的 terraform 文件更流畅一些,我必须为我们的生产和暂存环境创建大约 15 个谷歌秘密资源及其各自的秘密版本。

I've been playing with using for_each to see if I can achieve this without scrolling through a very long.tf file.我一直在尝试使用for_each来查看是否可以在不滚动非常长的.tf 文件的情况下实现这一点。 However, as part of the username (and password) creation, I'm using some built in TF functions, such as the random_ID generator and password generator, but I can't seem to get these integrated with the setup.然而,作为用户名(和密码)创建的一部分,我使用了一些内置的 TF 函数,例如 random_ID 生成器和密码生成器,但我似乎无法将它们与设置集成。 Here's my current terraform setup on my tests:这是我当前的 terraform 测试设置:


resource "random_id" "dbusername_suffix" {
  byte_length = 4
}

resource "google_secret_manager_secret" "user" {
  for_each = toset( ["user1", "user2", "user3"] )
  provider = google-beta

  secret_id = each.key

  replication {
    automatic = true
  }

  depends_on = [google_project_service.secretmanager]
}

resource "google_secret_manager_secret_version" "user-secret-version" {
  provider = google-beta
  for_each = toset( ["user1", "user2", "user3"] )

  secret      = google_secret_manager_secret.user[each.key].id
  secret_data = each.key_${random_id.dbusername_suffix.hex}
}

I want the secret data to look something like this: user1_hgfjsidg for example.我希望秘密数据看起来像这样:例如user1_hgfjsidg However it doesnt like ${random_id.dbusername_suffix.hex} and complains about the use of the variable alongside each.key and won't run.但是它不喜欢${random_id.dbusername_suffix.hex}并且抱怨在 each.key 旁边使用变量并且不会运行。 I've also tried with quotes and all that does is create the secret with the data "each.key-jsflknlf" so its not reading the keys.我也尝试过使用引号,所做的只是用数据“each.key-jsflknlf”创建秘密,这样它就不会读取密钥。

I have tried doing this also:我也试过这样做:

resource "google_secret_manager_secret_version" "user-secret-version" {
  provider = google-beta
  for_each = toset( ["user1_${random_id.dbusername_suffix.hex}", "user2_${random_id.dbusername_suffix.hex}", "user3_${random_id.dbusername_suffix.hex}"] )

  secret      = google_secret_manager_secret.user[each.key].id
  secret_data = each.key
}

But this also doesn't work, as it requires the data to be in the secret name, which defeats the object.但这也行不通,因为它要求数据在秘密名称中,这打败了 object。

Any ideas to try would be great, if this is possible to do.如果可能的话,任何尝试的想法都会很棒。

Sorted, re-read the docs and found it needs to be in this format:排序,重新阅读文档,发现需要这样的格式:

secret_data = "${each.key}_${random_id.dbusername_suffix.hex}"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM