使用 ConfigMap
掛載配置檔案
Intro
有一些敏感資訊比如資料庫連線字串之類的出於安全考慮,這些敏感資訊儲存在了 AzureKeyVault
中,最近應用上了 k8s 部署,所以想把 AzureKeyVault
的資訊遷移到 ConfigMap
,不再依賴 AzureKeyVault
。
ConfigMap
新建一個 ConfigMap,你可以從檔案建立,如何建立ConfigMap 可以參考官方檔案,也可以直接手動編輯,這裡用的 ConfigMap 如下所示:
apiVersion: v1
kind: ConfigMap
metadata:
name: reservation-configs
namespace: default
data:
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/v1
kind: Deployment
metadata:
name: activityreservation
namespace: default
labels:
app: activityreservation
spec:
replicas: 2
revisionHistoryLimit: 2 # how many old ReplicaSets for this Deployment you want to retain, https://kubernetes.io/docs/concepts/workloads/controllers/deployment/#clean-up-policy
selector:
matchLabels:
app: activityreservation
minReadySeconds: 0
strategy:
type: RollingUpdate
rollingUpdate:
maxUnavailable: 1
maxSurge: 1
template:
metadata:
labels:
app: activityreservation
spec:
dnsConfig:
options:
- name: ndots
value: "1"
containers:
- name: activityreservation
image: weihanli/activityreservation:20190529.2
imagePullPolicy: IfNotPresent
resources:
limits:
memory: "256Mi"
cpu: "300m"
readinessProbe:
tcpSocket:
port: 80
initialDelaySeconds: 60
periodSeconds: 30
livenessProbe:
httpGet:
path: /Health
port: 80
initialDelaySeconds: 60
periodSeconds: 60
ports:
- containerPort: 80
volumeMounts:
- name: settings
mountPath: /app/appsettings.json
subPath: appsettings
volumes:
- name: settings
configMap:
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
朋友會在“發現-看一看”看到你“在看”的內容