Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

terraform-kubernetes-provider how to create secret from file?

I'm using the terraform kubernetes-provider and I'd like to translate something like this kubectl command into TF:

kubectl create secret generic my-secret --from-file mysecret.json

It seems, however the secret resource's data field expects only a TF map.

I've tried something like

data "template_file" "my-secret" {
  template = "${file("${path.module}/my-secret.json")}"
}

resource "kubernetes_secret" "sgw-config" {
   metadata {
     name = "my-secret"
   }
   type = "Opaque"
   data = "{data.template_file.my-secret.template}"
}

But it complains that this is not a map. So, I can do something like this:

   data = {
      "my-secret.json" = "{data.template_file.my-secret.template}"
   }

But this will write the secret with a top-level field named my-secret.json and when I volume mount it, it won't work with other resources.

What is the trick here?

like image 632
Davis Ford Avatar asked Mar 25 '19 18:03

Davis Ford


1 Answers

This might be a bit off-topic, but I've been facing similar problem except that the file might not be present in which case the terraform [plan|apply] fails.

To be exact: I needed to duplicate a secret from one namespace to another one.

I realized that by using hashicorp/external provider.

The steps are pretty simple:

  1. Load data by calling external program
  2. Refer to the data in kubernetes_secret resource

The program should accept (and process) JSON on STDIN and produce valid JSON on STDOUT as response to the parameters passed-in in the STDIN's JSON.

Example shell script:

#!/bin/bash

set -e

/bin/echo -n '{ "token": "'
kubectl get -n consul secrets/hashicorp-consul-bootstrap-acl-token --template={{.data.token}}
/bin/echo -n '"}'

tarraform source:


data "external" "token" {
  program = ["sh", "${path.module}/consul-token.sh"]
}

resource "kubernetes_secret" "consul-token" {
  depends_on = [data.external.token]

  metadata {
    name      = "consul-token"
    namespace = "app"
  }

  data = {
    token = base64decode(data.external.token.result.token)
  }
}

and requirements:


terraform {
  required_providers {
    external = {
      source  = "hashicorp/external"
      version = ">= 2.0.0"
    }
  }
}
like image 121
Petr Hadraba Avatar answered Sep 30 '22 19:09

Petr Hadraba