应用配置的关键在于能够在多个环境中区分配置边项,将配置从应用程序源码 中分离,可频繁变更配置值。如果将pod 定义描述看作是应用程序源代码,显然需 要将配置移出pod 定义。
Kubemetes 允许将配置选项分离到单独的资源对象ConfigMap 中,本质上就是 一个键/值对映射,既可以是一个变量的值,也可以是完整的配置文件。
k8s.io/api/core/v1/types.go
// ConfigMap holds configuration data for pods to consume.
type ConfigMap struct {
metav1.TypeMeta `json:",inline"`
// Standard object's metadata.
// More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata
// +optional
metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"`
// Data contains the configuration data.
// Each key must consist of alphanumeric characters, '-', '_' or '.'.
// Values with non-UTF-8 byte sequences must use the BinaryData field.
// The keys stored in Data must not overlap with the keys in
// the BinaryData field, this is enforced during validation process.
// +optional
Data map[string]string `json:"data,omitempty" protobuf:"bytes,2,rep,name=data"`
// BinaryData contains the binary data.
// Each key must consist of alphanumeric characters, '-', '_' or '.'.
// BinaryData can contain byte sequences that are not in the UTF-8 range.
// The keys stored in BinaryData must not overlap with the ones in
// the Data field, this is enforced during validation process.
// Using this field will require 1.10+ apiserver and
// kubelet.
// +optional
BinaryData map[string][]byte `json:"binaryData,omitempty" protobuf:"bytes,3,rep,name=binaryData"`
}
结构中Data 字段描述了ConfigMap key/value 含义。同yaml创建描述相同,value可以是变量,也可以是配置文件的整个内容。
client-go/kubernetes/type/core/v1/configmap.go
// ConfigMapInterface has methods to work with ConfigMap resources.
type ConfigMapInterface interface {
Create(*v1.ConfigMap) (*v1.ConfigMap, error)
Update(*v1.ConfigMap) (*v1.ConfigMap, error)
Delete(name string, options *metav1.DeleteOptions) error
DeleteCollection(options *metav1.DeleteOptions, listOptions metav1.ListOptions) error
Get(name string, options metav1.GetOptions) (*v1.ConfigMap, error)
List(opts metav1.ListOptions) (*v1.ConfigMapList, error)
Watch(opts metav1.ListOptions) (watch.Interface, error)
Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1.ConfigMap, err error)
ConfigMapExpansion
}
以上是client-go的rest接口函数,可以实现对ConfigMap的管理。
首先要引用ConfigMap,必须在创建应用之前,先创建ConfigMap。
apiVers i on : vl
kind: Pod
metadata:
name: test
spec:
containers:
- image : luksa/fortune:env
env :
name : INTERVAL //设置环境变量名
valueFrorn :
configMapKeyRef
name:configmap-name //引用的ConfigMap,既创建的ConfigMap名称
key: configmap-key //环境变量的值设置为ConfigMap中,对应的键值
apiVersion: vl
kind: Pod
metadata:
name: test
spec:
containers:
- image: nginx:alpine
name: web-server
volumeMounts:
- name: config
mountPath: /etc //挂在configmap券至此位置
readOnly: true
volumes:
- name: config
configMap:
name: configmap-name //卷定义引用此创建的configmap