写一个ansible的playbook自动化部署一个三master二node的k8s集群
时间: 2024-06-08 15:09:30 浏览: 255
好的,以下是一个简单的Ansible Playbook,可以自动化部署一个三master二node的Kubernetes集群。
1. 首先,我们需要创建一个inventory文件,指定服务器的IP地址和SSH用户名。在本例中,我们将使用`hosts.ini`文件:
```
[masters]
192.168.1.1
192.168.1.2
192.168.1.3
[nodes]
192.168.1.4
192.168.1.5
[all:vars]
ansible_user=ubuntu
```
2. 接下来,我们需要创建一个`deploy-k8s.yml`文件,定义Kubernetes集群的部署步骤:
```
---
- hosts: all
become: yes
tasks:
- name: Install Docker
apt:
name:
- docker.io
- apt-transport-https
- ca-certificates
- curl
- gnupg-agent
- software-properties-common
state: present
- name: Add Kubernetes apt-key
apt_key:
url: https://packages.cloud.google.com/apt/doc/apt-key.gpg
state: present
- name: Add Kubernetes apt repository
apt_repository:
repo: deb https://apt.kubernetes.io/ kubernetes-xenial main
state: present
filename: kubernetes.list
- name: Install Kubernetes components
apt:
name:
- kubelet
- kubeadm
- kubectl
state: present
- name: Disable swap
command: swapoff -a
become: yes
when: ansible_swaptotal_mb > 0
- name: Initialize Kubernetes cluster
command: kubeadm init --control-plane-endpoint "loadbalancer" --upload-certs --pod-network-cidr=10.244.0.0/16
become: yes
args:
creates: /etc/kubernetes/admin.conf
- name: Copy Kubernetes config file to user's home directory
copy:
src: /etc/kubernetes/admin.conf
dest: /home/{{ ansible_user }}/admin.conf
owner: "{{ ansible_user }}"
- name: Create Kubernetes directory for user
file:
path: /home/{{ ansible_user }}/.kube
state: directory
owner: "{{ ansible_user }}"
- name: Copy Kubernetes config file to user's .kube directory
copy:
src: /etc/kubernetes/admin.conf
dest: /home/{{ ansible_user }}/.kube/config
owner: "{{ ansible_user }}"
- name: Install Flannel CNI plugin
command: kubectl apply -f https://raw.githubusercontent.com/coreos/flannel/master/Documentation/kube-flannel.yml
become: yes
args:
creates: /etc/kubernetes/cni/net.d/10-flannel.conflist
- name: Join worker nodes to Kubernetes cluster
command: kubeadm join loadbalancer:6443 --token <token> --discovery-token-ca-cert-hash <hash>
become: yes
when: inventory_hostname in groups['nodes']
- name: Copy Kubernetes config file to worker nodes
copy:
src: /etc/kubernetes/admin.conf
dest: /tmp/admin.conf
- name: Set Kubernetes config file for worker nodes
command: kubectl config --kubeconfig=/tmp/admin.conf use-context kubernetes-admin@kubernetes
become: yes
when: inventory_hostname in groups['nodes']
```
3. 最后,我们可以运行这个Playbook来自动化部署Kubernetes集群:
```
ansible-playbook -i hosts.ini deploy-k8s.yml
```
这个Playbook将会在所有服务器上安装Docker和Kubernetes组件,禁用swap,初始化Kubernetes集群,安装Flannel CNI插件,将节点加入到集群中,并且在工作节点上设置Kubernetes配置文件。
阅读全文