使用 ConfigMap
掛載配置文件
Intro
有一些敏感信息比如數據庫連接字符串之類的出於安全考慮,這些敏感信息保存在了 Azure KeyVault
中,最近應用上了 k8s 部署,所以想把 Azure KeyVault
的信息遷移到 ConfigMap
,不再依賴 Azure KeyVault
。
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
測試
-
部署
ConfigMap
kubectl apply -f ConfigMap.yaml
-
部署
deployment
kubectl apply -f reservation-deployment.yaml
-
等待 pod 啟動之后,查看
appsettings.json
文件內容是否成功被替換掉獲取對應的 pod 名稱,然后通過
kubectl exec <pod-name> cat /app/appsettings.json
來獲取pod中 appsettings.json 文件的內容出現 ConnectionStrings 就證明文件被替換掉了,原始的配置文件里是沒有 ConnectionStrings 節點的,原始的方式是通過從
Azure KeyVault
中加載的