需要在相同部署的 pod 上有一个 post 部署任务

Need to a have a post deployment task on the pod of same deployment

我正在编写使用 Kubernetes 部署服务的 ansible 脚本,我被 post-部署过程的一个步骤困住了:

我已经部署了一个具有“副本:3”的服务,并且所有副本都已启动并且 运行ning 现在我的问题是我必须做一个我必须进入容器的迁移和 运行 那里已经存在一个脚本。

我可以通过单独进入容器然后 运行 脚本手动完成,但这将再次需要手动干预。

我想要实现的是一旦部署完成并且所有副本都已启动并且运行宁我想通过进入容器来运行脚本并且所有这些步骤应该是由 ansible 脚本执行,无需手动操作。

有办法吗?

看看 k8s_exec 模块。

- name: Check RC status of command executed
  community.kubernetes.k8s_exec:
    namespace: myproject
    pod: busybox-test
    command: cmd_with_non_zero_exit_code
  register: command_status
  ignore_errors: True

- name: Check last command status
  debug:
    msg: "cmd failed"
  when: command_status.return_code != 0

@Vasili Angapov 是对的 - k8s_exec 模块可能是这种情况下的最佳解决方案,但我想添加一些有用的注释。


要使用 k8s_exec 我们需要知道确切的 Pod 名称(我们需要在 ansible 任务中将其作为 pod 参数传递).如您所写,我假设您的 PodsDeployment 管理,因此每个 Pod 的名称中都有由 ReplicaSet 添加的随机字符串。因此,您必须以某种方式找到 Pods 的全名。

我创建了一个简单的剧本来说明我们如何找到所有 PodsPod 名称,标签为:app=web 然后 运行 示例 touch file123456789 命令在这些 Pods.

---
- hosts: localhost
  collections:
    - community.kubernetes

  tasks:     
    - name: "Search for all Pods labelled app=web"
      k8s_info:
        kind: Pod
        label_selectors:
          - app = web
      register: pod_names

    - name: "Get Pod names"
      set_fact:
        pod_names: "{{ pod_names | json_query('resources[*].metadata.name') }}"

    - name: "Run command on every Pod labelled app=web"
      k8s_exec:
        namespace: default
        pod: "{{ item }}"
        command: touch file123456789
      with_items: "{{ pod_names }}"

注意: 您也可以使用 command 模块代替 k8s_exec 模块。 在我们的示例中,我们可以使用:

而不是 k8s_exec 任务
- name: "Run command on every Pod labelled app=web"
  command: >
    kubectl exec "{{ item }}" -n default -- touch file123456789
  with_items: "{{ pod_names }}"