Secret、ConfigMap

咋滴都行發表於2020-11-11

Secret

什麼是Secret?作用是什麼?
用來儲存一些敏感資訊,比如MySQL服務的賬號和密碼,或者一些祕鑰、證書等。
舉例:
使用者名稱: root
密碼: 123.com

將上述資訊,儲存為Secret資源,應該怎麼做?
一、–from-literal

[root@master ~]# kubectl create secret generic mysecret1 --from-literal=username=root --from-literal=password=123.com
secret/mysecret1 created

PS: generic(通用的,公共的)–演算法。
//檢視Secrets資源物件

[root@master ~]# kubectl get secrets 
NAME                  TYPE                                  DATA   AGE
default-token-vnwn4   kubernetes.io/service-account-token   3      5d21h
mysecret1             Opaque

//這裡我們使用Describe命令,檢視其詳細資訊,等看到對應的key值,卻看不到詳細values值,因為建立的時候,我們給這個資料做了一個加密動作

[root@master ~]# kubectl get secrets 
NAME                  TYPE                                  DATA   AGE
default-token-vnwn4   kubernetes.io/service-account-token   3      5d21h
mysecret1             Opaque                                2      2m40s
[root@master ~]# kubectl describe secrets mysecret1 
Name:         mysecret1
Namespace:    default
Labels:       <none>
Annotations:  <none>

Type:  Opaque

Data
====
password:  7 bytes
username:  4 bytes

注意: 一個–from-literal語句,只能儲存一條資訊。

二、–from-file

[root@master secret]# echo root > username
[root@master secret]# echo 123.com > password
[root@master secret]# kubectl create secret generic mysecret2 --from-file=username --from-file=password
secret/mysecret2 created
[root@master secret]# kubectl get secrets 
NAME                  TYPE                                  DATA   AGE
default-token-vnwn4   kubernetes.io/service-account-token   3      5d21h
mysecret1             Opaque                                2      6m50s
mysecret2             Opaque                                2      13s

PS: --from-file的方式,並沒有想象中那麼全面,厲害。因為每個檔案中,只能夠儲存一條資訊。

三、–from-env-file

[root@master secret]# cat env.txt 
username=root
password=123.com
[root@master secret]# kubectl create secret generic mysecret3 --from-env-file=env.txt
secret/mysecret3 created
[root@master secret]# kubectl get secrets 
NAME                  TYPE                                  DATA   AGE
default-token-vnwn4   kubernetes.io/service-account-token   3      5d21h
mysecret1             Opaque                                2      8m49s
mysecret2             Opaque                                2      2m12s
mysecret3             Opaque                                2      9s

PS: 這種儲存資料的方式,比第二種要方便的多,不過要注意的是,檔案中,每一行只能記錄一條資料(key=value)。

四、通過yaml檔案建立
思考:在建立yaml檔案的時候,為了避免能直接看到我們儲存的資料,所以,我們通常為會儲存的資料,進行加密。

[root@master secret]# echo root |base64
cm9vdAo=
[root@master secret]# echo 123.com | base64
MTIzLmNvbQo=
[root@master secret]# vim base.yaml
 
apiVersion: v1
kind: Secret
metadata:
  name: mysecret4
data:
  username: cm9vdAo=
  password: MTIzLmNvbQo=
  
[root@master secret]# kubectl apply -f base.yaml 
secret/mysecret4 created
[root@master secret]# kubectl get secrets 
NAME                  TYPE                                  DATA   AGE
default-token-vnwn4   kubernetes.io/service-account-token   3      5d21h
mysecret1             Opaque                                2      13m
mysecret2             Opaque                                2      6m59s
mysecret3             Opaque                                2      4m56s
mysecret4             Opaque                                2      91s

PS:即使,在儲存資料前,我們對要儲存的資料做了加密處理,但,base64這種方法也不是絕對的安全,比如上邊我們用base64這種方法得到的亂碼字串,就可以使用–decode解碼

[root@master secret]# echo -n cm9vdAo= | base64 --decode
root
[root@master secret]# echo -n MTIzLmNvbQo= | base64 --decode
123.com

Secret資源的使用

1、Volume
舉例:建立一個Pod資源,用volume的方式使用mysecret1.

[root@master secret]# vim volume.yaml 

kind: Pod
apiVersion: v1
metadata:
  name: mypod
spec:
  containers:
  - name: mypod
    image: busybox
    args:
      - /bin/sh
      - -c
      - sleep 30000
    volumeMounts:
    - name: test-volume
      mountPath: "/etc/volume"
      readOnly: true
  volumes:
  - name: test-volume
    secret:
      secretName: mysecret1
