Save kubeconfig yaml to vault via terraform

Hi.

How do i use Terraform vault provider to write a k8s config under a KV2 engine using
vault_generic_secret under terraform

https://registry.terraform.io/providers/hashicorp/vault/latest/docs/resources/generic_secret

Is it also possible to read the value of the K8 kubeconfig from a file and substitute the value for the key?

I am trying the following

data "local_file" "input" {
    filename = var.shoot_kubeconfig_path
}

resource "vault_generic_secret" "vault_secret_kvv2_new" {
  provider = vault.child_namespace
  path = join("/", [ var.kvv2_secret_path, "config2" ])

  data_json = <<EOT
{
  "foo":  "${data.local_file.input.content}"
}
EOT

  depends_on = [ vault_mount.kvv2 ]
}

Error

Error: invalid character '\n' in string literal

  on main.tf line 61, in resource "vault_generic_secret" "vault_secret_kvv2_new":
  61: resource "vault_generic_secret" "vault_secret_kvv2_new" {

Kevin

did you ever figure this out?

I believe the problem with the earlier example is that it’s trying to incorporate a whole kubeconfig document into a JSON string without encoding, using just string interpolation.

I think something like:

  data_json = jsonencode({foo = data.local_file.input.content})

ought to work.

I have been attemtping jsondecode but I get a different error

│ Error: Error in function call

│ on main.tf line 11, in resource “vault_generic_secret” “main”:
│ 11: data_json = jsondecode(azurerm_kubernetes_cluster.main.kube_config_raw)
│ ├────────────────
│ │ azurerm_kubernetes_cluster.main.kube_config_raw has a sensitive value

│ Call to function “jsondecode” failed: invalid character ‘a’ looking for
│ beginning of value.

There are two ways in which what you’re trying doesn’t match what I posted:

  • jsonencode, not jsondecode
  • You do need to wrap the string kubeconfig in a object/dictionary: {some_key_name_doesnt_matter_what_you_decide = literal_kubeconfig_string_value}
1 Like

Here is the fix that worked for me, not totally related to the OP but it might be helpful for those having similar issues.

For anyone looking for help on this down the line, here is the resolution

resource “vault_generic_secret” “main” {

path = “kv/mynamespace”

data_json = jsonencode(yamldecode("${azurerm_kubernetes_cluster.main.kube_config_raw}"))

}

If you do it this way, you’re taking your YAML kubeconfig, and turning it into parsed JSON, and storing that in Vault.

This may be fine for your use-case, but technically it’s lossy, if you cared about preserving comments or other YAML features not supported in JSON.