This Task aims to automate the setup of a production-ready Kubernetes cluster using Ansible. The automation will handle installing essential Kubernetes components (kubeadm, kubelet, kubectl), configuring networking (Calico or Flannel), and ensuring seamless cluster operations.
kubectl get nodes
).sudo apt update && sudo apt install -y ansible
Define the Kubernetes master and worker nodes in inventory.ini:
[master]
master-node ansible_host=192.168.1.100
[workers]
worker-node-1 ansible_host=192.168.1.101
worker-node-2 ansible_host=192.168.1.102
[k8s_cluster:children]
master
workers
- name: Install Kubernetes Dependencies
hosts: k8s_cluster
become: yes
tasks:
- name: Install required packages
apt:
name: ['curl', 'apt-transport-https', 'ca-certificates']
state: present
update_cache: yes
- name: Install Docker
apt:
name: docker.io
state: present
- name: Add Kubernetes GPG key
shell: curl -fsSL https://packages.cloud.google.com/apt/doc/apt-key.gpg | apt-key add -
- name: Add Kubernetes Repository
shell: echo "deb https://apt.kubernetes.io/ kubernetes-xenial main" | tee -a /etc/apt/sources.list.d/kubernetes.list
- name: Install kubeadm, kubelet, and kubectl
apt:
name: ['kubelet', 'kubeadm', 'kubectl']
state: present
update_cache: yes
- name: Enable kubelet service
systemd:
name: kubelet
enabled: yes
- name: Initialize Kubernetes Master
hosts: master
become: yes
tasks:
- name: Initialize the cluster
shell: kubeadm init --pod-network-cidr=192.168.0.0/16
register: kubeadm_output
changed_when: true
- name: Copy kubeconfig to user directory
shell: |
mkdir -p $HOME/.kube
cp -i /etc/kubernetes/admin.conf $HOME/.kube/config
chown $(id -u):$(id -g) $HOME/.kube/config
For Calico:
- name: Deploy Calico Network Plugin
hosts: master
become: yes
tasks:
- name: Apply Calico YAML
shell: kubectl apply -f https://docs.projectcalico.org/manifests/calico.yaml
For Flannel:
- name: Deploy Flannel Network Plugin
hosts: master
become: yes
tasks:
- name: Apply Flannel YAML
shell: kubectl apply -f https://raw.githubusercontent.com/coreos/flannel/master/Documentation/kube-flannel.yml
- name: Join Worker Nodes to the Cluster
hosts: workers
become: yes
tasks:
- name: Join the cluster
shell: "{{ hostvars['master-node']['kubeadm_output'].stdout_lines | select('match', '^kubeadm join') | list | first }}"
args:
chdir: $HOME
kubectl get nodes
kubectl get pods -n kube-system
kubectl create deployment nginx --image=nginx
kubectl expose deployment nginx --port=80 --type=NodePort
kubectl get svc nginx
curl http://:
This project provides a fully automated Kubernetes setup with Ansible and networking configuration, ready for real-world implementation.