[root@master secret]# kubectl apply -f volume.yaml 
pod/mypod created

//通過yalm檔案,執行此Pod資源,然後進入Pod對應的掛載目錄,去驗證是否有我們的secret資源儲存的資料。

[root@master secret]# kubectl get pod
NAME    READY   STATUS    RESTARTS   AGE
mypod   1/1     Running   0          2m57s
[root@master secret]# kubectl exec -it mypod bash
OCI runtime exec failed: exec failed: container_linux.go:349: starting container process caused "exec: \"bash\": executable file not found in $PATH": unknown
command terminated with exit code 126
[root@master secret]# kubectl exec -it mypod sh
/ # cd /etc/volume/
/etc/volume # ls
password  username
/etc/volume # cat username
root 
/etc/volume # cat password 
123.com

PS: 以volume的掛載方式去使用secret資源,它會隨著secret資源物件資料的改變而改變。所以,通常用volume掛載的時候,為了保證secret資源的安全,在掛載的使用都是隻讀掛載(readOnly)

//我們也可以自安定存放資料的檔名,比如上述Pod資源,可以更改為:

kind: Pod
apiVersion: v1
metadata:
  name: mypod
spec:
  containers:
  - name: mypod
    image: busybox
    args:
      - /bin/sh
      - -c
      - sleep 30000
    volumeMounts:
    - name: test-volume
      mountPath: "/etc/volume"
      readOnly: true
  volumes:
  - name: test-volume
    secret:
      secretName: mysecret1
      items:
      - key: username
        path: mygroup/my-username
      - key: password
        path: mygroup/my-password

//在對應的位置,仍然可以檢視到我們更改過後的資料。資料會實時同步、更新.

[root@master secret]# kubectl exec -it mypod sh
/ # cd /etc/volume/
/etc/volume # ls
mygroup
/etc/volume # ls mygroup/
my-password  my-username

2、用環境變數的方式
同樣,我們更改一下上述的Pod,將它引用secret資源物件的方式更改為環境變數的方式:


kind: Pod
apiVersion: v1
metadata:
  name: mypod
spec:
  containers:
  - name: mypod
    image: busybox
    args:
      - /bin/sh
      - -c
      - sleep 30000
    env:
      - name: SECRET_USERNAME
        valueFrom:
          secretKeyRef:
            name: mysecret1
            key:  username
      - name: SECRET_PASSWORD
        valueFrom:
          secretKeyRef:
            name: mysecret1
            key: password
[root@master secret]# kubectl apply -f volume.yaml 
pod/mypod created

/執行此yaml檔案,並進入Pod去驗證一下變數的值是否正確。

[root@master secret]# kubectl get pod
NAME    READY   STATUS    RESTARTS   AGE
mypod   1/1     Running   0          83s
[root@master secret]# kubectl exec -it mypod sh
/ # echo $SECRET_USERNAME
root
/ # echo $SECRET_PASSWORD
123.com

//我們發現,用環境變數的方式也可以正確引用secret資源,但是,它並不會像Volume的方式一樣,它引用資料不會進行動態的更新。

小的技巧:資源在建立的過程中,可以直接使用命令的方式創,也可以使用yaml檔案的方式,雖然yaml檔案的方式建立,相對比較麻煩,但是,它會將我們在建立對應資源的時候的基本狀態做一個儲存。

我們可以先使用命令的方式建立出來對應的資源,然後將此資源另存為一個yaml檔案。比如我們剛剛建立的mysecret2:

[root@master secret]# kubectl get secrets mysecret2 -o yaml > mysecret2.yaml
[root@master secret]# cat mysecret2.yaml 
apiVersion: v1
data:
  password: MTIzLmNvbQo=
  username: cm9vdAo=
kind: Secret
metadata:
  creationTimestamp: "2020-11-09T07:49:43Z"
  name: mysecret2
  namespace: default
  resourceVersion: "5047"
  selfLink: /api/v1/namespaces/default/secrets/mysecret2
  uid: 51d64fa7-0db9-42f5-ad12-9fa6910841aa
type: Opaque

Secret實踐k8s連線Harbor
假設此時有一個deployment需要用到私有映象,已知 Harbor地址為:192.168.1.131,首先應該確認各節點都修改了/usr/lib/systemd/system/docker.service檔案,或者在/etc/docker/daemon.json檔案中新增過私有倉庫地址。因為登入Harbor需要使用者名稱和密碼,所以我們可以先建立一個Secret檔案,將Harbor的信心進行儲存到k8s叢集中。

