Reza
Reza

Reputation: 19843

How can I use terraform data in variables

I have a script like below

variables.tf


data "google_secret_manager_secret_version" "my_secret" {
  secret = "my-secret"
}

variable "clients" {
  description = "clients data"
  default = [
    {
      id           = { stringValue = "test" }
      clientSecret = { stringValue = "${data.google_secret_manager_secret_version.my_secret.secret_data}" }
      eventType    = { stringValue = "something" }
    }
  ]
}

main.tf

resource "google_firestore_document" "clients" {
  for_each = {
    for index, client in var.clients :
    index => client
  }
  project     = var.project_id
  collection  = "clients"
  document_id = each.value.id.stringValue
  fields      = jsonencode(each.value)
}

but when I run it I get this error

Error: Variables not allowed
  on variables.tf line 16, in variable "clients":
  16:       clientSecret        = { stringValue = "${data.google_secret_manager_secret_version.my_secret.secret_data}" }

Variables may not be used here.

Wondering how can I use dynamic values read from secret manager and use it in variable or any other solutions

Upvotes: 2

Views: 1001

Answers (1)

Reza
Reza

Reputation: 19843

I finally ended up like this

variables.tf

variable "clients" {
  description = "clients data"
  default = {
    X = {
      id                  = { stringValue = "test" }
      eventType           = { stringValue = "something" }
    }
  }
}

main.tf

data "google_secret_manager_secret_version" "my_secret" {
  project = var.project_id
  secret  = "my-secret"
}

resource "google_firestore_document" "clients-x" {
  project     = var.project_id
  collection  = "clients"
  document_id = var.clients.X.id.stringValue
  fields = jsonencode(merge(
    var.clients.X,
    {
      clientSecret = { stringValue = data.google_secret_manager_secret_version.my_secret.secret_data }
    }
  ))
}

Upvotes: 3

Related Questions