容器編排系統K8s之ConfigMap、Secret資源

1874發表於2020-12-27

  前文我們瞭解了k8s上的pv/pvc/sc資源的使用和相關說明,回顧請參考:https://www.cnblogs.com/qiuhom-1874/p/14188621.html;今天我們主要來聊一下k8s上配置應用相關話題;

  在說configmap和secret資源之前,我們先來回顧下在docker環境下怎麼給容器提供配置資訊;在docker容器裡我們要給容器裡的應用提供配置的方式有兩種,一種是通過環境變數的方式,把對應容器裡跑的程式的某些屬性通過一個環境變數傳遞給容器執行時的環境中去,這樣容器啟動時,讀取對應的環境變數,對應容器裡的應用程式就會根據我們傳遞的環境變數來啟動對應的程式,從而實現配置容器裡應用程式的目的;這種能夠通過環境變數向容器裡的應用傳遞配置的前提是對應應用程式支援;第二種方式就是通過儲存卷的方式,把外部的配置檔案直接通過儲存卷的方式掛載到容器裡的應用程式對應位置,對應程式在啟動時,通過讀取掛載的配置檔案,從而實現配置容器裡的應用程式的目的;這兩種方式都有一個特點,只能在初始化容器時做,一旦一個容器初始化完成以後,修改對應的配置,必須要重新初始化容器,對應配置才能生效;對於k8s上的pod來說,也是類似的邏輯;第一通過環境變數的方式,第二通過儲存卷的方式;不同於docker容器,在k8s上一切皆物件,我們需要把對應的配置資訊通過對應資源初始化為一個物件,然後通過pod呼叫對應的物件,從而實現向pod裡的容器提供配置,這種能夠把配置資訊初始化為一個物件並被pod所呼叫的資源有兩個,分別是configmap和secret;configmap和secret資源都是用來向pod提供配置資訊的資源,兩者用法都很相似,唯一不同的是configmap主要用於提供非敏感配置的資源,secret主要用來提供敏感配置的資源;簡單講就是configmap不加密,secret要對敏感配置做加密處理(嚴格上不叫加密,它是把對應敏感資料做base64編碼處理);

  configmap資源物件的建立和使用

  configmap是k8s上的一個標準資源,我們可以通過命令的方式來建立,也可以通過定義資源清單的方式來建立;

  configmap通過create命令來建立的語法格式

Usage:
  kubectl create configmap NAME [--from-file=[key=]source] [--from-literal=key1=value1]
[--dry-run=server|client|none] [options]

  提示:configmap物件的建立主要指定對應configmap物件的名稱,以及把對應配置資訊傳遞給對應物件;configmap物件支援從命令列直接獲取使用者給定的kv配置資訊,也支援通過讀取一個配置檔案的內容來獲取對應配置;--from-file選項表示,對應配置資訊從檔案獲取,預設我們直接指定一個配置檔案的檔名稱,它會把檔案的基名(不包含路徑名稱)當作對應配置資訊的key,把檔案內容當作對應key的值;--from-literal選項表示,對應配置資訊從使用者在命令給定的key和value獲取;

  示例:通過命令的方式建立configmap資源物件,並在命令列向其傳遞kv配置;

[root@master01 ~]# kubectl create cm configmap-demo --from-literal=key1=value1 --from-literal=key2=value2
configmap/configmap-demo created
[root@master01 ~]# kubectl get cm
NAME               DATA   AGE
configmap-demo     2      8s
kube-root-ca.crt   1      4d2h
[root@master01 ~]# kubectl describe cm configmap-demo
Name:         configmap-demo
Namespace:    default
Labels:       <none>
Annotations:  <none>

Data
====
key1:
----
value1
key2:
----
value2
Events:  <none>
[root@master01 ~]# 

  提示:configmap可以簡寫為cm;--from-literal選項可以多次使用,每次指定一個配置項;從上面的顯示看,對應configmap-demo這個物件儲存了兩個配置,分別是key1=value1、key2=value2;

  定義pod應用configmap物件

[root@master01 ~]# cat nginx-demo.yaml
apiVersion: v1
kind: Pod
metadata:
  name: nginx-demo
  namespace: default
  labels:
    app: nginx
    rel: stable
spec:
  containers: 
  - name: nginx-demo
    image: nginx:1.14-alpine
    env:
    - name: FIRST_KEY
      valueFrom:
        configMapKeyRef:
          name: configmap-demo
          key: key1
    - name: SECOND_KEY
      valueFrom: 
        configMapKeyRef:
          name: configmap-demo
          key: key2
[root@master01 ~]# 

  提示:以上配置清單主要在nginx-demo容器裡通過configmap向對應容器的執行環境傳遞兩個環境變數;FIRST_KEY這個環境變數的值對應configmap物件裡儲存的key1這個鍵的值;SECOND_KEY這個環境變數的值對應configmap物件裡的key2這個鍵的值;

  應用資源清單

[root@master01 ~]# kubectl apply -f nginx-demo.yaml
pod/nginx-demo created
[root@master01 ~]# kubectl get pods
NAME         READY   STATUS              RESTARTS   AGE
nginx-demo   0/1     ContainerCreating   0          8s
[root@master01 ~]# kubectl get pods -w
NAME         READY   STATUS              RESTARTS   AGE
nginx-demo   0/1     ContainerCreating   0          17s
nginx-demo   1/1     Running             0          17s
^C[root@master01 ~]# kubectl describe pod nginx-demo
Name:         nginx-demo
Namespace:    default
Priority:     0
Node:         node03.k8s.org/172.16.11.6
Start Time:   Sat, 26 Dec 2020 22:28:10 +0800
Labels:       app=nginx
              rel=stable
Annotations:  <none>
Status:       Running
IP:           10.244.3.8
IPs:
  IP:  10.244.3.8
Containers:
  nginx-demo:
    Container ID:   docker://63cf5421b597f9dcd1169193c248091c62183ba18ec565122e242a53045d3112
    Image:          nginx:1.14-alpine
    Image ID:       docker-pullable://nginx@sha256:485b610fefec7ff6c463ced9623314a04ed67e3945b9c08d7e53a47f6d108dc7
    Port:           <none>
    Host Port:      <none>
    State:          Running
      Started:      Sat, 26 Dec 2020 22:28:26 +0800
    Ready:          True
    Restart Count:  0
    Environment:
      FIRST_KEY:   <set to the key 'key1' of config map 'configmap-demo'>  Optional: false
      SECOND_KEY:  <set to the key 'key2' of config map 'configmap-demo'>  Optional: false
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-8qs4l (ro)
Conditions:
  Type              Status
  Initialized       True 
  Ready             True 
  ContainersReady   True 
  PodScheduled      True 
Volumes:
  default-token-8qs4l:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  default-token-8qs4l
    Optional:    false
QoS Class:       BestEffort
Node-Selectors:  <none>
Tolerations:     node.kubernetes.io/not-ready:NoExecute op=Exists for 300s
                 node.kubernetes.io/unreachable:NoExecute op=Exists for 300s
Events:
  Type    Reason     Age   From               Message
  ----    ------     ----  ----               -------
  Normal  Scheduled  35s   default-scheduler  Successfully assigned default/nginx-demo to node03.k8s.org
  Normal  Pulling    32s   kubelet            Pulling image "nginx:1.14-alpine"
  Normal  Pulled     20s   kubelet            Successfully pulled image "nginx:1.14-alpine" in 12.059556374s
  Normal  Created    20s   kubelet            Created container nginx-demo
  Normal  Started    19s   kubelet            Started container nginx-demo
[root@master01 ~]# 

  提示:從上面pod的詳細資訊可以看到在對應Environment欄位下多了兩個環境變數,分別是FIRST_KEY和SECOND_KEY;

  驗證:進入對應pod,看看環境變數是否有FIRST_KEY和SECOND_KEY,對應值是否是configmap物件中的值

  提示:可以看到在對應pod的環境變數中有我們傳遞的兩個環境變數,對應的值也是我們在configmap物件中定義的值;

  示例:通過命令的方式建立configmap資源物件,並通過配置檔案向其傳遞配置資訊;

  準備配置檔案

[root@master01 ~]# cat www-k8s-org.conf
server {
        server_name www.k8s.org;
        listen 80;
        location / {
            root "/www/html";
        }
}
[root@master01 ~]# cat bbs-k8s-org.conf
server {
        server_name bbs.k8s.org;
        listen 80;
        location / {
            root "/bbs/html";
        }
}
[root@master01 ~]# 

  建立configmap物件,並把上面兩個配置檔案資訊傳遞給configmap物件

[root@master01 ~]# kubectl create cm nginx-conf --from-file=./www-k8s-org.conf --from-file=bbs-conf=./bbs-k8s-org.conf
configmap/nginx-conf created
[root@master01 ~]# kubectl get cm
NAME               DATA   AGE
configmap-demo     2      47m
kube-root-ca.crt   1      4d2h
nginx-conf         2      11s
[root@master01 ~]# kubectl describe cm nginx-conf
Name:         nginx-conf
Namespace:    default
Labels:       <none>
Annotations:  <none>

Data
====
bbs-conf:
----
server {
  server_name bbs.k8s.org;
        listen 80;
        location / {
          root "/bbs/html";
      }
}

www-k8s-org.conf:
----
server {
  server_name www.k8s.org;
        listen 80;
        location / {
          root "/www/html";
      }
}

Events:  <none>
[root@master01 ~]# 

  提示:可以看到cm物件建立成功,並且成功把對應的配置檔案內容當作對應key傳遞給cm物件了;在建立cm物件時,要使用--from-file選項來指定從檔案載入配置資訊,如果只指定了檔名,則以檔案基名作為對應key,其檔案內容作為對應key的值;

  定義pod掛載configmap物件中的配置檔案資訊

[root@master01 ~]# cat nginx-demo2.yaml
apiVersion: v1
kind: Pod
metadata:
  name: nginx-demo2
  namespace: default
  labels:
    app: nginx
    rel: stable
spec:
  containers: 
  - name: nginx-demo
    image: nginx:1.14-alpine
    volumeMounts:
    - name: website-conf
      mountPath: /etc/nginx/conf.d/
  volumes:
  - name: website-conf
    configMap:
      name: nginx-conf
      items:
      - key: www-k8s-org.conf
        path: www-k8s-org.conf
        mode: 0644 
      - key: bbs-conf
        path: bbs-k8s-org.conf
        mode: 0644
[root@master01 ~]# 

  提示:以上配置資訊表示把configmap物件中的兩個配置資訊,都以檔案的方式掛載到/etc/nginx/conf.d/目錄下;configmap型別儲存卷它會把configmap中的物件以檔案的形式掛載到對應pod;其中spec.volumes.configMap.items.key欄位用於指定configmap物件中的key;path用於指定把對應的key對映的檔名稱;mode是用於指定對應檔案的許可權資訊;

  應用配置清單

[root@master01 ~]# kubectl apply -f nginx-demo2.yaml
pod/nginx-demo2 created
[root@master01 ~]# kubectl get pods -w
NAME          READY   STATUS    RESTARTS   AGE
nginx-demo    1/1     Running   0          47m
nginx-demo2   1/1     Running   0          8s
^C[root@master01 ~]# kubectl describe pod nginx-demo2
Name:         nginx-demo2
Namespace:    default
Priority:     0
Node:         node02.k8s.org/172.16.11.5
Start Time:   Sat, 26 Dec 2020 23:15:29 +0800
Labels:       app=nginx
              rel=stable
Annotations:  <none>
Status:       Running
IP:           10.244.2.8
IPs:
  IP:  10.244.2.8
Containers:
  nginx-demo:
    Container ID:   docker://38781957cabf78616c7d826664009c215d3ef7105955e722e5e0104eca636ab0
    Image:          nginx:1.14-alpine
    Image ID:       docker-pullable://nginx@sha256:485b610fefec7ff6c463ced9623314a04ed67e3945b9c08d7e53a47f6d108dc7
    Port:           <none>
    Host Port:      <none>
    State:          Running
      Started:      Sat, 26 Dec 2020 23:15:34 +0800
    Ready:          True
    Restart Count:  0
    Environment:    <none>
    Mounts:
      /etc/nginx/conf.d/ from website-conf (rw)
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-8qs4l (ro)
Conditions:
  Type              Status
  Initialized       True 
  Ready             True 
  ContainersReady   True 
  PodScheduled      True 
Volumes:
  website-conf:
    Type:      ConfigMap (a volume populated by a ConfigMap)
    Name:      nginx-conf
    Optional:  false
  default-token-8qs4l:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  default-token-8qs4l
    Optional:    false
QoS Class:       BestEffort
Node-Selectors:  <none>
Tolerations:     node.kubernetes.io/not-ready:NoExecute op=Exists for 300s
                 node.kubernetes.io/unreachable:NoExecute op=Exists for 300s
Events:
  Type    Reason     Age   From               Message
  ----    ------     ----  ----               -------
  Normal  Scheduled  21s   default-scheduler  Successfully assigned default/nginx-demo2 to node02.k8s.org
  Normal  Pulled     18s   kubelet            Container image "nginx:1.14-alpine" already present on machine
  Normal  Created    18s   kubelet            Created container nginx-demo
  Normal  Started    17s   kubelet            Started container nginx-demo
[root@master01 ~]# 

  進入nginx-demo2容器,看看對應/etc/nginx/conf.d/目錄下是否有兩個我們指定的配置檔案?對應檔案內容是否是cm物件中對應key的內容?

[root@master01 ~]# kubectl exec -it nginx-demo2 -- /bin/sh
/ # cd /etc/nginx/conf.d/
/etc/nginx/conf.d # ls 
bbs-k8s-org.conf  www-k8s-org.conf
/etc/nginx/conf.d # cat www-k8s-org.conf 
server {
        server_name www.k8s.org;
        listen 80;
        location / {
            root "/www/html";
        }
}
/etc/nginx/conf.d # cat bbs-k8s-org.conf 
server {
        server_name bbs.k8s.org;
        listen 80;
        location / {
            root "/bbs/html";
        }
}
/etc/nginx/conf.d # 

  提示:可以看到在對應pod容器裡,在/etc/nginx/conf.d/目錄下有兩個配置檔案,這兩個配置檔案就是我們定義pod時掛載configmap儲存卷定義的檔名稱;對應檔案內容也是cm物件中儲存的檔案內容;

  測試:修改對應cm資源的配置資訊,看看對應引用了該cm資源物件的pod是否會更新配置資訊?

  提示:線上修改cm物件配置資訊,可以使用edit命令來修改指定cm物件即可;修改完成後儲存退出對應配置就會立即更新到cm物件;以上主要修改了bbs-conf鍵中的listen 80修改為8080;

  驗證:檢視對應cm物件,看看配置資訊是否更新?

  提示:可以看到對應cm物件中的配置資訊已經被更新;

  驗證:看看對應引用該cm物件中的配置資訊的pod是否更新了配置?是否過載了對應配置?

  提示:對應pod配置檔案資訊已經更新,但是並沒有應用新配置;像這種情況我們還得自己手動進入到對應的容器裡過載配置;

  示例:使用配置清單建立cm物件

[root@master01 ~]# cat configmap-demo.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: test-cm-demo
  namespace: default
data:
  website-conf: |
    server {
        server_name bbs.k8s.org;
        listen 80;
        location / {
            root "/bbs/html";
        }
    }
[root@master01 ~]# 

  提示:cm物件在沒有spec欄位,卻而代之的是data欄位,該欄位主要用來定義對應kv配置資訊;key可以是任意合法名稱,對應的值可以是一個檔案內容;如果對應內容需要多行來書寫,需要在對應的key後面加上 “|”;

  應用配置清單

[root@master01 ~]# kubectl apply -f configmap-demo.yaml
configmap/test-cm-demo created
[root@master01 ~]# kubectl get cm
NAME               DATA   AGE
configmap-demo     2      82m
kube-root-ca.crt   1      4d3h
nginx-conf         2      35m
test-cm-demo       1      5s
[root@master01 ~]# kubectl describe cm test-cm-demo
Name:         test-cm-demo
Namespace:    default
Labels:       <none>
Annotations:  <none>

Data
====
website-conf:
----
server {
    server_name bbs.k8s.org;
    listen 80;
    location / {
        root "/bbs/html";
    }
}

Events:  <none>
[root@master01 ~]# 

  提示:可以看到對應的cm物件已經成功被建立,並且裡面儲存了我們在定義cm時的配置資訊;

  Secret資源的建立和使用

  secret資源和configmap資源的用法都很類似,可以在命令列中通過create命令來建立,也可以通過定義資源清單來建立,其使用方式和configmap也很類似;

  secret資源通過create命令來建立的語法格式

[root@master01 ~]# kubectl create secret
Create a secret using specified subcommand.

Available Commands:
  docker-registry Create a secret for use with a Docker registry
  generic         Create a secret from a local file, directory or literal value
  tls             Create a TLS secret

Usage:
  kubectl create secret [flags] [options]

Use "kubectl <command> --help" for more information about a given command.
Use "kubectl options" for a list of global command-line options (applies to all commands).
[root@master01 ~]# 

  提示:secret資源有三種型別,分別是docker-registry、generis、tls;其中docker-registry型別主要用來建立儲存私有映象倉庫中需要用到的認證資訊,比如使用者名稱稱,使用者密碼,倉庫地址,使用者郵件資訊等等;generis型別是比較通用的一種型別,它可以從一個檔案中載入資訊,也可以從命令列中獲取對應的kv配置資訊;tls型別主要用來儲存證照相關的證照,私鑰;在前邊我們使用ingress資源時,在應用對應的證照和私鑰時,就是通過tls型別的secret資源物件來向其ingress資源物件傳遞證照和私鑰檔案資訊;

  建立docker-registry型別的secret資源的語法格式

Usage:
  kubectl create secret docker-registry NAME --docker-username=user --docker-password=password --docker-email=email
[--docker-server=string] [--from-literal=key1=value1] [--dry-run=server|client|none] [options]

  示例:使用create命令來建立一個docker-registry型別的secret資源物件

[root@master01 ~]# kubectl create secret docker-registry docker-registry.io --docker-username=qiuhom --docker-password=Admin123.com --docker-server=docker-registry.io
secret/docker-registry.io created
[root@master01 ~]# kubectl get secret
NAME                           TYPE                                  DATA   AGE
default-token-xvd4c            kubernetes.io/service-account-token   3      18d
docker-registry.io             kubernetes.io/dockerconfigjson        1      15s
www-myapp-com-ingress-secret   kubernetes.io/tls                     2      4d22h
[root@master01 ~]# kubectl describe secret docker-registry.io
Name:         docker-registry.io
Namespace:    default
Labels:       <none>
Annotations:  <none>

Type:  kubernetes.io/dockerconfigjson

Data
====
.dockerconfigjson:  118 bytes
[root@master01 ~]# kubectl get secret docker-registry.io -o yaml
apiVersion: v1
data:
  .dockerconfigjson: eyJhdXRocyI6eyJkb2NrZXItcmVnaXN0cnkuaW8iOnsidXNlcm5hbWUiOiJxaXVob20iLCJwYXNzd29yZCI6IkFkbWluMTIzLmNvbSIsImF1dGgiOiJjV2wxYUc5dE9rRmtiV2x1TVRJekxtTnZiUT09In19fQ==
kind: Secret
metadata:
  creationTimestamp: "2020-12-26T16:40:56Z"
  managedFields:
  - apiVersion: v1
    fieldsType: FieldsV1
    fieldsV1:
      f:data:
        .: {}
        f:.dockerconfigjson: {}
      f:type: {}
    manager: kubectl-create
    operation: Update
    time: "2020-12-26T16:40:56Z"
  name: docker-registry.io
  namespace: default
  resourceVersion: "392306"
  uid: ac9e425f-95e7-4c34-b161-c621ad2b0a8a
type: kubernetes.io/dockerconfigjson
[root@master01 ~]# 

  提示:從上面對應secret資源物件中輸出為yaml格式的配置中可以看到,對應data欄位輸出的是一個base64編碼後的字串;其實裡面的內容就是我們建立secret資源物件時指定的內容;如下

[root@master01 ~]#  echo  eyJhdXRocyI6eyJkb2NrZXItcmVnaXN0cnkuaW8iOnsidXNlcm5hbWUiOiJxaXVob20iLCJwYXNzd29yZCI6IkFkbWluMTIzLmNvbSIsImF1dGgiOiJjV2wxYUc5dE9rRmtiV2x1TVRJekxtTnZiUT09In19fQ== |base64 -d
{"auths":{"docker-registry.io":{"username":"qiuhom","password":"Admin123.com","auth":"cWl1aG9tOkFkbWluMTIzLmNvbQ=="}}}[root@master01 ~]# 
[root@master01 ~]# echo cWl1aG9tOkFkbWluMTIzLmNvbQ== |base64 -d
qiuhom:Admin123.com[root@master01 ~]# 
[root@master01 ~]# 

  提示:可以看到所有把對應字串交給base64解密後,拿到的就是我們在建立docker-registry型別的secret資源物件傳遞的選項;

  定義pod資源引用docker-registry型別的secret資源物件

[root@master01 ~]# cat test-pod-demo.yaml
apiVersion: v1
kind: Pod
metadata:
  name: test-nginx
  namespace: default
  labels:
    app: nginx
spec:
  imagePullSecrets:
  - name: docker-registry.io
  containers:
  - name: nginx
    image: docker-registry.io/test/nginx:latest
[root@master01 ~]# 

  提示:在定義pod時,如果要從對應私有映象倉庫中拉去映象,需要用到認證資訊,可以使用imagePullSecrets欄位來應用對應的secret資源物件來傳遞倉庫的認證資訊;在應用配置清單之前,需要將所有節點的/etc/hosts檔案和/etc/docker/daemon.json檔案更新下;如果是私鑰映象倉庫預設docker會認為不安全,需要我們手動指定出來;如果對應域名在網際網路上無法正常解析,還需要藉助對應的hosts檔案將其解析到對應倉庫伺服器的地址上;如下

[root@master01 ~]# cat /etc/hosts
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
192.168.0.99 time.test.org time-node
192.168.0.41  master01 master01.k8s.org
192.168.0.42  master02 master02.k8s.org
192.168.0.43  master03 master03.k8s.org
192.168.0.44  node01 node01.k8s.org
192.168.0.45  node02 node02.k8s.org
192.168.0.46  node03 node03.k8s.org
192.168.0.47  node04 node04.k8s.org
199.232.28.133 raw.githubusercontent.com
192.168.0.99 docker-registry.io registry
[root@master01 ~]# cat /etc/docker/daemon.json 
{
"registry-mirrors": ["https://cyr1uljt.mirror.aliyuncs.com"],
"insecure-registries": ["docker-registry.io"]
}
[root@master01 ~]# scp /etc/docker/daemon.json node01:/etc/docker/
daemon.json                                                                                                100%  112    39.4KB/s   00:00    
[root@master01 ~]# scp /etc/docker/daemon.json node02:/etc/docker/
daemon.json                                                                                                100%  112    67.3KB/s   00:00    
[root@master01 ~]# scp /etc/docker/daemon.json node03:/etc/docker/
daemon.json                                                                                                100%  112     8.9KB/s   00:00    
[root@master01 ~]# scp /etc/docker/daemon.json node04:/etc/docker/
daemon.json                                                                                                100%  112    69.8KB/s   00:00    
[root@master01 ~]# scp /etc/hosts node01:/etc/
hosts                                                                                                      100%  541   477.4KB/s   00:00    
[root@master01 ~]# scp /etc/hosts node02:/etc/
hosts                                                                                                      100%  541   225.7KB/s   00:00    
[root@master01 ~]# scp /etc/hosts node03:/etc/
hosts                                                                                                      100%  541   217.3KB/s   00:00    
[root@master01 ~]# scp /etc/hosts node04:/etc/
hosts                                                                                                      100%  541   149.4KB/s   00:00    
[root@master01 ~]# ssh node01 'systemctl restart docker'
[root@master01 ~]# ssh node02 'systemctl restart docker' 
[root@master01 ~]# ssh node03 'systemctl restart docker' 
[root@master01 ~]# ssh node04 'systemctl restart docker' 

  提示:有關docker私有映象倉庫harbor的搭建過程可以參考本人部落格:https://www.cnblogs.com/qiuhom-1874/p/13061984.html

  應用配置清單,看看對應的pod是否能夠啟動成功?

[root@master01 ~]# kubectl apply -f test-pod-demo.yaml
pod/test-nginx created
[root@master01 ~]# kubectl get pods -w
NAME         READY   STATUS    RESTARTS   AGE
test-nginx   1/1     Running   0          6s
^C[root@master01 ~]# kubectl describe pod test-nginx
Name:         test-nginx
Namespace:    default
Priority:     0
Node:         node02.k8s.org/192.168.0.45
Start Time:   Sun, 27 Dec 2020 01:04:18 +0800
Labels:       app=nginx
Annotations:  <none>
Status:       Running
IP:           10.244.2.107
IPs:
  IP:  10.244.2.107
Containers:
  nginx:
    Container ID:   docker://9062506afc2fc002102754ee8b2205732ddb740f7f86b870131cb582fc3b9f52
    Image:          docker-registry.io/test/nginx:latest
    Image ID:       docker-pullable://docker-registry.io/test/nginx@sha256:0efad4d09a419dc6d574c3c3baacb804a530acd61d5eba72cb1f14e1f5ac0c8f
    Port:           <none>
    Host Port:      <none>
    State:          Running
      Started:      Sun, 27 Dec 2020 01:04:24 +0800
    Ready:          True
    Restart Count:  0
    Environment:    <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-xvd4c (ro)
Conditions:
  Type              Status
  Initialized       True 
  Ready             True 
  ContainersReady   True 
  PodScheduled      True 
Volumes:
  default-token-xvd4c:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  default-token-xvd4c
    Optional:    false
QoS Class:       BestEffort
Node-Selectors:  <none>
Tolerations:     node.kubernetes.io/not-ready:NoExecute op=Exists for 300s
                 node.kubernetes.io/unreachable:NoExecute op=Exists for 300s
Events:
  Type    Reason     Age   From               Message
  ----    ------     ----  ----               -------
  Normal  Scheduled  27s   default-scheduler  Successfully assigned default/test-nginx to node02.k8s.org
  Normal  Pulling    26s   kubelet            Pulling image "docker-registry.io/test/nginx:latest"
  Normal  Pulled     21s   kubelet            Successfully pulled image "docker-registry.io/test/nginx:latest" in 4.835022509s
  Normal  Created    21s   kubelet            Created container nginx
  Normal  Started    21s   kubelet            Started container nginx
[root@master01 ~]# 

  提示:可以看到對應pod能夠正常到指定的私鑰倉庫中把映象託下來,並啟動成功;

  使用create命令建立generic型別的secret資源物件語法格式

Usage:
  kubectl create secret generic NAME [--type=string] [--from-file=[key=]source] [--from-literal=key1=value1]
[--dry-run=server|client|none] [options]

  示例:使用create命令建立generic型別的secret資源物件

[root@master01 ~]# kubectl create secret generic mysql-auth --from-literal=username=root --from-literal=passwd=admin
secret/mysql-auth created
[root@master01 ~]# kubectl get secret
NAME                           TYPE                                  DATA   AGE
default-token-xvd4c            kubernetes.io/service-account-token   3      18d
docker-registry.io             kubernetes.io/dockerconfigjson        1      37m
mysql-auth                     Opaque                                2      13s
www-myapp-com-ingress-secret   kubernetes.io/tls                     2      4d23h
[root@master01 ~]# kubectl describe secret mysql-auth
Name:         mysql-auth
Namespace:    default
Labels:       <none>
Annotations:  <none>

Type:  Opaque

Data
====
passwd:    5 bytes
username:  4 bytes
[root@master01 ~]# kubectl get secret mysql-auth -o yaml
apiVersion: v1
data:
  passwd: YWRtaW4=
  username: cm9vdA==
kind: Secret
metadata:
  creationTimestamp: "2020-12-26T17:18:08Z"
  managedFields:
  - apiVersion: v1
    fieldsType: FieldsV1
    fieldsV1:
      f:data:
        .: {}
        f:passwd: {}
        f:username: {}
      f:type: {}
    manager: kubectl-create
    operation: Update
    time: "2020-12-26T17:18:08Z"
  name: mysql-auth
  namespace: default
  resourceVersion: "396175"
  uid: a22e27a8-b9f7-405a-b503-ac546da0b4cd
type: Opaque
[root@master01 ~]# 

  提示:generic型別的secret資源的建立和configmap很類似,它可以接受從命令列中使用者手動傳遞對應的配置資訊,也支援從配置檔案中獲取對應的配置資訊;

  建立pod資源,引用generic型別的secret型別的資源

[root@master01 ~]# cat mysql-demo.yaml
apiVersion: v1
kind: Pod
metadata:
  name: mysql-demo
  namespace: default
  labels:
    app: mysql
spec:
  containers:
  - name: mysql-demo
    image: mysql:5.6
    env:
    - name: MYSQL_ROOT_PASSWORD
      valueFrom:
        secretKeyRef:
          name: mysql-auth
          key: passwd
[root@master01 ~]# 

  提示:上述清單定義了執行一個pod,其內部跑一個mysql:5.6的容器;對應使用環境變數的方式向mysql-demo容器傳遞了一個MYSQL_ROOT_PASSWORD的環境變數,對應環境變數的值為generic型別的secret資源物件中的passwd這個鍵的值;

  應用配置清單

[root@master01 ~]# kubectl apply -f mysql-demo.yaml
pod/mysql-demo created
[root@master01 ~]# kubectl get pods -w
NAME         READY   STATUS              RESTARTS   AGE
mysql-demo   0/1     ContainerCreating   0          7s
test-nginx   1/1     Running             0          29m
mysql-demo   1/1     Running             0          32s
^C[root@master01 ~]# kubectl describe pod mysql-demo
Name:         mysql-demo
Namespace:    default
Priority:     0
Node:         node03.k8s.org/192.168.0.46
Start Time:   Sun, 27 Dec 2020 01:34:10 +0800
Labels:       app=mysql
Annotations:  <none>
Status:       Running
IP:           10.244.3.106
IPs:
  IP:  10.244.3.106