1.先登入Harbor倉庫:

[root@master ~]# vim /usr/lib/systemd/system/docker.service
ExecStart=/usr/bin/dockerd --insecure-registry 192.168.1.23
[root@master ~]# systemctl daemon-reload
[root@master ~]# systemctl restart docker
[root@node1 ~]# vim /usr/lib/systemd/system/docker.service
[root@node1 ~]# systemctl daemon-reload
[root@node1 ~]# systemctl restart docker.service
[root@node2 ~]# vim /usr/lib/systemd/system/docker.service
[root@node2 ~]# systemctl daemon-reload
[root@node2 ~]# systemctl restart docker
[root@harbor harbor]# docker-compose restart
Restarting nginx              ... done
Restarting harbor-portal      ... done
Restarting harbor-jobservice  ... done
Restarting harbor-core        ... done
Restarting harbor-adminserver ... done
Restarting registryctl        ... done
Restarting registry           ... done
Restarting harbor-db          ... done
Restarting redis              ... done
Restarting harbor-log         ... done
[root@master ~]# docker login -u admin -p Harbor12345 192.168.1.23
WARNING! Using --password via the CLI is insecure. Use --password-stdin.
WARNING! Your password will be stored unencrypted in /root/.docker/config.json.
Configure a credential helper to remove this warning. See
https://docs.docker.com/engine/reference/commandline/login/#credentials-store

Login Succeeded

2.檢視登入祕鑰資料:

[root@master ~]# cat .docker/config.json
{
	"auths": {
		"192.168.1.23": {
			"auth": "YWRtaW46SGFyYm9yMTIzNDU="
		}
	},
	"HttpHeaders": {
		"User-Agent": "Docker-Client/18.09.0 (linux)"
	}
}

3.進行加密:

[root@master ~]# cat .docker/config.json | base64
ewoJImF1dGhzIjogewoJCSIxOTIuMTY4LjIyOS4yMTQiOiB7CgkJCSJhdXRoIjogIllXUnRhVzQ2U0dGeVltOXlNVEl6TkRVPSIKCQl9Cgl9LAoJIkh0dHBIZWFkZXJzIjogewoJCSJVc2VyLUFnZW50IjogIkRvY2tlci1DbGllbnQvMTguMDkuMCAobGludXgpIgoJfQp9

4.建立secret資源:

[root@master ~]# mkdir secret
[root@master ~]# cd secret/
[root@master secret]# vim secret.yaml
apiVersion: v1
kind: Secret
metadata:
  name: harbor-secret
type: kubernetes.io/dockerconfigjson
data:
  .dockerconfigjson: ewoJImF1dGhzIjogewoJCSIxOTIuMTY4LjIyOS4yMTQiOiB7CgkJCSJhdXRoIjogIllXUnRhVzQ2U0dGeVltOXlNVEl6TkRVPSIKCQl9Cgl9LAoJIkh0dHBIZWFkZXJzIjogewoJCSJVc2VyLUFnZW50IjogIkRvY2tlci1DbGllbnQvMTguMDkuMCAobGludXgpIgoJfQp9
[root@master secret]# kubectl apply -f secret.yaml

5.建立Deployment資源引用secret資源:

[root@master secret]# vim deploy.yaml
kind: Deployment
apiVersion: extensions/v1beta1
metadata:
  name: test
spec:
  replicas: 2
  template:
    metadata:
      labels:
        test: registry
    spec:
      containers:
      - name: test
        image: 192.168.1.23/test/httpd:v1
        imagePullPolicy: Always
      imagePullSecrets:
      - name: harbor-secret
[root@master secret]# kubectl apply -f deploy.yaml
[root@master secret]# kubectl get pod
NAME                    READY   STATUS    RESTARTS   AGE
test-6d9c69c9f8-7nvlv   1/1     Running   0          42s
test-6d9c69c9f8-sc7w4   1/1     Running   0          42s

ConfigMap

與secret資源一樣,configMap也可以儲存一些資料資訊,不同的是,secret資源儲存的是相對敏感的資訊或者是祕鑰等,而configMap儲存的是一些明文的資料。
舉例:
user1=admin
user2=root

一、–from-literal

[root@master ~]# kubectl create configmap myconfigmap1 --from-literal=user1=admin --from-literal=user2=root
configmap/myconfigmap1 created
[root@master ~]# kubectl describe configmaps myconfigmap1 
Name:         myconfigmap1
Namespace:    default
Labels:       <none>
Annotations:  <none>

