Search code examples
jsonterraform

Unable to set JSON value to variable in Terraform


I have this code to write some json data to Vault from Terraform and I have added these resources to write in main.tf -

provider "vault" {
address = "https://secrets.staging.hulu.com"

auth_login {
   path = "auth/aws/login"
   method = "aws"
   namespace = var.vault_namespace
   parameters = {
      role         = "service-${var.yp_service_id}-tfe"
      header_value = var.header_value
      sts_region   = local.region
    }
  }
}

resource "vault_generic_secret" "example" {
   path      = "kv/${var.yp_service_id}/secret"
   data_json = var.secret
}

data vault_generic_secret example {
  depends_on = [vault_generic_secret.example]
  path      = "kv/${var.yp_service_id}/secret"
}

The data that I get to write is in json format, that looks like this which I think is a valid JSON data -

{
  "DD_API_KEY": "*****************",
  "DD_APP_KEY": "*****************",
  "DD_SITE": "datadoghq.com"
}

I have declared the variables here in variables.tf -

variable "address" {
  type        = string
  description = "vault address"
  default     = "https://secrets.staging.dummy.com"
}

variable "vault_namespace" {
  type        = string
  description = "vault namespace"
  default     = "5f8dd98fc08eda598857b651"
}

variable "header_value" {
  type        = string
  description = "vault header"
  default     = "secrets.staging.dummy.com"
}

variable "secret" {
  description = "Sensitive secrets for the service"
  type        = map(string)
  sensitive   = true
}

variable "data_json" {
  description = "Sensitive secrets for the service"
  type        = map(any)
  sensitive   = true
  default     = {}
}

But when I run terraform plan, I keep getting this error -

Waiting for the plan to start...

Terraform v1.7.5
on linux_amd64
Initializing plugins and modules...
╷
│ Error: Incorrect attribute value type
│ 
│   on main.tf line 173, in resource "vault_generic_secret" "example":
│  173:   data_json = var.secret
│ 
│ Inappropriate value for attribute "data_json": string required.
╵
Operation failed: failed running terraform plan (exit 1)

How do I set the value to data_json here? Am I missing something? This is in version 1.7.5 by the way. Thanks in advance!


Solution

  • According to the current config in the question the type of variable secret is a HCL2 map(string), and the Vault provider expects a type of string. Therefore one must encode the HCL2 to JSON:

    resource "vault_generic_secret" "example" {
      path      = "kv/${var.yp_service_id}/secret"
      data_json = jsonencode(var.secret)
    }
    

    Although the value of var.secret is not specified in the question, the value transmitted to Vault is, and therefore the following would be the expected value of var.secret to encode to the desired JSON specified in the question:

    {
      "DD_API_KEY" = "*****************",
      "DD_APP_KEY" = "*****************",
      "DD_SITE"    = "datadoghq.com"
    }