使用 ConfigMap 掛載配置檔案
Intro
有一些敏感資訊比如資料庫連線字串之類的出於安全考慮,這些敏感資訊儲存在了 AzureKeyVault 中,最近應用上了 k8s 部署,所以想把 AzureKeyVault 的資訊遷移到 ConfigMap,不再依賴 AzureKeyVault。
ConfigMap
新建一個 ConfigMap,你可以從檔案建立,如何建立ConfigMap 可以參考官方檔案,也可以直接手動編輯,這裡用的 ConfigMap 如下所示:
apiVersion: v1kind: ConfigMapmetadata:name: reservation-configsnamespace: defaultdata:appsettings: |{"ConnectionStrings": {"Redis": "redis-server","Reservation": "Server=localhost;uid=liweihan;pwd=**;database=Reservation","ElasticSearch": "elasticsearch"},"MpWechat":{"AppId": "wx4a41d3773ae55543","AppSecret": "**********","Token": "AmazingDotNet","AESKey": "------------"},"AppSettings": {"WechatSubscribeReply": "","SentryClientKey": "https://**"},"Tencent": {"Captcha": {"AppId": "2062135016","AppSecret": "****"}},"GoogleRecaptcha": {"SiteKey": "6Lc-**","Secret": "6Lc-**"},"Logging": {"LogLevel": {"Default": "Warning","ActivityReservation": "Debug","RequestLog": "Debug"}}}
掛載 ConfigMap 中的配置檔案到 Pod
Deployment 定義如下所示, 這裡直接把上面定義的 appsettings 直接掛載為應用程式的根目錄下 appsettings.json 檔案
apiVersion: apps/v1kind: Deploymentmetadata:name: activityreservationnamespace: defaultlabels:app: activityreservationspec:replicas: 2revisionHistoryLimit: 2 # how many old ReplicaSets for this Deployment you want to retain, https://kubernetes.io/docs/concepts/workloads/controllers/deployment/#clean-up-policyselector:matchLabels:app: activityreservationminReadySeconds: 0strategy:type: RollingUpdaterollingUpdate:maxUnavailable: 1maxSurge: 1template:metadata:labels:app: activityreservationspec:dnsConfig:options:- name: ndotsvalue: "1"containers:- name: activityreservationimage: weihanli/activityreservation:20190529.2imagePullPolicy: IfNotPresentresources:limits:memory: "256Mi"cpu: "300m"readinessProbe:tcpSocket:port: 80initialDelaySeconds: 60periodSeconds: 30livenessProbe:httpGet:path: /Healthport: 80initialDelaySeconds: 60periodSeconds: 60ports:- containerPort: 80volumeMounts:- name: settingsmountPath: /app/appsettings.jsonsubPath: appsettingsvolumes:- name: settingsconfigMap:name: reservation-configs
測試
1. 部署 ConfigMap
kubectl apply -f ConfigMap.yaml
2. 部署 deployment
kubectl apply -f reservation-deployment.yaml
3. 等待 pod 啟動之後,檢視 appsettings.json 檔案內容是否成功被替換掉
獲取對應的 pod 名稱,然後透過 kubectlexec<pod-name>cat/app/appsettings.json 來獲取pod中 appsettings.json 檔案的內容
出現 ConnectionStrings 就證明檔案被替換掉了,原始的配置檔案裡是沒有 ConnectionStrings 節點的,原始的方式是透過從 AzureKeyVault 中載入的

Reference
- https://kubernetes.io/docs/tasks/configure-pod-container/configure-pod-configmap/#understanding-configmaps-and-pods
- https://github.com/WeihanLi/ActivityReservation
知識星球
朋友會在“發現-看一看”看到你“在看”的內容