Data
====
user1:
----
admin
user2:
----
root
Events:  <none>
[root@master ~]# kubectl get configmaps 
NAME           DATA   AGE
myconfigmap1   2      2m22s

二、–from-file

[root@master ~]# echo admin > user1
[root@master ~]# echo root > user2
[root@master ~]# kubectl create configmap myconfigmap2 --from-file=user1  --from-file=user2
configmap/myconfigmap2 created
[root@master ~]# kubectl describe configmaps myconfigmap2
Name:         myconfigmap2
Namespace:    default
Labels:       <none>
Annotations:  <none>

Data
====
user2:
----
root

user1:
----
admin

Events:  <none>
[root@master ~]# kubectl get configmaps 
NAME           DATA   AGE
myconfigmap1   2      2m22s
myconfigmap2   2      52s

三、–from-env-file

[root@master ~]# cat > user.txt <<EOF
> user1=admin
> user2=root
> EOF
[root@master ~]# kubectl create configmap myconfigmap3 --from-env-file=user.txt
configmap/myconfigmap3 created
[root@master ~]# kubectl describe configmaps myconfigmap3
Name:         myconfigmap3
Namespace:    default
Labels:       <none>
Annotations:  <none>

Data
====
user1:
----
admin
user2:
----
root
Events:  <none>
[root@master ~]# kubectl get configmaps 
NAME           DATA   AGE
myconfigmap1   2      4m40s
myconfigmap2   2      3m10s
myconfigmap3   2      27s

四、通過yaml檔案的方式

[root@master ~]# vim configmap.yaml

kind: ConfigMap
apiVersion: v1
metadata:
  name: myconfigmap4
data:
  user1: admin
  user2: root
[root@master ~]# kubectl apply -f configmap.yaml 
configmap/myconfigmap4 created
[root@master ~]# kubectl get configmaps 
NAME           DATA   AGE
myconfigmap1   2      6m31s
myconfigmap2   2      5m1s
myconfigmap3   2      2m18s
myconfigmap4   2      5s

ConfigMap資源的使用
舉例:建立一個Pod資源,引用上述myconfigmap1資源

1、Volume

[root@master ~]# vim pod1.yaml

kind: Pod
apiVersion: v1
metadata:
  name: mypod3
spec:
  containers:
  - name: mypod3
    image: busybox
    args:
      - /bin/sh
      - -c
      - sleep 30000
    volumeMounts:
    - name: volume2
      mountPath: "/tmp/volume"
      readOnly: true
  volumes:
  - name: volume2
    configMap:
      name: myconfigmap1
[root@master ~]# kubectl apply -f pod1.yaml 
pod/mypod3 created

/建立並執行Pod資源,進入Pod檢視驗證儲存的資訊


[root@master ~]# kubectl get pod
NAME     READY   STATUS    RESTARTS   AGE
mypod3   1/1     Running   0          54s
[root@master ~]# kubectl exec -it mypod3 sh
/ # cat /tmp/volume/user1
admin
/ # cat /tmp/volume/user2
root

/這裡假如我們將myconfigmap1對應的user1的值進行更改,會看到Pod內對應的值也會進行動態的更新

[root@master ~]# kubectl edit configmaps myconfigmap1
...
apiVersion: v1
data:
  user1: test
  user2: root
kind: ConfigMap
...
[root@master ~]# kubectl exec -it mypod3 sh
/ # cat /tmp/volume/user1 
test

2、環境變數

[root@master ~]# vim pod2.yaml

kind: Pod
apiVersion: v1
metadata:
  name: pod2
spec:
  containers:
  - name: pod2
    image: busybox
    args:
    - /bin/sh
    - -c
    - sleep 30000
    env:
    - name: USER_1
      valueFrom:
        configMapKeyRef:
          name: myconfigmap1
          key: user1
    - name: USER_2
      valueFrom:
        configMapKeyRef:
          name: myconfigmap1
          key: user2
[root@master ~]# kubectl apply -f pod2.yaml 
pod/pod2 created

//建立並執行Pod,進入Pod驗證環境變數對應的值

[root@master ~]# kubectl get pod
NAME     READY   STATUS    RESTARTS   AGE
mypod3   1/1     Running   0          25m
mypod4   1/1     Running   0          43s
[root@master ~]# kubectl exec -it mypod4 sh
/ # echo $USER_1
test
/ # echo $USER_2
root

//這裡假如再講user1對應的更改為admin,再次驗證Pod內的變數值仍然不會變,說明環境變數的方式不倫引用的什麼資源,都不會動態的更新。

相關文章