kubernetes之使用ConfigMap管理Pod配置文件

简介

ConfigMaps可以使容器镜像与配置文件解耦,实现容器化应用程序的可移植性。此文提供一系列的方法示例讲述如何创建ConfigMaps,使用存储在ConfigMaps中的数据配置Pod。

备注:此文档参考官方文档,并加以自己的理解。如有误导性的内容,请批评指正。

创建一个ConfigMap

我们可以使用kubectl create configmapkustomization.yaml中的ConfigMap生成器创建一个ConfigMap。从Kubernetes 1.14版本开始,kubectl开始支持使用kustomization.yaml创建ConfigMap

使用 kubectl create configmap 创建一个 ConfigMap

使用kubectl create configmap从目录、文件或字面值创建configmaps。

kubectl create configmap <map-name> <data-source>

<map-name>即配置的ConfigMap的名字,<data-source>是从目录、文件或字面值下读取数据的目录。

ConfigMap中的data-source应该是一个键值对:

  • key=文件名称或提供的命令行的key
  • value=提命令行中提供的文件内容或字面值

使用kubectl describekubectl get查看ConfigMap的信息。

从目录中创建 ConfigMaps

可以使用kubectl create configmap从同一个目录下的多个文件创建ConfigMap

# Create the local directory
mkdir -p configure-pod-container/configmap/

# Download the sample files into `configure-pod-container/configmap/` directory
wget https://kubernetes.io/examples/configmap/game.properties -O configure-pod-container/configmap/game.properties
wget https://kubernetes.io/examples/configmap/ui.properties -O configure-pod-container/configmap/ui.properties

# Create the configmap
kubectl create configmap game-config --from-file=configure-pod-container/configmap/

configure-pod-container/configmap/目录下包含连个文件

game.properties
ui.properties

查看配置的ConfigMap内容:

kubectl describe configmaps game-config

从结果可以看出:ConfigMap中的data块中包含了configure-pod-container/configmap/目录下game.propertiesui.properties两个文件中的所有内容。

Name:         game-config
Namespace:    default
Labels:       <none>
Annotations:  <none>

Data
====
game-env-file.properties:
----
enemies=aliens
lives=3
allowed="true"

# This comment and the empty line above it are ignored

game.properties:
----
enemies=aliens
lives=3
enemies.cheat=true
enemies.cheat.level=noGoodRotten
secret.code.passphrase=UUDDLRLRBABAS
secret.code.allowed=true
secret.code.lives=30
ui.properties:
----
color.good=purple
color.bad=yellow
allow.textmode=true
how.nice.to.look=fairlyNice

Events:  <none>

yaml格式输出如下:

# kubectl get configmaps game-config -o yaml
apiVersion: v1
data:
  game-env-file.properties: |
    enemies=aliens
    lives=3
    allowed="true"

    # This comment and the empty line above it are ignored
  game.properties: |-
    enemies=aliens
    lives=3
    enemies.cheat=true
    enemies.cheat.level=noGoodRotten
    secret.code.passphrase=UUDDLRLRBABAS
    secret.code.allowed=true
    secret.code.lives=30
  ui.properties: |
    color.good=purple
    color.bad=yellow
    allow.textmode=true
    how.nice.to.look=fairlyNice
kind: ConfigMap
metadata:
  creationTimestamp: "2020-01-17T07:18:08Z"
  name: game-config
  namespace: default
  resourceVersion: "10100181"
  selfLink: /api/v1/namespaces/default/configmaps/game-config
  uid: a447f523-ddf4-48f5-a0eb-6f24c732fee5

从文件中创建 ConfigMaps

使用kubectl create configmap从一个独立的文件或多个文件中创建ConfigMap

例如:

# kubectl create configmap game-config-2 --from-file=configure-pod-container/configmap/game.properties

查看内容:

# kubectl describe configmaps game-config-2

输出如下所示

Name:         game-config-2
Namespace:    default
Labels:       <none>
Annotations:  <none>

Data
====
game.properties:
----
enemies=aliens
lives=3
enemies.cheat=true
enemies.cheat.level=noGoodRotten
secret.code.passphrase=UUDDLRLRBABAS
secret.code.allowed=true
secret.code.lives=30
Events:  <none>