Containers:
  mysql-demo:
    Container ID:   docker://97d88917cbc8e304af120e83a859814248cd915da7d2056643b3f29f61c2cb7b
    Image:          mysql:5.6
    Image ID:       docker-pullable://mysql@sha256:51d59639d9a864ec302008c81d6909c532eff8b946993ef6448c086ba7917e82
    Port:           <none>
    Host Port:      <none>
    State:          Running
      Started:      Sun, 27 Dec 2020 01:34:42 +0800
    Ready:          True
    Restart Count:  0
    Environment:
      MYSQL_ROOT_PASSWORD:  <set to the key 'passwd' in secret 'mysql-auth'>  Optional: false
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-xvd4c (ro)
Conditions:
  Type              Status
  Initialized       True 
  Ready             True 
  ContainersReady   True 
  PodScheduled      True 
Volumes:
  default-token-xvd4c:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  default-token-xvd4c
    Optional:    false
QoS Class:       BestEffort
Node-Selectors:  <none>
Tolerations:     node.kubernetes.io/not-ready:NoExecute op=Exists for 300s
                 node.kubernetes.io/unreachable:NoExecute op=Exists for 300s
Events:
  Type    Reason     Age   From               Message
  ----    ------     ----  ----               -------
  Normal  Scheduled  50s   default-scheduler  Successfully assigned default/mysql-demo to node03.k8s.org
  Normal  Pulling    49s   kubelet            Pulling image "mysql:5.6"
  Normal  Pulled     18s   kubelet            Successfully pulled image "mysql:5.6" in 30.561208525s
  Normal  Created    18s   kubelet            Created container mysql-demo
  Normal  Started    18s   kubelet            Started container mysql-demo
[root@master01 ~]# 

  提示:可以看到對應容器已經正常處於running狀態,並在其詳細資訊中看到對應環境變數MYSQL_ROOT_PASSWORD引用secret中的passwd鍵;

  測試:進入mysql-demo的互動式介面,看看使用建立secret時使用的passwd鍵傳遞的密碼是否可以正常登入到mysql系統?

[root@master01 ~]# kubectl exec -it mysql-demo -- /bin/sh
# mysql
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)
# mysql -padmin
Warning: Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 2
Server version: 5.6.50 MySQL Community Server (GPL)

Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
+--------------------+
3 rows in set (0.00 sec)

mysql> exit
Bye
# 

  提示:可以看到直接在容器互動式介面直接不使用密碼是不能正常登入到mysql資料庫;使用正確的密碼後能夠正常進入mysql;其實我們在互動式介面上檢視環境變數也能檢視到對應的環境變數的資訊;如下

  使用create命令建立tls型別的secret資源物件語法格式

Usage:
  kubectl create secret tls NAME --cert=path/to/cert/file --key=path/to/key/file
[--dry-run=server|client|none] [options]

  示例:使用create命令建立tls型別的secret資源物件

[root@master01 manifests]# kubectl create secret tls test-tls --cert=./tls.crt --key=./tls.key
secret/test-tls created
[root@master01 manifests]# kubectl get secret
NAME                           TYPE                                  DATA   AGE
default-token-xvd4c            kubernetes.io/service-account-token   3      18d
docker-registry.io             kubernetes.io/dockerconfigjson        1      65m
mysql-auth                     Opaque                                2      28m
test-tls                       kubernetes.io/tls                     2      10s
www-myapp-com-ingress-secret   kubernetes.io/tls                     2      4d23h
[root@master01 manifests]# kubectl describe secret test-tls
Name:         test-tls
Namespace:    default
Labels:       <none>
Annotations:  <none>

Type:  kubernetes.io/tls

Data
====
tls.crt:  1285 bytes
tls.key:  1679 bytes
[root@master01 manifests]# kubectl get secret test-tls -o yaml
apiVersion: v1
data:
  tls.crt: LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSURoekNDQW0rZ0F3SUJBZ0lKQU4wS2RzTWpIMlNYTUEwR0NTcUdTSWIzRFFFQkN3VUFNRm94Q3pBSkJnTlYKQkFZVEFrTk9NUkF3RGdZRFZRUUlEQWRUYVVOb2RXRnVNUkl3RUFZRFZRUUhEQWxIZFdGdVoxbDFZVzR4RFRBTApCZ05WQkFvTUJGUmxjM1F4RmpBVUJnTlZCQU1NRFhkM2R5NXRlV0Z3Y0M1amIyMHdIaGNOTWpBeE1qSXhNVGMxCk5ETTNXaGNOTXpBeE1qRTVNVGMxTkRNM1dqQmFNUXN3Q1FZRFZRUUdFd0pEVGpFUU1BNEdBMVVFQ0F3SFUybEQKYUhWaGJqRVNNQkFHQTFVRUJ3d0pSM1ZoYm1kWmRXRnVNUTB3Q3dZRFZRUUtEQVJVWlhOME1SWXdGQVlEVlFRRApEQTEzZDNjdWJYbGhjSEF1WTI5dE1JSUJJakFOQmdrcWhraUc5dzBCQVFFRkFBT0NBUThBTUlJQkNnS0NBUUVBCnV0ek51djNFd0JRRjAvaHY4T2M3eGZzVUZIRG80cm5nYlV5Ym1UTVd6WkVONER3QTlCeVhvUk8rMUFOR0h0cXMKTTk4MUpJM3N5R21uMTV1Q1N5YTRlMjNIOEZrRVcveFh4VzNVMXZoRmxpRlB3NFgxM0ZRTno5TGJqUDdmbHBOTwpRRzZKVm1nYUNyZFp1TlFnbzFJSG1ocmFFWHV6VStTVkYzVXh1MHd3OUNRZmsxcG82N0NiN0FNRlRMa25QbUhJCndpbHpEK1dYeUtyV3NjRDBQZ2gzTTV1QnBENTJuNURsOHpWZDJiSFlSZGdIUm90dTJ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1:
      f:data:
        .: {}
        f:tls.crt: {}
        f:tls.key: {}
      f:type: {}
    manager: kubectl-create
    operation: Update
    time: "2020-12-26T17:46:00Z"
  name: test-tls
  namespace: default
  resourceVersion: "399079"
  uid: 67fb9062-56b4-4900-bab6-45ea35b75a09
