Ansible shell 模块执行 kubectl 错误连接到本地主机被拒绝

Ansible shell module execute kubectl error connection to localhost refused

我有一个用于构建 kubernetes 集群的 ansible 脚本。如果我 运行 kubectl 通过 shell 模块:

- name: Ensure kube-apiserver-to-kubelet ClusterRole is applied
  shell: "kubectl apply -f kube-apiserver-to-kubelet.yaml"
  delegate_to: controller1
  run_once: true

我收到以下错误 "The connection to the server localhost:8080 was refused - did you specify the right host or port?":

fatal: [controller1 -> 10.240.0.11]: FAILED! => {"changed": true, "cmd": "kubectl apply -f kube-apiserver-to-kubelet.yaml", "delta": "0:00:00.116446", "end": "2018-04-15 21:42:51.023786", "msg": "non-zero return code", "rc": 1, "start": "2018-04-15 21:42:50.907340", "stderr": "The connection to the server localhost:8080 was refused - did you specify the right host or port?", "stderr_lines": ["The connection to the server localhost:8080 was refused - did you specify the right host or port?"], "stdout": "", "stdout_lines": []}

但是,如果我登录 controller1(我使用堡垒主机作为节点的代理。)并执行命令 运行s 没有问题:

kubectl apply -f kube-apiserver-to-kubelet.yaml
clusterrole.rbac.authorization.k8s.io "system:kube-apiserver-to-kubelet" configured
clusterrolebinding.rbac.authorization.k8s.io "system:kube-apiserver" configured

为什么这直接在节点上工作,而不是通过 ansible,我需要做什么才能使这个 运行 不失败?

它可能没有获取您的 kubeconfig(localhost:8080 是未配置的默认值)

我会使用内置 "k8s_raw" 模块或在您的 shell 脚本中指定 --kubeconfig 参数