简体   繁体   English

访问机密作为 Kubernetes 中的环境变量

[英]Access secrets as environment variables in Kubernetes

I'm using Secrets as an environmental variable and I was wondering how you would call the secret in the client side of my application?我使用 Secrets 作为环境变量,我想知道您将如何在我的应用程序的客户端调用密钥? I'm running a Node.js application and want to use the Secrets environmental variable.我正在运行 Node.js 应用程序并希望使用 Secrets 环境变量。 I would normally call my environment variables by doing process.env.VARIABLE_NAME locally since I have an env file, but I know that it's not the same for a secret as environmental variable when deployed onto Kubernetes.我通常会通过在本地执行process.env.VARIABLE_NAME来调用我的环境变量,因为我有一个 env 文件,但我知道当部署到 Kubernetes 时,它与环境变量的秘密不同。

Could anybody help me with this?有人可以帮我吗? Thanks!谢谢!

The environment variable created by secret will read as eny other environment variable passed to pod. secret 创建的环境变量将读取为传递给 pod 的任何其他环境变量。

So if you create a secret, for example:因此,如果您创建一个秘密,例如:

kubectl create secret generic user --from-literal=username=xyz

and pass it to the pod:并将其传递给 pod:

env:
- name: USERNAME
  valueFrom:
    secretKeyRef:
      name: user
      key: username

It will be passed to the pod as environment variable.它将作为环境变量传递给 pod。 You can check it by executing printenv USERNAME in the pod and output will be similar to this:您可以通过在 pod 中执行printenv USERNAME来检查它,output 将与此类似:

kubectl exec -it secret-env -- printenv USERNAME
xyz

Multiple secrets can be passed to the pod as environment variables. 多个秘密可以作为环境变量传递给 pod。

After days of figuring out how to use Secrets as an environmental variable, I figured out how to reference it in my nodejs application!在弄清楚如何使用 Secrets 作为环境变量几天之后,我想出了如何在我的 nodejs 应用程序中引用它!

Before I was doing the normal way of calling environmental variables, process.env.VARIABLE_NAME , but that did not work for me when I had Secrets as an environment variable.在我以正常方式调用环境变量之前, process.env.VARIABLE_NAME ,但是当我将 Secrets 作为环境变量时,这对我不起作用。 In order to get the value of the variable, I had to do process.env.ENVIRONMENTAL_VARIABLES_USERNAME in my Javascript file and that worked for me!为了获得变量的值,我必须在我的 Javascript 文件中执行process.env.ENVIRONMENTAL_VARIABLES_USERNAME ,这对我有用! Where ENVIRONMENTAL_VARIABLES is the name and USERNAME is the key : Refer to my other question for clarification: Environmental variables returning undefined for Kubernetes deployment其中ENVIRONMENTAL_VARIABLESname ,而USERNAMEkey :请参阅我的其他问题以进行澄清: Environmental variables returned undefined for Kubernetes deployment

Not sure if this will help anyone else but this is how I managed to access my Secrets in my nodejs application!不确定这是否对其他人有帮助,但这就是我设法在我的 nodejs 应用程序中访问我的秘密的方式!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM