如何使用 Ansible Playbook 和 k8s 模块为 Kubernetes K8s 或 OpenShift OCP 容器和 Pod 分配 emptyDir 卷。

容器的文件系统仅在其生命周期内存在,因此当容器终止并重新启动时,文件系统中的更改会丢失。为了获得独立于容器的持久存储,可以使用卷,这对于有状态应用程序(如 Redis 等键值存储和数据库)尤为重要。

Ansible 创建 Kubernetes 或 OpenShift 服务 kubernetes.core.k8s 管理 Kubernetes (K8s) 对象

让我们来谈谈 Ansible 的 k8s 模块。它的全名是 kubernetes.core.k8s,属于 Ansible 用于与 Kubernetes 和 Red Hat OpenShift 集群交互的模块集合。它用于管理 Kubernetes (K8s) 对象。

参数

  • name(字符串)/namespace(字符串):对象名称/命名空间
  • api_version(字符串):"v1"
  • kind(字符串):对象模型
  • state(字符串):present(存在)/absent(不存在)/patched(已更新)
  • definition(字符串):YAML 定义
  • src(路径):YAML 定义文件路径
  • template(原始):YAML 模板定义
  • validate(字典):验证资源定义

k8s 模块有许多参数,以下是最常用的参数总结: 大多数参数非常通用,可以组合用于多种场景。name 和 namespace 参数用于指定对象名称和/或命名空间,可以在不提供完整资源定义的情况下创建、删除或发现对象。api_version 参数指定 Kubernetes API 版本,默认为 v1(版本 1)。kind 参数指定对象模型。state 参数(与其他模块类似)用于确定对象是应该被创建(present)、更新(patched)还是删除(absent)。definition 参数允许在创建或更新对象时提供有效的 YAML 定义(字符串、列表或字典)。如果希望指定 YAML 定义文件,src 参数提供包含对象或对象集合的有效 YAML 定义的文件路径。您还可以通过 template 参数指定 YAML 定义模板。validate 参数可用于定义如何根据 Kubernetes 模式验证资源定义,但请注意,这需要 kubernetes-validate Python 模块。

链接

如何使用 Ansible Playbook 配置 Kubernetes K8s 或 OpenShift OCP 的 Pod 使用卷进行存储

我将创建一个运行单个容器的 Pod。此 Pod 配置了一个 emptyDir 类型的卷,该卷的生命周期与 Pod 相同,即使容器终止并重新启动,卷依然存在。

代码

ansible_playbook.yml

---
- name: k8s 卷演示
  hosts: localhost
  gather_facts: false
  connection: local
  vars:
    myproject: "volume-example"
  tasks:
    - name: 创建 {{ myproject }} 命名空间
      kubernetes.core.k8s:
        kind: Namespace
        name: "{{ myproject }}"
        state: present
        api_version: v1

    - name: 创建 k8s Pod
      kubernetes.core.k8s:
        state: present
        namespace: "{{ myproject }}"
        definition:
          apiVersion: v1
          kind: Pod
          metadata:
            name: redis
          spec:
            containers:
              - name: redis
                image: redis
                volumeMounts:
                  - name: redis-storage
                    mountPath: /data/redis
            volumes:
              - name: redis-storage
                emptyDir: {}

执行

ansible-pilot $ ansible-playbook kubernetes/configure-volume.yml
[WARNING]: No inventory was parsed, only implicit localhost is available
[WARNING]: provided hosts list is empty, only localhost is available. Note that the implicit localhost does not match 'all'
PLAY [k8s 卷演示] ******************************************************
TASK [创建 volume-example 命名空间] ***********************************
changed: [localhost]
TASK [创建 k8s Pod] ***************************************************
changed: [localhost]
PLAY RECAP ************************************************************
localhost                  : ok=2    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
ansible-pilot $

幂等性测试

ansible-pilot $ ansible-playbook kubernetes/configure-volume.yml
[WARNING]: No inventory was parsed, only implicit localhost is available
[WARNING]: provided hosts list is empty, only localhost is available. Note that the implicit localhost does not match 'all'
PLAY [k8s 卷演示] ******************************************************
TASK [创建 volume-example 命名空间] ***********************************
ok: [localhost]
TASK [创建 k8s Pod] ***************************************************
ok: [localhost]
PLAY RECAP ************************************************************
localhost                  : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
ansible-pilot $

执行前

Kubernetes (k8s)

ansible-pilot $ kubeadmin get pod --namespace=volume-example
No resources found in volume-example namespace.
ansible-pilot $