也可以通过多次使用--from-file参数从多个数据源中创建ConfigMap

例如:

# kubectl create configmap game-config-2 --from-file=configure-pod-container/configmap/game.properties --from-file=configure-pod-container/configmap/ui.properties

使用--from-env-file选项从env-file中创建ConfigMap:

例如:

# Env-files contain a list of environment variables.
# These syntax rules apply:
#   Each line in an env file has to be in VAR=VAL format.
#   Lines beginning with # (i.e. comments) are ignored.
#   Blank lines are ignored.
#   There is no special handling of quotation marks (i.e. they will be part of the ConfigMap value)).

# Download the sample files into `configure-pod-container/configmap/` directory
wget https://kubernetes.io/examples/configmap/game-env-file.properties -O configure-pod-container/configmap/game-env-file.properties

# The env-file `game-env-file.properties` looks like below
cat configure-pod-container/configmap/game-env-file.properties
enemies=aliens
lives=3
allowed="true"

# This comment and the empty line above it are ignored

创建ConfigMap

kubectl create configmap game-config-env-file \
       --from-env-file=configure-pod-container/configmap/game-env-file.properties

查看内容

# kubectl get configmap game-config-env-file -o yaml

输出如下

apiVersion: v1
data:
  allowed: '"true"'
  enemies: aliens
  lives: "3"
kind: ConfigMap
metadata:
  creationTimestamp: "2020-01-17T07:32:05Z"
  name: game-config-env-file
  namespace: default
  resourceVersion: "10103588"
  selfLink: /api/v1/namespaces/default/configmaps/game-config-env-file
  uid: 0ed90509-5577-4225-a1ad-826426069da3

注意:当通过多次使用 --from-env-file 从多个数据源中创建ConfigMap时,只有最后一个 env-file生效。

演示多次使用 --from-env-file的例子
例如:

# Download the sample files into `configure-pod-container/configmap/` directory
wget https://k8s.io/examples/configmap/ui-env-file.properties -O configure-pod-container/configmap/ui-env-file.properties

# Create the configmap
kubectl create configmap config-multi-env-files \
        --from-env-file=configure-pod-container/configmap/game-env-file.properties \
        --from-env-file=configure-pod-container/configmap/ui-env-file.properties
# kubectl get configmap config-multi-env-files -o yaml

输出内容如下,从结果可以看出生效的配置为最后一个--from-env-file指定的ui-env-file.properties

apiVersion: v1
data:
  color: purple
  how: fairlyNice
  textmode: "true"
kind: ConfigMap
metadata:
  creationTimestamp: "2020-01-17T07:45:01Z"
  name: config-multi-env-files
  namespace: default
  resourceVersion: "10106742"
  selfLink: /api/v1/namespaces/default/configmaps/config-multi-env-files
  uid: 583873dd-12e6-408a-9373-b9cfeb092d5a

定义从文件创建ConfigMap时要使用的Key

使用--from-file参数给某个数据源的文件的数据定一个key,在ConfigMapdata块下可以看到这个key。

kubectl create configmap game-config-3 --from-file=<my-key-name>=<path-to-file>

这里的<my-key-name>即想要在COnfigMap中使用的key的名称,<path-to-file>是本地数据源中key要表达的数据内容。
例如:

# kubectl create configmap game-config-3 --from-file=game-special-key=configure-pod-container/configmap/game.properties

查看内容

# kubectl get configmaps game-config-3 -o yaml

输出结果如下,在data块下有一个名称为game-special-keykeykey的值即为--from-file=game-special-key=configure-pod-container/configmap/game.properties文件中的内容。

apiVersion: v1
data:
  game-special-key: |-
    enemies=aliens
    lives=3
    enemies.cheat=true
    enemies.cheat.level=noGoodRotten
    secret.code.passphrase=UUDDLRLRBABAS
    secret.code.allowed=true
    secret.code.lives=30
kind: ConfigMap
metadata:
  creationTimestamp: "2020-01-17T07:59:47Z"
  name: game-config-3
  namespace: default
  resourceVersion: "10110353"
  selfLink: /api/v1/namespaces/default/configmaps/game-config-3
  uid: e1569842-1438-46c3-91da-30cd989c17da