type: kubernetes.io/tls
[root@master01 manifests]# 

  提示:建立tls型別的secret資源物件時,只需要指定其名稱和對應的證照和私鑰檔案即可;這裡需要注意一點,不管外部證照和私鑰是什麼名字,在tls型別的secret資源物件中都叫tls.crt和tls.key;它會自動對映為這兩個名字;

  示例:定義pod掛載secret儲存卷

[root@master01 ~]# cat mount-secretvolume.yaml
apiVersion: v1
kind: Pod
metadata:
  name: test-pod
  namespace: default
spec:
  containers:
  - name: nginx
    image: nginx:1.14-alpine
    volumeMounts:
    - name: test-tls-secret
      mountPath: /etc/nginx/cert/
  volumes:
  - name: test-tls-secret
    secret:
      secretName: test-tls
      items:
      - key: tls.crt
        path: test.crt
        mode: 0400
      - key: tls.key
        path: test.key
        mode: 0400
[root@master01 ~]# 

  應用資源清單

[root@master01 ~]# kubectl apply -f mount-secretvolume.yaml
pod/test-pod created
[root@master01 ~]# kubectl get pods -w
NAME         READY   STATUS    RESTARTS   AGE
mysql-demo   1/1     Running   0          23m
test-nginx   1/1     Running   0          53m
test-pod     1/1     Running   0          6s
^C[root@master01 ~]# kubectl describe pod test-pod
Name:         test-pod
Namespace:    default
Priority:     0
Node:         node04.k8s.org/192.168.0.47
Start Time:   Sun, 27 Dec 2020 01:57:54 +0800
Labels:       <none>
Annotations:  <none>
Status:       Running
IP:           10.244.4.25
IPs:
  IP:  10.244.4.25
Containers:
  nginx:
    Container ID:   docker://4ec25999d3813cebe9c7a78c3ffa6b5d282f730c56c88454b08c08b1e7f7a3a7
    Image:          nginx:1.14-alpine
    Image ID:       docker-pullable://nginx@sha256:485b610fefec7ff6c463ced9623314a04ed67e3945b9c08d7e53a47f6d108dc7
    Port:           <none>
    Host Port:      <none>
    State:          Running
      Started:      Sun, 27 Dec 2020 01:57:55 +0800
    Ready:          True
    Restart Count:  0
    Environment:    <none>
    Mounts:
      /etc/nginx/cert/ from test-tls-secret (rw)
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-xvd4c (ro)
Conditions:
  Type              Status
  Initialized       True 
  Ready             True 
  ContainersReady   True 
  PodScheduled      True 
Volumes:
  test-tls-secret:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  test-tls
    Optional:    false
  default-token-xvd4c:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  default-token-xvd4c
    Optional:    false
QoS Class:       BestEffort
Node-Selectors:  <none>
Tolerations:     node.kubernetes.io/not-ready:NoExecute op=Exists for 300s
                 node.kubernetes.io/unreachable:NoExecute op=Exists for 300s
Events:
  Type    Reason     Age   From               Message
  ----    ------     ----  ----               -------
  Normal  Scheduled  20s   default-scheduler  Successfully assigned default/test-pod to node04.k8s.org
  Normal  Pulled     19s   kubelet            Container image "nginx:1.14-alpine" already present on machine
  Normal  Created    19s   kubelet            Created container nginx
  Normal  Started    19s   kubelet            Started container nginx
[root@master01 ~]# 

  提示:可以看到對應容器已經將對應secret儲存卷以讀寫方式掛載至/etc/nginx/cert/目錄;

  驗證:進入test-pod互動式介面,看看對應目錄下是否有對應的檔案呢?

[root@master01 ~]# kubectl exec -it test-pod -- /bin/sh
/ # cd /etc/nginx/
/etc/nginx # ls
cert                    fastcgi_params.default  modules                 uwsgi_params
conf.d                  koi-utf                 nginx.conf              uwsgi_params.default
fastcgi.conf            koi-win                 nginx.conf.default      win-utf
fastcgi.conf.default    mime.types              scgi_params
fastcgi_params          mime.types.default      scgi_params.default
/etc/nginx # ls cert
test.crt  test.key
/etc/nginx # cat cert/test.crt 
-----BEGIN CERTIFICATE-----
MIIDhzCCAm+gAwIBAgIJAN0KdsMjH2SXMA0GCSqGSIb3DQEBCwUAMFoxCzAJBgNV
BAYTAkNOMRAwDgYDVQQIDAdTaUNodWFuMRIwEAYDVQQHDAlHdWFuZ1l1YW4xDTAL
Bg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+jBLH6aRE2ZFFl+I4On74cJlMeke+Q0vlHi
kM4OxtfCbFC5j2aZ08RvH2hoJy0onlJnZ4/3wwl5AoGASAR6OcoeeyvfWO+BkSRv
0/kTNpjXaR51VroOazCPVeT1dzBgFWeGuc8QxodnbJifmJIwa1LH9MIJbNohsGHa
Kb2Tps930d7qx6w7ui+0Le/AyPVC27oNkIMCGEtlm7FXn9xUe6lx8JUXQcqxxhSt
fmHLR2v///EWIyA+2YTAnJcCgYAQgMNAksS2m1q+x3D0Q3BImeyK8Y6uhCMdmHHP
SPVTpzmtjrYASzQCGLiTfUz38IptuUx6fHuXpqbDk+G9gZi8g+aXR9dtfWi/b0e0
wfWj30+Z3wwOebDcg96dWFGIbwLEOC3jl7aabqjvHagyo56H1wzeRNwhidkhrLUD
Sy/FEQKBgQCSgRh+shRXtPsWeOV/vsZUTF4a4Rz0Z2hh4ZU6zKSS6o4OfVbHrc54
CqHeZGLG9jjKBmyXFvpNkvOjfxo9EYJIk800FVro1VmN1pUMRja+nKIjoxYASfPt
UZ0UpbrLY81WlaFOY+OBaEw8iUvpoa5KeKIuY9UCSyK9Dxa4Her4tQ==
-----END RSA PRIVATE KEY-----
/etc/nginx # 

  提示:可以看到在test-pod容器對應的/etc/nginx/目錄下自動建立了一個cert目錄,並在其目錄下看到有兩個證照檔案,一個名為test.crt,一個名為test.key;這兩個名字都是我們在pod資源清單中指定的名稱;

  示例:使用資源清單建立secret資源

