<p>I'm trying to use Kubernetes <a href="https://kubernetes.io/docs/tasks/administer-cluster/access-cluster-api/#go-client" rel="nofollow noreferrer">Go-Client</a> in my program (which will run outside my Kubernetes cluster) which requires access to config file. The config file requires some token, service account details etc so that the program can access the Kubernetes cluster. </p>

<p>The config file is of the form below: </p>

<pre><code>apiVersion: v1
kind: Config
users:
- name: testsa
  user:
    token: my-token
clusters:
- cluster:
    certificate-authority-data: my-cert
    server: my-server
  name: self-hosted-cluster
contexts:
- context:
    cluster: self-hosted-cluster
    user: testsa
  name: test-name
current-context: test-context
</code></pre>

<p>In the above file I need to give <code>my-token</code>, <code>my-cert</code> &amp; <code>my-server</code> as environment variables since I can't hard-code this in the file present in the repository due to security reason. How can I do that? </p>

Satyajit Das
<p>Thanks Markus for the hint link. </p>

<p>I am writing the answer in Go as the original link showed how to do it from command line. The steps are as follows: </p>

<ul>
<li>Replace the fields to be modified in the file with something of the form <code>${X}</code>.  In my case e.g. I replaced <code>my-token</code> with <code>${my-token}</code> and so on.</li>
<li>Here you can set <code>X</code> as an environment variable so that your code can access it during runtime. e.g. by doing <code>export X="abcd"</code> in command line.</li>
<li>Say the file name is <code>config</code>.</li>
<li>Execute the following code: </li>
</ul>

<pre><code>package main

import (
    "os"
    "os/exec"
)

func main() {
    mytoken := os.Getenv("mytoken")
    part := fmt.Sprintf("s/${mytoken}/%s/g", mytoken)
    command := exec.Command("sed", "-i", "", "-e", part, "config")
    command.Run()
}
</code></pre>

<p>This will do the required replacement during runtime. </p>
