如何设置能够执行kubectl(kubernetes)命令的ansible剧本 [英] How to setup ansible playbook that is able to execute kubectl (kubernetes) commands

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

问题描述

我正在尝试编写简单的ansible剧本,该剧本能够对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. 我首先需要为k8定义库存吗?像这样的东西: 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集合

ansible-galaxy collection install community.kubernetes

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

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剧本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