kubespray安装kubernetes完成后kubectl客户端配置
程序员文章站
2022-03-10 16:45:31
...
接上篇使用kuberspay无坑安装生产级Kubernetes集群,在使用kubespray
安装好了kubernetes之
后,我们需要在自己的客户端电脑配置kubectl,如何将集群的配置信息在本地配置呢,我们使用下面的脚本,放在scripts\copy-kubeconfig.yaml
下,内容为:
源码地址:http://www.wisely.top/2017/07/04/kubespray-kubectl-config/
---
- hosts: kube-master[0]
gather_facts: no
become: yes
tasks:
- fetch:
src: "/etc/kubernetes/ssl/{{ item }}.pem"
dest: "{{ playbook_dir }}/kubectl/{{ item }}.pem"
flat: True
with_items:
- admin-{{ inventory_hostname }}-key
- admin-{{ inventory_hostname }}
- ca
- name: export hostname
set_fact:
kubectl_name: "{{ inventory_hostname }}"
- hosts: localhost
connection: local
vars:
kubectl_name: "{{ hostvars[groups['kube-master'][0]].kubectl_name }}"
cluster_name: "{{ hostvars[groups['kube-master'][0]].cluster_name }}"
kube_apiserver_port: "{{ hostvars[groups['kube-master'][0]].kube_apiserver_port }}"
system_namespace: "{{ hostvars[groups['kube-master'][0]].system_namespace }}"
tasks:
- name: "check if context admin@{{ cluster_name }} exists"
command: kubectl config get-contexts admin@{{ cluster_name }}
register: kctl
failed_when: kctl.rc == 0
- block:
- name: "create cluster {{ cluster_name }}"
command: >
kubectl config set-cluster {{ cluster_name }}
--server=https://{{ kubectl_name }}:{{ kube_apiserver_port }}
--certificate-authority={{ playbook_dir }}/kubectl/ca.pem
--embed-certs
- name: "create credentials admin"
command: >
kubectl config set-credentials admin
--certificate-authority={{ playbook_dir }}/kubectl/ca.pem
--client-key={{ playbook_dir }}/kubectl/admin-{{ kubectl_name }}-key.pem
--client-certificate={{ playbook_dir }}/kubectl/admin-{{ kubectl_name }}.pem
--embed-certs
- name: "create context admin@{{ cluster_name }}"
command: >
kubectl config set-context admin@{{ cluster_name }}
--cluster={{ cluster_name }}
--namespace={{ system_namespace }}
--user=admin
- name: "use context admin@{{ cluster_name }}"
command: kubectl config use-context admin@{{ cluster_name }}
when: kctl.rc != 0
- name: "clean up fetched certificates"
file:
state: absent
path: "{{ playbook_dir }}/kubectl"
在kubespray
根目录执行:
ansible-playbook -i inventory/inventory.cfg scripts/copy-kubeconfig.yaml
执行完成后,如果你本机的hosts
文件已经配置了node1
对应的ip,配置已经完成;如果没有配置,编辑vi /Users/wangyunfei/.kube/config
,将node1
修改为192.168.1.130
。此时再执行:
wangyunfeideMBP:kubespray wangyunfei$ kubectl get node
NAME STATUS AGE VERSION
node1 Ready,SchedulingDisabled 3d v1.6.1+coreos.0
node2 Ready 3d v1.6.1+coreos.0
node3 Ready 3d v1.6.1+coreos.0