<p>I am currently developing a small API in golang which will connect to a sql database. Below is the snip where I am passing the database connection string details statically ( hardcoded in the code ) .</p>
<pre><code>const (
DB_USER     = &quot;username&quot;
DB_PASSWORD = &quot;password&quot;
DB_NAME     = &quot;db_name&quot;
DB_HOST     = &quot;db_server_name&quot;
DB_PORT     = db_port )
</code></pre>
<p>Now I want to use ENV variables to make this static hardcoded values to become dynamic, so anyone on the fly can set these details using ENV vars. Can someone help me how I can achieve this. How to set them in such way from code so it can be dynamically passed as ENV vars in k8's deployment ?</p>
<p>My current deployment.yaml file as below</p>
<pre><code>apiVersion: apps/v1
kind: Deployment
metadata:
  name: go-demo-app
spec:
  replicas: 1
  selector:
    matchLabels:
      app: go-demo-app
  template:
    metadata:
      labels:
        app: go-demo-app
    spec:
      containers:
        - name: go-demo-app
          image: dockerhub/go-api:latest
          resources: {}
          ports:
            - containerPort: 8001
</code></pre>
<p>The above is working fine as the db server name is hardcoded in the code and now I can looking to pass it dynamically using ENV vars via code which I can refer in k8's deployment</p>

Mahesh
<p>Change the .yaml to</p>
<pre><code>apiVersion: apps/v1
kind: Deployment
metadata:
  name: go-demo-app
spec:
  replicas: 1
  selector:
    matchLabels:
      app: go-demo-app
  template:
    metadata:
      labels:
        app: go-demo-app
    spec:
      containers:
        - name: go-demo-app
          image: dockerhub/go-api:latest
          resources: {}
          ports:
            - containerPort: 8001
          env:
            - name: DB_USER
              value: username
            - name: DB_PASSWORD 
              value: password
            - name: DB_NAME     
              value: db_name
            - name: DB_HOST     
              value: db_server_name
            - name: DB_PORT     
              value: &quot;3306&quot;
</code></pre>
<p><code>kubectl apply -f /path/to/file</code></p>
<p>on your code, change the initialization into</p>
<pre><code>var (
    DB_USER     = os.Getenv(&quot;DB_USER&quot;)
    DB_PASSWORD = os.Getenv(&quot;DB_PASSWORD&quot;)
    DB_NAME     = os.Getenv(&quot;DB_NAME&quot;)
    DB_HOST     = os.Getenv(&quot;DB_HOST&quot;)
    DB_PORT     = os.Getenv(&quot;DB_PORT&quot;)
)
</code></pre>
<p>I change const to var because it is not allowed</p>
