1. 程式人生 > >kubernetes資源物件ConfigMap學習(一)

kubernetes資源物件ConfigMap學習(一)

生產環境中很多應用程式的配置可能需要通過配置檔案,命令列引數和環境變數的組合配置來完成。這些配置應該從image中解耦,以此來保持容器化應用程式的可移植性。在K8S1.2後引入ConfigMap來處理這種型別的配置資料。ConfigMap API資源提供了將配置資料注入容器的方式,同時保證該機制對容器來說是透明的。ConfigMap可以被用來儲存單個屬性,也可以用來儲存整個配置檔案或者JSON二進位制物件。ConfigMap API資源儲存鍵/值對配置資料,這些資料可以在pods裡使用。

前提條件:已安裝kubernetes叢集

系統安裝好後,預設可以查詢到以下configmap

注:我這裡使用的是flannel網路,可能與你的存在差異。

kubectl describe configmap kube-flannel-cfg --namespace kube-system

上圖Data欄位

ConfigMap也是kubernetes的一種資源物件,當然建立ConfigMap也有兩種方式:

(1)通過kubectl create configmap命令

(2)通過yaml檔案

1、首先來看下通過命令列建立configmap

kubectl命令提供了可以從目錄、檔案或者字面值三種方式建立configmap

格式:

kubectl create configmap NAME [--from-file=[key=]source] [--from-literal=key1=value1][--dry-run] [options]

具體可以通過kubectl create configmap -h查詢

接下來,分別說明具體的用法:

首先,在configmap目錄下建立test1.txt、test2.txt以及env.txt檔案,內容如下:


--from-file引數使用:

格式:kubectl create configmap config-name --from-file=[key-name]=directory_path或者file-path

kubectl create configmap my-config --from-file=/root/practice/configmap


結果就是將該目錄下的檔名作為key值,檔案內容作為value值,儲存到my-config中。

--from-file跟具體的檔案,並且--from-file可以有多個。

kubectl create configmap my-config --from-file=/root/practice/configmap/test1.txt --from-file=/root/practice/configmap/test2.txt

如果想自己指定key的值,可以這樣:

kubectl create configmap my-config --from-file=test1=/root/practice/configmap/test1.txt--from-file=/root/practice/configmap/test2.txt

--from-env-file引數使用:

格式:kubectl create configmap config-name --from-env-file=env-file-path

kubectl create configmap my-env-config --from-env-file=/root/practice/configmap/env.txt

--from-env-file只能跟檔案,不能是目錄,並且檔案裡key/value有格式的要求,會做引數的校驗。我們上面把env.1寫成了env,1,因此報錯了。

這一次成功了,但是隻有4個鍵值對,env.4是空值,因為我們沒定義value值,env.5不存在,因為我們使用#註釋掉了。

--from-literal引數使用:

格式:kubectl create configmap config-name --from-literal=key-name=value

kubectl create configmap my-config1 --from-literal=key1=value1 --from-literal=key2=value2


2、通過yaml檔案建立configmap

我們可以看下在建立flannel網路時使用的yaml檔案(僅截取了ConfigMap的定義部分)

我們一開始查詢到的kube-flannel-cfg就是用過上述定義的資源物件建立的。

下面寫個簡單的例子,說明下,建立test-cfg.yaml檔案如下:

執行kubectl apply -f test-cfg.yaml,查詢configmap:test-cfg的具體資訊

至此,我們學習了configmap的建立方法,接下來就要學習怎麼使用configmap了。也就是說房子建好了,怎麼用的問題了。