[root@master01 ~]# cat test-secret.yaml
apiVersion: v1
kind: Secret
metadata: 
  name: test-secret-demo
  namespace: default
data:
  name: cWl1aG9tCg==
  passwd: YWRtaW4xMjMuY29tCg==
type: Opaque 
[root@master01 ~]# 

  提示:使用資源清單方式建立secret時,data欄位是定義對應的kv配置資訊,需要事先將其對應的值轉換為base64編碼;type是用來指定對應secret的型別,這個欄位有四個值,分別是Opaque 、kubernetes.io/dockerconfigjson、kubernetes.io/tls、kubernetes.io/service-account-token;

  應用資源清單

[root@master01 ~]# kubectl apply -f test-secret.yaml 
secret/test-secret-demo created
[root@master01 ~]# kubectl get secret
NAME                           TYPE                                  DATA   AGE
default-token-xvd4c            kubernetes.io/service-account-token   3      18d
docker-registry.io             kubernetes.io/dockerconfigjson        1      107m
mysql-auth                     Opaque                                2      70m
test-secret-demo               Opaque                                2      19s
test-tls                       kubernetes.io/tls                     2      42m
www-myapp-com-ingress-secret   kubernetes.io/tls                     2      5d
[root@master01 ~]# kubectl describe secret test-secret-demo
Name:         test-secret-demo
Namespace:    default
Labels:       <none>
Annotations:  <none>

Type:  Opaque

Data
====
name:    7 bytes
passwd:  13 bytes
[root@master01 ~]#kubectl get secret test-secret-demo -o yaml           
apiVersion: v1
data:
  name: cWl1aG9tCg==
  passwd: YWRtaW4xMjMuY29tCg==
kind: Secret
metadata:
  annotations:
    kubectl.kubernetes.io/last-applied-configuration: |
      {"apiVersion":"v1","data":{"name":"cWl1aG9tCg==","passwd":"YWRtaW4xMjMuY29tCg=="},"kind":"Secret","metadata":{"annotations":{},"name":"test-secret-demo","namespace":"default"},"type":"Opaque"}
  creationTimestamp: "2020-12-26T18:28:19Z"
  managedFields:
  - apiVersion: v1
    fieldsType: FieldsV1
    fieldsV1:
      f:data:
        .: {}
        f:name: {}
        f:passwd: {}
      f:metadata:
        f:annotations:
          .: {}
          f:kubectl.kubernetes.io/last-applied-configuration: {}
      f:type: {}
    manager: kubectl-client-side-apply
    operation: Update
    time: "2020-12-26T18:28:19Z"
  name: test-secret-demo
  namespace: default
  resourceVersion: "403480"
  uid: 95aecff5-7f78-4f16-908f-61deb56f8c53
type: Opaque
[root@master01 ~]# 

  示例:使用stringData欄位來指定資料

[root@master01 ~]# cat test1-secret.yaml
apiVersion: v1
kind: Secret
metadata: 
  name: test-secret-demo1
  namespace: default
stringData:
  name: qiuhom
  passwd: admin123.com
type: Opaque 
[root@master01 ~]# 

  提示:使用stringData欄位來指定kv配置資訊,可以不用將對應資料編碼為base64格式;它會在建立secret時,自動將其轉化為base64編碼格式,存放在data欄位中;

  應用配置清單

[root@master01 ~]# kubectl apply -f test1-secret.yaml
secret/test-secret-demo1 created
[root@master01 ~]# kubectl get secret
NAME                           TYPE                                  DATA   AGE
default-token-xvd4c            kubernetes.io/service-account-token   3      18d
docker-registry.io             kubernetes.io/dockerconfigjson        1      117m
mysql-auth                     Opaque                                2      79m
test-secret-demo               Opaque                                2      9m40s
test-secret-demo1              Opaque                                2      11s
test-tls                       kubernetes.io/tls                     2      51m
www-myapp-com-ingress-secret   kubernetes.io/tls                     2      5d
[root@master01 ~]# kubectl get secret test-secret-demo1 -o yaml
apiVersion: v1
data:
  name: cWl1aG9t
  passwd: YWRtaW4xMjMuY29t
kind: Secret
metadata:
  annotations:
    kubectl.kubernetes.io/last-applied-configuration: |
      {"apiVersion":"v1","kind":"Secret","metadata":{"annotations":{},"name":"test-secret-demo1","namespace":"default"},"stringData":{"name":"qiuhom","passwd":"admin123.com"},"type":"Opaque"}
  creationTimestamp: "2020-12-26T18:37:48Z"
  managedFields:
  - apiVersion: v1
    fieldsType: FieldsV1
    fieldsV1:
      f:data:
        .: {}
        f:name: {}
        f:passwd: {}
      f:metadata:
        f:annotations:
          .: {}
          f:kubectl.kubernetes.io/last-applied-configuration: {}
      f:type: {}
    manager: kubectl-client-side-apply
    operation: Update
    time: "2020-12-26T18:37:48Z"
  name: test-secret-demo1
  namespace: default
  resourceVersion: "404463"
  uid: 718d1306-43af-40cb-9a56-6177205be5c4
type: Opaque
[root@master01 ~]# kubectl describe secret test-secret-demo1    
Name:         test-secret-demo1
Namespace:    default
Labels:       <none>
Annotations:  <none>

Type:  Opaque

Data
====
name:    6 bytes
passwd:  12 bytes
[root@master01 ~]#

  提示:stringData欄位不會被apiserver輸出,它將stringData欄位資訊以base64編碼格式儲存在data欄位中給予顯示;但是將對應secret輸出為yaml格式時,在對應的註解資訊中能夠看到對應stringData的資訊;

相關文章