简体   繁体   中英

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.

I've been playing with using for_each to see if I can achieve this without scrolling through a very long.tf file. 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. Here's my current terraform setup on my tests:


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. However it doesnt like ${random_id.dbusername_suffix.hex} and complains about the use of the variable alongside each.key and won't run. 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.

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.

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}"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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