Openshift - 仅在特定时间段内运行 pod

Har*_*i M -1 openshift kubernetes

我是 Openshfit 的新手。我们正在使用 openshift 部署来部署我们的多个微服务(SpringBoot 应用程序)。部署是从 docker 镜像完成的。

我们有一种情况,我们需要从午夜到凌晨 5 点单独停止一个微服务(由于外部依赖)。

有人可以建议一种自动执行此操作的方法吗?

我能够oc scale deployment/sampleservice--replicas=0 手动运行 以将 pod 的数量设为零,并在稍后手动扩展到 1。

我不确定如何在特定时间自动运行此命令。Openshift 中的 CronJob 应该能够做到这一点。但不确定如何配置 cronjob 来执行 OC 命令。

任何指导都会有很大帮助

lar*_*sks 5

使用 cronjob 是一个不错的选择。

首先,您需要一个具有oc可用命令行客户端的图像。我确定某处有一个预构建的,但是由于它将在您的 OpenShift 集群中以特权运行,您需要一些您信任的东西,这可能意味着您自己构建它。我用了:

FROM quay.io/centos/centos:8

RUN curl -o /tmp/openshift-client.tar.gz \
                https://mirror.openshift.com/pub/openshift-v4/clients/ocp/latest/openshift-client-linux.tar.gz; \
    tar -C /bin -xf /tmp/openshift-client.tar.gz oc kubectl; \
    rm -f /tmp/openshift-client.tar.gz

ENTRYPOINT ["/bin/oc"]
Run Code Online (Sandbox Code Playgroud)

为了正确处理身份验证,您需要创建 aServiceAccount然后通过 aRole和 a为其分配适当的权限RoleBinding。我创建了一个ServiceAccount名为oc-client-sa

apiVersion: v1
kind: ServiceAccount
metadata:
  name: oc-client-sa
  namespace: oc-client-example
Run Code Online (Sandbox Code Playgroud)

授予和对象权限的Role命名对象:oc-client-rolePodDeployment

kind: Role
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: oc-client-role
  namespace: oc-client-example
rules:
  - verbs:
      - get
      - list
      - create
      - watch
      - patch
    apiGroups:
      - ''
    resources:
      - pods
  - verbs:
      - get
      - list
      - create
      - watch
      - patch
    apiGroups:
      - 'apps'
    resources:
      - deployments
      - deployments/scale
Run Code Online (Sandbox Code Playgroud)

以及RoleBinding将 连接oc-client-sa ServiceAccount 到 的oc-client-role Role

kind: RoleBinding
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: oc-client-rolebinding
  namespace: oc-client-example
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: oc-client-role
subjects:
  - kind: ServiceAccount
    name: oc-client-sa
Run Code Online (Sandbox Code Playgroud)

有了所有这些,我们可以编写CronJob这样的代码,在特定时间缩小部署规模。请注意,我们正在使用oc-client-sa ServiceAccount我们之前创建的来运行作业:

apiVersion: batch/v1
kind: CronJob
metadata:
  name: scale-web-down
  namespace: oc-client-example
spec:
  schedule: "00 00 * * *"
  concurrencyPolicy: Forbid
  jobTemplate:
    spec:
      template:
        spec:
          serviceAccountName: oc-client-sa
          restartPolicy: Never
          containers:
          - image: docker.io/larsks/openshift-client
            args:
              - scale
              - deployment/sampleservice
              - --replicas=0
            name: oc-scale-down
Run Code Online (Sandbox Code Playgroud)

你会写一个类似的,在凌晨 5 点扩大规模。

由于设置,oc客户端将自动使用 Kubernetes 提供给您的 pod 的凭据serviceAccountName