使用 K8S 清单"env:"中的 API 值覆盖 environment.ts 中的 API URL



我想知道是否有可能在环境中重写值。ts文件(angular)与Kubernetes清单?

我这样做是为了应用。

这是我为Spring做的:

spec:
containers:
- name: $(appName)
image: ACR/$(image)
imagePullPolicy: 
ports:
- name: http
containerPort: 8080
protocol: TCP
env:
- name: SPRING_DATASOURCE_PASSWORD
value: "$(datasourcePassword)"

和密码的值根据我为$(datasourcePassword)变量(azure devops变量)设置的值而更改。如果我设置了一个假密码,API将无法访问DB。

但是如果我对Angular的manifest做同样的处理:

spec:
containers:
- name: $(appName)
image: ACR/$(image)
imagePullPolicy: 
ports:
- name: http
containerPort: 8181
protocol: TCP
env:
- name: APIENDPOINT
value: "$(APIurl)"

前面仍然使用环境中默认定义的值。ts:

export const environment = {
production: true,
APIEndpoint: 'http://localhost:8080'
};

我哪里做错了?

谢谢你的帮助!

我遇到了你描述的同样的问题。我发现解决这个问题的一个好方法是创建一个environment-service-loader,我在其中对来自环境的属性进行合并。在environment.ts.

让我来描述每一步。

1。在app.module.ts中创建以下两个提供程序

import {environment} from '../environments/environment';
function initEnvironmentServiceFactory(
envServiceLoader: EnvServiceLoader,
environmentService: EnvironmentService
) {
return async () => {
const envs = await envServiceLoader.loadEnvVariables();
environmentService.setEnvVariables(envs);
};
}
providers: [
....
{provide: 'environment_prod', useValue: environment},
{
provide: APP_INITIALIZER,
useFactory: initEnvironmentServiceFactory,
deps: [EnvServiceLoader, EnvironmentService],
multi: true
},
....

2。创建将"覆盖"的enviserviceloader环境。t和env中定义的属性。assets/Json下的Json文件。在本例中,我将键生成定义为不可编辑的。

@Injectable({
providedIn: 'root'
})
export class EnvServiceLoader {
UNEDITABLE_PROPERTIES = ['production'];
constructor(@Inject('environment_prod') private environment, private 
httpClient: HttpClient) {
}
async loadEnvVariables(): Promise<any> {
const envJson = await this.getJsonConfig();
return {...this.environment, ...envJson, ...this.getUneditableConfig(this.environment)};
};
private getJsonConfig(): Promise<any> {
return this.httpClient.get('./assets/json/env.json')
.pipe(map((res: string) => JSON.parse(res)),
catchError(() => of({})
)).toPromise();
}
private getUneditableConfig(environmentConfig: any) {
return this.UNEDITABLE_PROPERTIES.reduce((config, key) => {
config[key] = environmentConfig[key];
return config;
}, {});
};
}

3。创建环境服务

@Injectable({
providedIn: 'root'
})
export class EnvironmentService {
private env;
setEnvVariables(env): void {
this.env = env;
}
getEnvVariables(): any {
return this.env;
}
}

KUBERNETES

1。创建一个configmap在Kuberentes中包含你想通过env.json覆盖的值

apiVersion: v1
kind: ConfigMap
metadata:
name: client-config
data:
env.json: |
"{"API_endpoint": "http://localhost:8080"}

2。在客户端的Kubernetes部署中,通过一个卷(在本例中名为config-volume),可以将configmap的内容复制到文件env中。/usr/share/nginx/html/assets/json

containers:
- image: your_client_image
imagePullPolicy: Always
name: your_client
ports:
- containerPort: 80
name: http
volumeMounts:
- mountPath: /usr/share/nginx/html/assets/json
name: config-volume
volumes:
- configMap:
name: client-config
name: config-volume

最新更新