从字面值中创建ConfigMap

使用带有--from-literal参数的kubectl create configmap从命令行的字面量中创建一个ConfigMap。

kubectl create configmap special-config --from-literal=special.how=very --from-literal=special.type=charm

可以用多个key-value的键值对。每一个命令行中提供的键值对在ConfigMapdata块下都是独立的。

查看内容

# kubectl get configmaps special-config -o yaml

输出如下

apiVersion: v1
data:
  special.how: very
  special.type: charm
kind: ConfigMap
metadata:
  creationTimestamp: "2020-01-17T08:09:09Z"
  name: special-config
  namespace: default
  resourceVersion: "10112639"
  selfLink: /api/v1/namespaces/default/configmaps/special-config
  uid: 57306de5-bd39-4d98-84fe-12357312551b

从生成器创建ConfigMap

kubelet从1.14版开始支持使用kustomization.yaml。可以从生成器创建ConfigMap,然后将其应用于在Apiserver上创建对象。

# Create a kustomization.yaml file with ConfigMapGenerator
cat <<EOF >./kustomization.yaml
configMapGenerator:
- name: game-config-4
  files:
  - configure-pod-container/configmap/game.properties
EOF

应用Kustomization目录创建ConfigMap对象。

kubectl apply -k .

查看是否创建成功

