本文介绍了如何设置能够执行 kubectl (kubernetes) 命令的 ansible playbook的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写简单的 ansible playbook,它能够对在 kubernetes 集群中运行的 pod(容器)执行一些任意命令.

I'm trying to write simple ansible playbook that would be able to execute some arbitrary command against the pod (container) running in kubernetes cluster.

我想使用 kubectl 连接插件:https://docs.ansible.com/ansible/latest/plugins/connection/kubectl.html 但很难弄清楚如何实际做到这一点.

I would like to utilise kubectl connection plugin: https://docs.ansible.com/ansible/latest/plugins/connection/kubectl.html but having struggle to figure out how to actually do that.

几个问题:

  1. 我是否需要先定义 k8s 的库存?类似于:https://docs.ansible.com/ansible/latest/plugins/inventory/k8s.html.我的理解是,我将通过清单定义 kube 配置,kubectl 插件将使用它来实际连接到 pod 以执行特定操作.
  2. 如果是,是否有任何通过 kubectl 插件执行任意命令的示例(但不是通过在某些远程机器上调用 kubectl 的 shell 插件 - 这不是我要找的)
  1. Do I need to first have inventory for k8s defined? Something like: https://docs.ansible.com/ansible/latest/plugins/inventory/k8s.html. My understanding is that I would define kube config via inventory which would be used by the kubectl plugin to actually connect to the pods to perform specific action.
  2. If yes, is there any example of arbitrary command executed via kubectl plugin (but not via shell plugin that invokes kubectl on some remote machine - this is not what I'm looking for)

我假设在 ansible-playbook 调用期间,我会指向 k8s 清单.

I'm assuming that, during the ansible-playbook invocation, I would point to k8s inventory.

谢谢.

推荐答案

首先安装 k8s 集合

First install k8s collections

ansible-galaxy collection install community.kubernetes

这是剧本,它将对所有 pod 进行排序并在每个 pod 中运行命令

and here is play-book, it will sort all pods and run a command in every pod

---
-
  hosts: localhost

  vars_files:
    - vars/main.yaml

  collections:
    - community.kubernetes

  tasks:
    -
      name: Get the pods in the specific namespace
      k8s_info:
        kubeconfig: '{{ k8s_kubeconfig }}'
        kind: Pod
        namespace: test
      register: pod_list


    -
      name: Print pod names
      debug:
         msg: "pod_list: {{ pod_list | json_query('resources[*].status.podIP')  }} "

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

    -
      k8s_exec:
        kubeconfig: '{{ k8s_kubeconfig }}'
        namespace: "{{ namespace  }}"
        pod: "{{ item.metadata.name }}"
        command: apt update
      with_items: "{{ pod_list.resources }}"
      register: exec
      loop_control:
        label: "{{ item.metadata.name }}"

这篇关于如何设置能够执行 kubectl (kubernetes) 命令的 ansible playbook的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 21:53