可以使用ansible提供的 k8s module ,需要满足以下python依赖
python >= 3.6
kubernetes >= 12.0.0
PyYAML >= 3.11
jsonpatch
默认情况下,k8s module读取的是~/.kube/config文件进行k8s cluster的连接,比如
- name: Create a k8s namespace
kubernetes.core.k8s:
name: testing
api_version: v1
kind: Namespace
state: present
就是创建一个namespace到当前的cluster里。
当前有个需求就是在pod里运行ansible然后创建其他k8s资源,但是pod里除了serviceaccount之外是没有~/.kube/config或者其他credentials相关的配置信息的,但是官方文档里没有给出不使用kubeconfig的情况下应该怎么和k8s cluster交互的例子,测试过程很麻烦,在做了一些尝试之后成功了,特此做下记录。
- hosts: localhost
tasks:
- name: create endpoint
kubernetes.core.k8s:
verify_ssl: no
host: https://<cluster api server dns>
api_key: "{{ lookup('file', '/var/run/secrets/kubernetes.io/serviceaccount/token') }}"
name: testing
api_version: v1
kind: Namespace
state: present
host表示当前cluster api-server的域名,因为公司产线把cluster的api-server的service通过ingress和aws route53暴露成一个dns地址。
api_key使用的是pod绑定的serviceaccount的token,通过lookup插件读取token文件的内容,表示用这个token作为credentials连接cluster,也就是这个api_key决定了你是否有权限登录cluster并且做相关的操作。
xiangche@XIANGCHE-M-NXHV ~ % ansible-playbook test.yaml
[WARNING]: No inventory was parsed, only implicit localhost is available
[WARNING]: provided hosts list is empty, only localhost is available. Note that the implicit localhost does not match 'all'
PLAY [localhost] **************************************************************************************************************************
TASK [Gathering Facts] ********************************************************************************************************************
ok: [localhost]
TASK [create endpoint] ********************************************************************************************************************
ok: [localhost]
PLAY RECAP ********************************************************************************************************************************
localhost : ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
除了可以用serviceaccount token之外,还可以用k8s cluster签名的certificate和key作为credentials
- hosts: localhost
tasks:
- name: create endpoint
kubernetes.core.k8s:
verify_ssl: no
host: https://<cluster api server dns>
client_cert: /Users/xiangche/cert
client_key: /Users/xiangche/key
name: testing
api_version: v1
kind: Namespace
state: present
client_cert和client_key分别对应申请的certificate和key,只不过这里需要填写文件路径,不能是内容,运行之后是一样的结果。