# kubectl get configmap
NAME                       DATA   AGE
...
game-config-4-m9dm2f92bt   1      48s
...
# kubectl describe configmaps/game-config-4-m9dm2f92bt
Name:         game-config-4-m9dm2f92bt
Namespace:    default
Labels:       <none>
Annotations:  kubectl.kubernetes.io/last-applied-configuration:
                {"apiVersion":"v1","data":{"game.properties":"enemies=aliens\nlives=3\nenemies.cheat=true\nenemies.cheat.level=noGoodRotten\nsecret.code.p...

Data
====
game.properties:
----
enemies=aliens
lives=3
enemies.cheat=true
enemies.cheat.level=noGoodRotten
secret.code.passphrase=UUDDLRLRBABAS
secret.code.allowed=true
secret.code.lives=30
Events:  <none>

注意,生成的ConfigMap名称具有通过对内容进行哈希后而附加的后缀。 这样可以确保每次修改内容时都会生成一个新的ConfigMap。

定义从文件生成ConfigMap时使用的Key

可以定义一个Key,而不是要在ConfigMap生成器中使用的文件名。 例如,要使用game-special-key从文件configure-pod-container/configmap/game.properties生成ConfigMap

# Create a kustomization.yaml file with ConfigMapGenerator
cat <<EOF >./kustomization.yaml
configMapGenerator:
- name: game-config-5
  files:
  - game-special-key=configure-pod-container/configmap/game.properties
EOF

应用Kustomization目录创建ConfigMap对象。

kubectl apply -k .

从字面量生成ConfigMap

为了从自定义的type=charmspecial.how=very字面量创建ConfigMap,在kustomization.yaml中定义的生成器如下:

# Create a kustomization.yaml file with ConfigMapGenerator
cat <<EOF >./kustomization.yaml
configMapGenerator:
- name: special-config-2
  literals:
  - special.how=very
  - special.type=charm
EOF

创建

kubectl apply -k .

使用 ConfigMap 中的数据定义容器的环境变量

从单一的 ConfigMap中的数据定义容器的环境变量:

1、在ConfigMap中以key-value的键值对定义环境变量

kubectl create configmap special-config --from-literal=special.how=very

2、将ConfigMap中定义的special.how值分配给Pod的spec中的SPECIAL_LEVEL_KEY环境变量。

apiVersion: v1
kind: Pod
metadata:
  name: dapi-test-pod
spec:
  containers:
    - name: test-container
      image: k8s.gcr.io/busybox
      command: [ "/bin/sh", "-c", "env" ]
      env:
        # Define the environment variable
        - name: SPECIAL_LEVEL_KEY
          valueFrom:
            configMapKeyRef:
              # The ConfigMap containing the value you want to assign to SPECIAL_LEVEL_KEY
              name: special-config
              # Specify the key associated with the value
              key: special.how
  restartPolicy: Never

创建Pod

kubectl create -f /root/k8s-example/pods/pod-single-configmap-env-variable.yaml

Pod的输出包含环境变量SPECIAL_LEVEL_KEY=very

从多个ConfigMaps数据中定义容器变量

创建ConfigMaps:

kubectl create -f /root/k8s-example/configmap/configmaps.yaml

在Pod的spec中定义环境变量

apiVersion: v1
kind: Pod
metadata:
  name: dapi-test-pod
spec:
  containers:
    - name: test-container
      image: k8s.gcr.io/busybox
      command: [ "/bin/sh", "-c", "env" ]
      env:
        - name: SPECIAL_LEVEL_KEY
          valueFrom:
            configMapKeyRef:
              name: special-config
              key: special.how
        - name: LOG_LEVEL
          valueFrom:
            configMapKeyRef:
              name: env-config
              key: log_level
  restartPolicy: Never

创建Pod:

kubectl create -f /root/k8s-example/pods/pod-multiple-configmap-env-variable.yaml

Pod的输出的环境变量包含两个SPECIAL_LEVEL_KEY=veryLOG_LEVEL=INFO

在ConfigMap中配置所有 key-value 键值对作为容器环境变量

创建包含多个键值对的ConfigMap

apiVersion: v1
kind: ConfigMap
metadata:
  name: special-config
  namespace: default
data:
  SPECIAL_LEVEL: very
  SPECIAL_TYPE: charm
kubectl create -f /root/k8s-example/configmap/configmap-multikeys.yaml

使用envFrom定义ConfigMap中的所有数据作为容器的环境变量。ConfigMap中的Key变成了Pod中的环境变量。

apiVersion: v1
kind: Pod
metadata:
  name: dapi-test-pod
spec:
  containers:
    - name: test-container
      image: k8s.gcr.io/busybox
      command: [ "/bin/sh", "-c", "env" ]
      envFrom:
      - configMapRef:
          name: special-config
  restartPolicy: Never

创建Pod

kubectl create -f https://kubernetes.io/examples/pods/pod-configmap-envFrom.yaml

Pod输出包含环境变量SPECIAL_LEVEL=verySPECIAL_TYPE=charm

在Pod命令中使用ConfigMap中定义的变量

在Pod的spec中的command块可以使用$(VAR_NAME)的方式,导入ConfigMap中定义的环境变量

apiVersion: v1
kind: Pod
metadata:
  name: dapi-test-pod
spec:
  containers:
    - name: test-container
      image: k8s.gcr.io/busybox
      command: [ "/bin/sh", "-c", "echo $(SPECIAL_LEVEL_KEY) $(SPECIAL_TYPE_KEY)" ]
      env:
        - name: SPECIAL_LEVEL_KEY
          valueFrom:
            configMapKeyRef:
              name: special-config
              key: SPECIAL_LEVEL
        - name: SPECIAL_TYPE_KEY
          valueFrom:
            configMapKeyRef:
              name: special-config
              key: SPECIAL_TYPE
  restartPolicy: Never

test-container容器输出如下:

very charm

Volumes 中添加 ConfigMap 数据

创建ConfigMap:

apiVersion: v1
kind: ConfigMap
metadata:
  name: special-config
  namespace: default
data:
  SPECIAL_LEVEL: very
  SPECIAL_TYPE: charm
# kubectl create -f /root/k8s-example/configmap/configmap-multikeys.yaml

在Pod的spec规格的volume块下添加ConfigMap的名称。此配置会添加ConfigMap中的数据到指定的volumeMounts.mountPath的目录中,即如下容器的/etc/config目录。command块列出volumeMounts.mountPath目录下的所有文件。

apiVersion: v1
kind: Pod
metadata:
  name: dapi-test-pod
spec:
  containers:
    - name: test-container
      image: k8s.gcr.io/busybox
      command: [ "/bin/sh", "-c", "ls /etc/config/" ]
      volumeMounts:
      - name: config-volume
        mountPath: /etc/config
  volumes:
    - name: config-volume
      configMap:
        # Provide the name of the ConfigMap containing the files you want
        # to add to the container
        name: special-config
  restartPolicy: Never

创建Pod:

# kubectl apply -f pod-configmap-volume.yaml

查看容器日志输出

# kubectl logs dapi-test-pod

输出内容如下:

SPECIAL_LEVEL
SPECIAL_TYPE

注意:如果 /etc/config 目录下有文件,将会被删除掉。

添加 ConfigMap数据到指定 Volume 路径下

使用 path 字段配置ConfigMap中的特定项到指定的路径下。例如SPECIAL_LEVEL项的内容将会挂载在config-volume指定的/etc/config/keys卷上。

apiVersion: v1
kind: Pod
metadata:
  name: dapi-test-pod
spec:
  containers:
    - name: test-container
      image: k8s.gcr.io/busybox
      command: [ "/bin/sh","-c","cat /etc/config/keys" ]
      volumeMounts:
      - name: config-volume
        mountPath: /etc/config
  volumes:
    - name: config-volume
      configMap:
        name: special-config
        items:
        - key: SPECIAL_LEVEL
          path: keys
  restartPolicy: Never

创建Pod

# kubectl apply -f /root/k8s-example/pods/pod-configmap-volume-specific-key.yaml

查看日志输出

# kubectl logs dapi-test-pod
very

注意:所有以前在 /etc/config/ 目录下的文件将会被删除

删除资源

# kubectl delete configmaps game-config
# kubectl delete configmaps game-config-2
# kubectl delete configmaps config-multi-env-files
# kubectl delete configmaps game-config-3
...

理解 ConfigMap 和 Pod

ConfigMap 的 API 资源以键值对的形式存储配置数据。数据可以在Pod中使用,也可以提供系统组件的配置。例如 controllers。ConfigMap与Secrets类似,但是提供了一种处理不包含敏感信息的字符串的方法。 用户和系统组件都可以将配置数据存储在ConfigMap中。

注意:ConfigMap应该引用属性文件,而不是替换它们。 可以将ConfigMap表示为类似于Linux / etc目录及其内容的东西。 例如,如果从ConfigMap创建Kubernetes卷,则ConfigMap中的每个数据项都由该卷中的单个文件表示。

ConfigMap的data字段包含配置数据。 如下例所示,它可以很简单,例如使用--from-literal定义的单个属性例,也可以很复杂,如使用--from-file定义的配置文件

apiVersion: v1
kind: ConfigMap
metadata:
  creationTimestamp: 2016-02-18T19:14:38Z
  name: example-config
  namespace: default
data:
  # example of a simple property defined using --from-literal
  example.property.1: hello
  example.property.2: world
  # example of a complex property defined using --from-file
  example.property.file: |-
    property.1=value-1
    property.2=value-2
    property.3=value-3

ConfigMap的限制条件

  • 在Pod的被创建之前必须先创建 ConfigMap(除非设置了 ConfigMap为可选项。如果引用的ConfigMap不存在,则Pod不会启动。 同样,对ConfigMap中不存在的key的引用也会阻止Pod启动。

  • 如果使用envFrom从ConfigMap中定义环境变量,则将忽略被认为无效的键。 可以启动Pod,但无效名称将记录在事件日志(InvalidVariableNames)中。 日志消息列出了每个跳过的键,可使用如下命令查看

kubectl get events

类似输出如下:

LASTSEEN FIRSTSEEN COUNT NAME          KIND  SUBOBJECT  TYPE      REASON                            SOURCE                MESSAGE
   0s       0s        1     dapi-test-pod Pod              Warning   InvalidEnvironmentVariableNames   {kubelet, 127.0.0.1}  Keys [1badkey, 2alsobad] from the EnvFrom configMap default/myconfig were skipped since they are considered invalid environment variable names.
  • ConfigMap驻留在特定的命名空间中。 ConfigMap只能由位于相同名称空间中的Pod引用
  • 不能给静态Pod配置ConfigMaps,Kubelet不支持。

猜你喜欢

转载自www.cnblogs.com/mcsiberiawolf/p/12227855.html