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



我正在编写用于使用Kubernetes部署服务的可见脚本,我被一个用于部署后过程的步骤所困扰:

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

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

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

有办法做到这一点吗?

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


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

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

---
- 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 }}"

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

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

看看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

相关内容

最新更新