コンテンツにスキップ

06. 秘密の情報を扱う

リソースに秘密の情報をハードコーディングすると内容を共有できない問題が起きる。

そういうときはSecretを定義する。

k8s/secret.yaml
1
2
3
4
5
6
7
8
9
apiVersion: v1
kind: Secret
metadata:
  name: app-secret
type: Opaque
stringData:
  postgres-url: postgresql://postgres:postgres@db:5432/todo
  postgres-password: postgres
  postgres-user: postgres

k8s/secret.yaml.gitignoreに追加する。

k8s/app-deployment.yaml
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
 apiVersion: apps/v1
 kind: Deployment
 metadata:
   labels:
     io.kompose.service: app
   name: app
 spec:
   selector:
     matchLabels:
       io.kompose.service: app
   template:
     metadata:
       labels:
         io.kompose.service: app
     spec:
       containers:
         - env:  # アプリに渡す環境変数を定義する
             - name: DATABASE_URL
-              value: postgresql://postgres:postgres@db:5432/todo
+              valueFrom:
+                secretKeyRef:
+                  name: app-secret
+                  key: postgres-url
             - name: HOSTNAME
               value: "0.0.0.0"
           image: 192.168.11.42:8085/nextjs-todo-example:latest  # 使うDockerイメージを指定する
           name: app
           ports:
             - containerPort: 3000
               protocol: TCP
           resources:  # CPUの使用量の下限・上限を指定する
             requests:
               cpu: "4m" # Pod1個で0.004コアを確保する
             limits:
               cpu: "10m" # Pod1個で最大0.01コアを確保する
       restartPolicy: Always