在Angular 6中将Kubernetes机密用作环境变量 [英] Use Kubernetes secrets as environment variables in Angular 6

查看:76
本文介绍了在Angular 6中将Kubernetes机密用作环境变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我配置了自动构建Angular 6应用程序,并在每次将其推送到我的代码存储库(Google Cloud存储库)时在Kubernetes中进行部署.

I configured an automatic build of my Angular 6 app and deployment in Kubernetes each time is push to my code repository (Google Cloud Repository).

Dev环境变量通常按如下方式存储在environment.ts文件中:

Dev environment variables are classically store in a environment.ts file like this:

export const environment = {
  production: false,
  api_key: "my_dev_api_key"
};

但是我不想将Prod机密放到我的存储库中,所以我认为我可以使用Kubernetes机密.

But I don't want to put my Prod secrets in my repository so I figured I could use Kubernetes secrets.

因此,我在Kubernetes中创建了一个秘密:

So, I create a secret in Kubernetes:

kubectl create secret generic literal-token --from-literal api_key=my_prod_api_key

但是如何在我的Angular应用中使用它?

But how to use it in my Angular app?

推荐答案

尽管如此,您的Angular应用还是 client 应用,即用户的浏览器会下载该应用的源代码(一堆) CSS/JS/HTML文件,图片等),并在用户的计算机上执行.因此,您不能像实现 client/server 应用程序那样隐藏任何东西.在客户端/服务器应用程序中,所有机密都将驻留在服务器部分中.如果将机密放入k8s机密中,则不会将其提交到存储库中,但是无论如何您都将其公开给所有用户.

Nevertheless what you do, your Angular app is a client application i.e. the user's browser downloads the source code of the app (a bunch of CSS/JS/HTML files, images etc.) and it executes it on the user's machine. So you can't hide anything like you do when implementing a client/server app. In client/server applications all the secrets will reside in the server part. If you put the secret in a k8s secret you will not commit it in the repository, but you will expose it to all of your users anyway.

如果您仍然想基于环境变量填充配置(这是合法的用例),那么我已经看到并使用了以下方法.该应用程序为Angular 6,并由nginx服务器提供给浏览器. docker容器中的启动脚本有点奇怪,看起来类似于以下几行:

If you still want to populate a configuration based on environment variables (which is a legit use-case), I've seen and used the following approach. The app is Angular 6 and is served to the browser by an nginx server. The startup script in the docker container is a bit odd and looks similar to those lines below:

envsubst < /usr/share/nginx/html/assets/config.json.tpl > /usr/share/nginx/html/assets/config.json
rm /usr/share/nginx/html/assets/config.json.tpl
echo "Configuration:"
cat /usr/share/nginx/html/assets/config.json
nginx -g 'daemon off;'

如您所见,我们已经使用envsubst替换了Assets文件夹中的配置模板. config.json.tpl可能看起来像这样:

As you see we've used envsubst to substitute a config template in the assets folder. The config.json.tpl may look like this:

{
  "apiUrl": "${API_URL}"
}

envsubst将用其真实值替换环境变量,并且资产中将有一个有效的JSON配置代码段.然后nginx然后将启动.

envsubst will substitute the environment variables with their real values and you will have a valid JSON configuration snippet in your assets. Then nginx will then startup.

这篇关于在Angular 6中将Kubernetes机密用作环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