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

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

as long the file is UTF-8 encoded you can use something like this

resource kubernetes_secret some-secret {

      metadata {
        name      = some-secret
        namespace = kubernetes_namespace.some-ns.metadata.0.name
        labels = {
          sensitive = true
          app       = my-app
        }
      }
      data = {
        file.txt = file(${path.cwd}/your/relative/path/to/file.txt)
      }
    }

If the file is a binary one you will have an error like

Call to function file failed: contents of
/your/relative/path/to/file.txt are not valid UTF-8; use the
filebase64 function to obtain the Base64 encoded contents or the other
file functions (e.g. filemd5, filesha256) to obtain file hashing
results instead.

I tried encoding the file in base64 but then the problem is that the resulting text will be re-encoded in base64 by the provider. So I guess there is no solution for binary files at the moment…
Ill edit with what I find next for binaries.

Just use
https://www.terraform.io/docs/providers/kubernetes/r/config_map.html#binary_data

resource kubernetes_config_map example {

  metadata {
    name = my-config
  }

  binary_data = {
    my_payload.bin = ${filebase64(${path.module}/my_payload.bin)}
  }
}

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

This might be a bit off-topic, but Ive 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 STDINs 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
    }
  }
}

Leave a Reply

Your email address will not be published.