OpenShift (OCP)

ansible-pilot $ oc login -u kubeadmin https://api.crc.testing:6443
Logged into "https://api.crc.testing:6443" as "kubeadmin" using existing credentials.
You have access to 64 projects, the list has been suppressed. You can list all projects with 'oc projects'
Using project "default".
ansible-pilot $ oc project volume-example
error: A project named "volume-example" does not exist on "https://api.crc.testing:6443".
Your projects are:
* default
[...]
ansible-pilot $ oc get pod --namespace=volume-example
No resources found in volume-example namespace.
ansible-pilot $

执行后

Kubernetes (k8s)

ansible-pilot $ kubeadmin get pod --namespace=volume-example
NAME    READY   STATUS    RESTARTS   AGE
redis   1/1     Running   0          38s
ansible-pilot $ kubeadmin get pod --namespace=volume-example --output=yaml
apiVersion: v1
items:
- apiVersion: v1
  kind: Pod
  metadata:
    annotations:
      k8s.v1.cni.cncf.io/network-status: |-
        [{
            "name": "openshift-sdn",
            "interface": "eth0",
            "ips": [
                "10.217.0.129"
            ],
            "default": true,
            "dns": {}
        }]
      k8s.v1.cni.cncf.io/networks-status: |-
        [{
            "name": "openshift-sdn",
            "interface": "eth0",
            "ips": [
                "10.217.0.129"
            ],
            "default": true,
            "dns": {}
        }]
      openshift.io/scc: anyuid
    creationTimestamp: "2022-04-19T14:32:03Z"
    name: redis
    namespace: volume-example
    resourceVersion: "354824"
    uid: 6726f836-e601-430a-a829-1575ede0a781
  spec:
    containers:
    - image: redis
      imagePullPolicy: Always
      name: redis
      resources: {}
      securityContext:
        capabilities:
          drop:
          - MKNOD
      terminationMessagePath: /dev/termination-log
      terminationMessagePolicy: File
      volumeMounts:
      - mountPath: /data/redis
        name: redis-storage
      - mountPath: /var/run/secrets/kubernetes.io/serviceaccount
        name: kube-api-access-qprq2
        readOnly: true
    dnsPolicy: ClusterFirst
    enableServiceLinks: true
    imagePullSecrets:
    - name: default-dockercfg-8h4dp
    nodeName: crc-8rwmc-master-0
    preemptionPolicy: PreemptLowerPriority
    priority: 0
    restartPolicy: Always
    schedulerName: default-scheduler
    securityContext:
      seLinuxOptions:
        level: s0:c26,c25
    serviceAccount: default
    serviceAccountName: default
    terminationGracePeriodSeconds: 30
    tolerations:
    - effect: NoExecute
      key: node.kubernetes.io/not-ready
      operator: Exists
      tolerationSeconds: 300
    - effect: NoExecute
      key: node.kubernetes.io/unreachable
      operator: Exists
      tolerationSeconds: 300
    volumes:
    - emptyDir: {}
      name: redis-storage
    - name: kube-api-access-qprq2
      projected:
        defaultMode: 420
        sources:
        - serviceAccountToken:
            expirationSeconds: 3607
            path: token
        - configMap:
            items:
            - key: ca.crt
              path: ca.crt
            name: kube-root-ca.crt
        - downwardAPI:
            items:
            - fieldRef:
                apiVersion: v1
                fieldPath: metadata.namespace
              path: namespace
        - configMap:
            items:
            - key: service-ca.crt
              path: service-ca.crt
            name: openshift-service-ca.crt
  status:
    conditions:
    - lastProbeTime: null
      lastTransitionTime: "2022-04-19T14:32:03Z"
      status: "True"
      type: Initialized
    - lastProbeTime: null
      lastTransitionTime: "2022-04-19T14:32:10Z"
      status: "True"
      type: Ready
    - lastProbeTime: null
      lastTransitionTime: "2022-04-19T14:32:10Z"
      status: "True"
      type: ContainersReady
    - lastProbeTime: null
      lastTransitionTime: "2022-04-19T14:32:03Z"
      status: "True"
      type: PodScheduled
    containerStatuses:
    - containerID: cri-o://4bffa22f092c5c7808b39af757a5df46b214e5037f891e1bee8f7bd95f1ae26b
      image: docker.io/library/redis:latest
      imageID: docker.io/library/redis@sha256:1b36e146475b71ee04da1ce60f201308392ff8468107f91615885d2e49536010
      lastState: {}
      name: redis
      ready: true
      restartCount: 0
      started: true
      state:
        running:
          startedAt: "2022-04-19T14:32:09Z"
    hostIP: 192.168.126.11
    phase: Running
    podIP: 10.217.0.129
    podIPs:
    - ip: 10.217.0.129
    qosClass: BestEffort
    startTime: "2022-04-19T14:32:03Z"
