如何在 google kubernetes 引擎上设置环境变量?

时间:2021-04-01 12:38:24

标签: docker kubernetes google-cloud-platform google-kubernetes-engine

我在 Firebase 托管的 GoLang 项目中使用 Google Kubernetes Engine

我遵循的步骤:

  1. 在 firebase 帐户上启用 firebase admin SDK。它为我生成了一个服务帐户 JSON。这也在我的 Google 控制台服务凭据下创建了一个服务帐户。

  2. 遵循此 answer 并使用 kubectl create secret generic google-application-credentials --from-file=./sample-project.json

    添加新的密钥
  3. 对我的 deployment.YAML 文件进行了更改(添加了卷安装和环境变量)

    spec:
      containers:
      - image: gcr.io/sample-ee458/city:0.27
      name: city-app
      volumeMounts:
      - name: google-application-credentials-volume
        mountPath: /etc/gcp
        readOnly: true 
    env:
    - name: GOOGLE_APPLICATION_CREDENTIALS
      value: /etc/gcp/application-credentials.json
    
  4. 在同一个文件中设置卷

    volumes:
    - name: google-application-credentials-volume
    secret:
      secretName: google-application-credentials
      items:
      - key: application-credentials.json # default name created by the create secret from-file command
      path: application-credentials.json
    
  5. 运行 kubectl apply -f deployment.yaml 并使用 docker push 命令进行部署。

它让我error getting credentials using google_application_credentials environment variable gke。我在这里缺少什么?任何提示都值得赞赏。

3 个答案:

答案 0 :(得分:2)

您可以通过两种不同的方式使用 Secret:

  • 将 Secret 安装为并作为文件访问
  • 将 Secret 映射到环境变量并通过读取变量访问它

你似乎把它们都混在一起了。决定是要作为文件(推荐)还是作为环境变量来访问它。

在文档中查看两者的示例:

示例 - 作为环境变量访问它

首先,创建 Secret,这可以像您一样完成:

kubectl create secret generic google-application-credentials --from-file=./application-credentials.json
<块引用>

我想以环境变量的形式访问它。

要将秘密公开为 Pod 或部署中的环境变量,请将您的 Pod 模板编写为:

  containers:
  - name: city-app
    image: gcr.io/sample-ee458/city:0.27
    env:
      - name: GOOGLE_APPLICATION_CREDENTIALS
        valueFrom:
          secretKeyRef:
            name: google-application-credentials  # name of the Secret
            key: application-credentials.json

当作为环境变量访问 Secret 时,您不需要将其添加为卷。

答案 1 :(得分:1)

最后,我弄清楚如何复制它并使用环境变量。这是。更新后的YAML文件

apiVersion: apps/v1beta1
kind: Deployment
metadata:
  name: my-app
spec:
  template:
    spec:
      volumes:
      - name: google-cloud-keys
        secret:
          secretName: gac-keys
      containers:
      - name: my-app
        image: us.gcr.io/my-app
        volumeMounts:
        - name: google-cloud-keys
          mountPath: /var/secrets/google
          readOnly: true
        env:
        - name: GOOGLE_APPLICATION_CREDENTIALS
          value: /var/secrets/google/new-file-name.json

答案 2 :(得分:0)

当前的答案是关于秘密、环境变量和卷的正确答案。但是,如果您尝试在 GKE 中加载身份验证,我绝对不建议使用服务帐户密钥文件。

在 GKE 上,有一个名为 workload identity 的强大功能。它与 metadata server on a compute engine instance(和其他产品)完全一样,但在 pod 和命名空间级别(创建一个代理来拦截元数据服务器调用并将它们重定向到正确的凭据,配置有工作负载标识)。

它更安全,您不必保存和管理机密文件,以及所有的限制和涉及的风险。

相关问题