我想使用Ansible自动执行kubectl
和helm
命令。目标机器配置正确,因此两者都可以在手动shell(例如kubectl get nodes
或helm list
(中使用cli。但当试图进行任何API调用时,如获取服务器版本
- name: List charts
shell: kubectl version -v=8
它以禁止错误中断。详细的日志记录并没有给我更多的细节:
fatal: [127.0.0.1]: FAILED! => changed=true
cmd: kubectl version -v=10
delta: '0:00:00.072452'
end: '2020-02-27 15:22:36.227928'
msg: non-zero return code
rc: 255
start: '2020-02-27 15:22:36.155476'
stderr: |-
I0227 15:22:36.224517 27321 loader.go:359] Config loaded from file /home/user/.kube/config
I0227 15:22:36.225211 27321 round_trippers.go:386] curl -k -v -XGET -H "Accept: application/json, */*" -H "User-Agent: kubectl/v1.11.3 (linux/amd64) kubernetes/a452946" 'https://k8smaster01:6443/version?timeout=32s'
I0227 15:22:36.225975 27321 round_trippers.go:405] GET https://k8smaster01:6443/version?timeout=32s in 0 milliseconds
I0227 15:22:36.225986 27321 round_trippers.go:411] Response Headers:
I0227 15:22:36.226062 27321 helpers.go:219] Connection error: Get https://k8smaster01:6443/version?timeout=32s: Forbidden
F0227 15:22:36.226080 27321 helpers.go:119] Unable to connect to the server: Forbidden
stderr_lines: <omitted>
stdout: 'Client Version: version.Info{Major:"1", Minor:"11", GitVersion:"v1.11.3", GitCommit:"a4529464e4629c21224b3d52edfe0ea91b072862", GitTreeState:"clean", BuildDate:"2018-09-09T18:02:47Z", GoVersion:"go1.10.3", Compiler:"gc", Platform:"linux/amd64"}'
stdout_lines: <omitted>
然而,当发送手动请求到像这样的API网址
- name: Test master connection
shell: curl -k https://k8smaster01:6443/version?timeout=32s
它起作用:
stderr_lines: <omitted>
stdout: |-
{
"major": "1",
"minor": "11",
"gitVersion": "v1.11.3",
"gitCommit": "a4529464e4629c21224b3d52edfe0ea91b072862",
"gitTreeState": "clean",
"buildDate": "2018-09-09T17:53:03Z",
"goVersion": "go1.10.3",
"compiler": "gc",
"platform": "linux/amd64"
}
为什么使用kubectl
的API调用在使用Ansible执行时不起作用
我在代理服务器后面,但k8smaster01
设置在no_proxy
中。很可能得到了,我在任务中打印了$no_proxy
用于测试。
对于curl
,我使用了-k
,因为它是来自k8s的自签名证书。这可能会伤害kubectl
(它本身在不从Ansible运行时起作用(。当使用Ansible调用kubectl --insecure-skip-tls-verify=true get node
时,它也不起作用。
我试图通过设置空的环境变量来从代理中取消设置env变量(因为代理仅用于互联网访问(:
- name: Kubectl test
become: false
shell: kubectl get no -v=10
environment:
http_proxy:
https_proxy:
no_proxy:
HTTP_PROXY:
HTTPS_PROXY:
NO_PROXY:
这是个坏主意,因为curl
(似乎在kubectl
内部使用(将其解析为None
并失败。奇怪的是,kubectl
失败了,出现了一个dns错误:
skipped caching discovery info due to Get https://k8smaster01:6443/api?timeout=32s: proxyconnect tcp: dial tcp: lookup None on 127.0.0.53:53: server misbehaving
发现主要问题是我在/etc/environment
中设置了NO_PROXY=$no_proxy
,其中no_proxy
包含主机名k8smaster01
。由于/etc/environment
不解析bash变量,所以大写的NO_PROXY
只包含作为字符串的$no_proxy
。因此,用相应的值(例如NO_PROXY=k8smaster01
(代替NO_PROXY=$no_proxy
就足够了。
这在以前并不是一个问题,因为大多数应用程序似乎都遵循Linux规范,使用小写的环境变量来使用代理。
在本地集群(侦听https://0.0.0.0:<any port>
的服务器(上,将0.0.0.0/8放在NO_PROXY中,否则kubectl(使用kubectl集群信息进行验证(将尝试使用您配置的代理。