kind: List
metadata:
  resourceVersion: ""
  selfLink: ""
ansible-pilot $

OpenShift (OCP)

ansible-pilot $ oc project volume-example
Now using project "volume-example" on server "https://api.crc.testing:6443".
ansible-pilot $ oc get pod --namespace=volume-example
NAME    READY   STATUS    RESTARTS   AGE
redis   1/1     Running   0          38s
ansible-pilot $ oc get pod --namespace=volume-example --output=yaml
apiVersion: v1
items:
- apiVersion: v1
  kind: Pod
  metadata:
    annotations:
      k8s.v1.cni.cncf.io/network-status: |-
        [{
            "name": "openshift-sdn",
            "interface": "eth0",
            "ips": [
                "10.217.0.129"
            ],
            "default": true,
            "dns": {}
        }]
      k8s.v1.cni.cncf.io/networks-status: |-
        [{
            "name": "openshift-sdn",
            "interface": "eth0",
            "ips": [
                "10.217.0.129"
            ],
            "default": true,
            "dns": {}
        }]
      openshift.io/scc: anyuid
    creationTimestamp: "2022-04-19T14:32:03Z"
    name: redis
    namespace: volume-example
    resourceVersion: "354824"
    uid: 6726f836-e601-430a-a829-1575ede0a781
  spec:
    containers:
    - image: redis
      imagePullPolicy: Always
      name: redis
      resources: {}
      securityContext:
        capabilities:
          drop:
          - MKNOD
      terminationMessagePath: /dev/termination-log
      terminationMessagePolicy: File
      volumeMounts:
      - mountPath: /data/redis
        name: redis-storage
      - mountPath: /var/run/secrets/kubernetes.io/serviceaccount
        name: kube-api-access-qprq2
        readOnly: true
    dnsPolicy: ClusterFirst
    enableServiceLinks: true
    imagePullSecrets:
    - name: default-dockercfg-8h4dp
    nodeName: crc-8rwmc-master-0
    preemptionPolicy: PreemptLowerPriority
    priority: 0
    restartPolicy: Always
    schedulerName: default-scheduler
    securityContext:
      seLinuxOptions:
        level: s0:c26,c25
    serviceAccount: default
    serviceAccountName: default
    terminationGracePeriodSeconds: 30
    tolerations:
    - effect: NoExecute
      key: node.kubernetes.io/not-ready
      operator: Exists
      tolerationSeconds: 300
    - effect: NoExecute
      key: node.kubernetes.io/unreachable
      operator: Exists
      tolerationSeconds: 300
    volumes:
    - emptyDir: {}
      name: redis-storage
    - name: kube-api-access-qprq2
      projected:
        defaultMode: 420
        sources:
        - serviceAccountToken:
            expirationSeconds: 3607
            path: token
        - configMap:
            items:
            - key: ca.crt
              path: ca.crt
            name: kube-root-ca.crt
        - downwardAPI:
            items:
            - fieldRef:
                apiVersion: v1
                fieldPath: metadata.namespace
              path: namespace
        - configMap:
            items:
            - key: service-ca.crt
              path: service-ca.crt
            name: openshift-service-ca.crt
  status:
    conditions:
    - lastProbeTime: null
      lastTransitionTime: "2022-04-19T14:32:03Z"
      status: "True"
      type: Initialized
    - lastProbeTime: null
      lastTransitionTime: "2022-04-19T14:32:10Z"
      status: "True"
      type: Ready
    - lastProbeTime: null
      lastTransitionTime: "2022-04-19T14:32:10Z"
      status: "True"
      type: ContainersReady
    - lastProbeTime: null
      lastTransitionTime: "2022-04-19T14:32:03Z"
      status: "True"
      type: PodScheduled
    containerStatuses:
    - containerID: cri-o://4bffa22f092c5c7808b39af757a5df46b214e5037f891e1bee8f7bd95f1ae26b
      image: docker.io/library/redis:latest
      imageID: docker.io/library/redis@sha256:1b36e146475b71ee04da1ce60f201308392ff8468107f91615885d2e49536010
      lastState: {}
      name: redis
      ready: true
      restartCount: 0
      started: true
      state:
        running:
          startedAt: "2022-04-19T14:32:09Z"
    hostIP: 192.168.126.11
    phase: Running
    podIP: 10.217.0.129
    podIPs:
    - ip: 10.217.0.129
    qosClass: BestEffort
    startTime: "2022-04-19T14:32:03Z"
