Kubernetes

如何使用 kustomize 從屬性文件載入配置映射?

  • October 15, 2021

我嘗試使用 kustomize 將屬性文件載入為配置映射。

為此,我在 github連結中創建了一個範例集。

使用基本文件:

#kustomize build base
apiVersion: v1
data:
 config: |-
   dbport=1234
   dcname=sfsdf
   dbssl=false
   locktime=300
   domainuser=
kind: ConfigMap
metadata:
 labels:
   owner: sara
 name: database-configmap
---
apiVersion: apps/v1
kind: Deployment
metadata:
 labels:
   app: nginx
   owner: sara
 name: nginx
spec:
 replicas: 1
 selector:
   matchLabels:
     app: nginx
     owner: sara
 template:
   metadata:
     labels:
       app: nginx
       owner: sara
   spec:
     containers:
     - image: nginx
       name: nginx

使用外部文件:

#kustomize build file
apiVersion: v1
data:
 config: "dbport=156767\r\ndcname=dfsd\r\ndbssl=false\r\nlocktime=300\r\ndomainuser=somedts"
kind: ConfigMap
metadata:
 labels:
   env: dev
   owner: sara
 name: dev-database-configmap
---
apiVersion: apps/v1
kind: Deployment
metadata:
 labels:
   app: nginx
   env: dev
   owner: sara
 name: dev-nginx
spec:
 replicas: 1
 selector:
   matchLabels:
     app: nginx
     env: dev
     owner: sara
 template:
   metadata:
     labels:
       app: nginx
       env: dev
       owner: sara
   spec:
     containers:
     - image: nginx
       name: nginx

如果您觀察到 configmap|被刪除並替換\r\n為單個字元串。如何修復這種對齊方式?

將此作為社區 wiki 發布,隨時編輯和擴展。


正如@mdaniel 在評論中提到的:

好吧,除了 \r 字元,這兩種形式是相同的;: | 標量引用僅供人類使用——當它進入集群時,它的形式為 config: “whatever\nwhatever-else\n”,因為 yaml2json 將針對這兩種形式顯示,或者,當然,它實際上是如何顯示的在 Pod 中實現

您可以通過從 kubernetes 集群中獲取 configmap 詳細資訊來檢查這一點,json並查看它們是否以相同的方式儲存(除了\r上面提到的附加內容):

$ kubectl get cm database-configmap -o json
{
   "apiVersion": "v1",
   "data": {
       "config": "dbport=1234\ndcname=sfsdf\ndbssl=false\nlocktime=300\ndomainuser="
   },
   "kind": "ConfigMap",
   ...

$ kubectl get cm dev-database-configmap -o json
{
   "apiVersion": "v1",
   "data": {
       "config": "dbport=156767\r\ndcname=dfsd\r\ndbssl=false\r\nlocktime=300\r\ndomainuser=somedts"
   },
   "kind": "ConfigMap",
   ...

StackOverflow 上有一個答案,它很快顯示了\n 、 \r 和 \r\n 之間的區別

引用自:https://serverfault.com/questions/1079866