kind: List
metadata:
  resourceVersion: ""
  selfLink: ""
ansible-pilot $

Kubernetes Redis Pod 日志

1:C 19 Apr 2022 14:48:44.365 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
1:C 19 Apr 2022 14:48:44.366 # Redis version=6.2.6, bits=64, commit=00000000, modified=0, pid=1, just started
1:C 19 Apr 2022 14:48:44.366 # Warning: no config file specified, using the default config. In order to specify a config file use redis-server /path/to/redis.conf
1:M 19 Apr 2022 14:48:44.366 * monotonic clock: POSIX clock_gettime
1:M 19 Apr 2022 14:48:44.367 * Running mode=standalone, port=6379.
1:M 19 Apr 2022 14:48:44.367 # WARNING: The TCP backlog setting of 511 cannot be enforced because /proc/sys/net/core/somaxconn is set to the lower value of 128.
1:M 19 Apr 2022 14:48:44.367 # Server initialized
1:M 19 Apr 2022 14:48:44.368 * Ready to accept connections

Ansible 模块 k8s 执行后

在执行 Ansible 模块 kubernetes.core.k8s 后,我们成功地在 Kubernetes 或 OpenShift 环境中创建了一个名为 redis 的 Pod,并为其配置了一个 emptyDir 类型的卷。以下是对执行后状态的进一步说明:

1. Pod 的运行状态

从 Kubernetes 和 OpenShift 的命令行工具输出中可以看到,redis Pod 已成功创建并处于运行状态。Pod 的状态为 Running,并且容器内的 Redis 服务也已启动并准备好接受连接。

2. 卷的挂载和使用

Pod 配置了一个 emptyDir 类型的卷,挂载路径为 /data/redis。这种类型的卷会在 Pod 创建时自动创建,并在 Pod 生命周期内保持存在,即使容器终止并重新启动,卷中的数据也不会丢失。这为 Redis 提供了持久化存储,确保数据不会因容器重启而丢失。

3. Kubernetes 和 OpenShift 的资源状态

通过 kubectl 和 oc 命令行工具,我们可以看到 Pod 的详细信息,包括其网络配置、卷挂载信息以及状态条件。这些信息表明 Pod 已正确初始化,并且所有容器都已准备好运行。

4. Redis 服务的日志

从 Redis Pod 的日志中可以看到,Redis 服务已成功启动,并且正在监听默认端口 6379。日志中提到没有指定配置文件,因此 Redis 使用了默认配置。如果需要自定义配置,可以通过挂载配置文件的方式将自定义的 redis.conf 文件注入到 Pod 中。

5. Ansible Playbook 的幂等性

在执行 Ansible Playbook 时,我们进行了幂等性测试。第一次运行时,Ansible 创建了命名空间和 Pod,状态为 changed;第二次运行时,由于资源已经存在,状态为 ok,这表明 Ansible Playbook 具有良好的幂等性,不会对已经存在的资源进行不必要的更改。

6. 后续操作建议

a. 访问 Redis 服务

如果需要从集群外部访问 Redis 服务,可以创建一个 Service 对象,将 Pod 的端口暴露到集群外部。例如,可以使用 NodePort 或 LoadBalancer 类型的服务。

b. 持久化存储

虽然 emptyDir 卷在 Pod 生命周期内是持久的,但如果 Pod 被删除,数据仍然会丢失。如果需要更持久的存储,可以考虑使用 PersistentVolume 和 PersistentVolumeClaim,例如基于 NFS、Ceph 或云存储的持久化卷。

c. 配置管理

为了更好地管理 Redis 配置,可以通过 Kubernetes 的 ConfigMap 或 Secret 对象将配置文件注入到 Pod 中,而不是使用默认配置。

d. 监控和日志

可以为 Redis Pod 配置监控和日志收集工具,例如 Prometheus 和 Fluentd,以便更好地管理和维护服务。

通过 Ansible 和 Kubernetes/OpenShift 的结合,我们能够高效地部署和管理有状态的应用程序,如 Redis。这种自动化的方式不仅提高了部署效率,还确保了环境的一致性和可维护性。