Step 3: Deploying Prerequisites

In short
  • Ansible installs the K8S prerequisites on each server and allows you to replay deployments.
  • Introduction to the Ansible directory structure (inventory, roles, variables).
  • Choosing versions and components via variables.
  • Requires an Ansible instance that is ready to use.

Legacy version of the Kubernetes cookbook

This article is part of the first version of the cookbook (VMware and PhotonOS). A new version, on XCP-ng and Rocky Linux, is being published: the equivalent step is Step 03 - Ansible and OS Foundation. The article remains online for reference.

Introduction

With all the servers deployed and ready to use, it is time to apply the configuration needed to host the Kubernetes cluster.

The chosen approach is to use Ansible to configure each server with the prerequisites needed for the installation and proper functioning of K8S.

The advantage of this method is that you can easily replay deployments and track the evolution of your cluster over time by only modifying Ansible variables.

Ansible Organization

Continuing this step requires having an Ansible instance configured and ready to use. As a reminder, the deployed VMs are based on a template, for which we have specifically prepared the SSH layer to be controlled by Ansible.

On my end, Ansible is installed on my Windows workstation through the WSL layer. The tool has been configured to include in its inventory a connection to vCenter in order to identify available VMs and create groups on the fly based on the tags of the VMs. These tags were deployed in the previous step, along with the VMs, using OpenTofu (Terraform).

The exercise will be to create an Ansible role role_k8s_deploy, launched by a playbook playbook_deploy_k8s.yaml.

Due to the tags attached to the VMs, the actions described in the Ansible role will be applied either to all servers, or to the control plane, or to the workers, or to the load balancers. Feel free to take a look at the architecture definition to understand the scope of each VM.

Ansible relies on a specific file structure, with folder names that must be respected, each containing particular elements. It is, of course, possible to adapt this structure and use it according to different strategies.

Here is a description of what will be used for this article.

Ansible directory structure

Click the image to enlarge.

Ansible Inventory

The content of the inventory file is described in the corresponding article.

Ansible Playbook

The content of the playbook playbook_deploy_k8s.yml is very basic.

  
#Deploie le role "role_k8s_deploy" sur tous les serveurs appartenant au groupe "TAG_COOLCORP_APPS_K8S"
---
- name: Deploy K8S Cluster
  hosts: TAG_COOLCORP_APPS_K8S
  roles: 
    - role_k8s_deploy
  

It will allow us to apply the role role_k8s_deploy to all VMs in the group TAG_COOLCORP_APP_K8S, that is, all VMs with this tag, which are all the VMs previously deployed with OpenTofu (Terraform).

To start the deployment, simply call the playbook using the following command:

ansible-playbook playbooks/playbook_deploy_k8s.yml --ask-vault-pass

As a reminder, since the inventory has access to vCenter, the file is encrypted and requires a password requested by the --ask-vault-pass option

The command will start the execution of commands destined for the servers.

Variable Management

First, Ansible loads the variables present in the main.yml file in the defaults folder.

As you can see, each variable is named var_something. The idea is to follow a good practice that facilitates reading and interpreting information, but everyone can use their preferred naming convention.

The content of the file is segmented into sections:

System Variables

Global variables, specific to all servers, such as the name of the NTP server to use, the definition of tags...

  
#####Variables systeme
var_lan_tag: TAG-COOLCORP-NETWORK-LAN
var_web_tag: TAG-COOLCORP-NETWORK-WEB
var_ntp_server: ntp.ofivalmo.fr
var_domain: "coolcorp.priv coolcorp.fr"
#variable user
var_admin_user: bvivi57

Package Variables

These variables define the list of packages to be installed on each server, depending on its role. We also define the packages that are present by default in the system and which need to be removed to avoid any conflicts.

  
######Variables Packages
#Liste des paquets à déployer sur les control planee
var_k8s_packages_master:
  - kubeadm-{{  var_kub_version  }}
  - nfs-utils
  - tdnf-plugin-repogpgcheck
  - wget
  - tar
  - kubectl-{{  var_kub_version  }}
  - kubelet-{{  var_kub_version  }}
  - apparmor-parser
  - jq
  - cri-tools
  - git
  - linux

#Liste des paquets à déployer sur les nodes
var_k8s_packages_worker:
  - kubeadm-{{  var_kub_version  }}
  - nfs-utils
  - tdnf-plugin-repogpgcheck
  - wget
  - tar
  - kubelet-{{  var_kub_version  }}
  - apparmor-parser
  - cri-tools
  - linux

#Liste des paquets à supprimer  
var_remove_packages:
 - docker
 - containerd  

Note that some variables themselves refer to other variables, such as the version of Kubernetes defined later in the file.

K8S Variables

The last section is the most important and the heaviest, since it defines all the variables specific to K8S and its components.

  
    ###############Variable Kubernetes
    #Variables utilisées pour construire le fichier de configuration de kubeadm basé sur le template kubeadm.conf.j2 du dossier templates
    var_api_version: v1beta3
    var_kub_version : "1.29.4"
    var_kub_name: kub
    var_pod_subnet: "10.11.0.0/16"
    var_service_subnet: "10.12.0.0/16"
    var_vip_kub_endpoint: kub.coolcorp.priv
    var_vip_kub_vip: "192.168.10.91"
    var_vip_kub_vip_dmz: "192.168.5.91"
    
    #Variables pour définir les roles
    var_tag_master: TAG-COOLCORP-ROLE-MASTER
    var_tag_worker: TAG-COOLCORP-ROLE-WORKER
        
    #Variables définissant les ports à ouvrir
    #- ports "system" pour kubernetes 
    var_kubelet_port: 10250
    var_kube_api_port: 6443
    var_etcd_port: 2379
    var_etcd_member_port: 2380
    var_node_service_port: "30000:32767"
    
    #- ports "réseau" pour le fonctionnement du CNI Cilium
    var_cilium_udp_vxlan_port: 8472
    var_cilium_tcp_healt_port: 4240
    var_cilium_tcp_obser_port: 4222
    var_cilium_tcp_relay_port: 4245
    var_cilium_tcp_hubblepeer_port: 4244
    
    #Configuration de Cilium
    var_cilium_subnet: "10.13.0.0/16"
    var_cilium_cli: "https://github.com/cilium/cilium-cli/releases/latest/download/cilium-linux-amd64.tar.gz"
    
    #Lien vers la récupération du binaire containerd
    var_containerd_binary: https://github.com/containerd/containerd/releases/download/v1.7.16/containerd-1.7.16-linux-amd64.tar.gz
    
    #informations pour la connexion au vcenter pour l'addon VMware Kubernetes
    var_vcenter: vcenter.coolcorp.priv
    var_vcenter_user: [email protected]
    var_vcenter_password: "mot_de_passe_qui_ne_devrait_pas_être_visible"
    var_vcenter_datacenter : "Paris"
    
    #Configuration de l'ingress controler "Traefik"
    var_namespace_traefik_prd_lan: prd-traefik-lan
    var_namespace_traefik_prd_dmz: prd-traefik-dmz
    var_version_traefik: "2.10.4"
    var_traefik_lan_service_account: svc-prd-traefik
    var_traefik_dmz_service_account: svc-prd-traefik-dmz
    var_url_traefik_lan: traefik-lan.coolcorp.priv
    var_url_traefik_dmz: traefik-dmz.coolcorp.priv
    

The kubeadm subsection will allow us to define the content of the configuration file that we will pass to kubeadm during cluster deployment. For this, the file is templated in jinja format, named kubeadm.conf.j2 and located in the templates folder.

Here is its content:

  
---
apiVersion: kubeadm.k8s.io/{{  var_api_version  }}
kind: ClusterConfiguration
kubernetesVersion: {{  var_kub_version  }}
networking:
 podSubnet: "{{  var_pod_subnet  }}"
 serviceSubnet: "{{  var_service_subnet  }}"
controlPlaneEndpoint: "{{  var_vip_kub_endpoint  }}:6443"
clusterName: "{{  var_kub_name  }}"
controllerManager:
  extraArgs:
    cloud-provider: external
apiServer:
 certSANs:
 - {{  var_vip_kub_vip  }}
 - {{  var_vip_kub_endpoint  }} 

When running Ansible, the file will be copied to the desired destination using the values defined in the main.yml variables. The details of these values and associated explanations will be provided in a future article, but it is at this level that we define which version of Kubernetes we want to deploy. As of writing this article, K8S is available in version 1.30.1, but I prefer to stay on the latest release of the 1.29 branch, which is 1.29.5. We will have the opportunity to describe an update operation later.

Other variables are available, including those for preparing the network configuration with Cilium deployment, configuring Traefik to expose applications, and some basic parameters for VMware add-ons.

Note that for these latter items, a password is present in plain text, which is not good at all. Ideally, it should be handled in the same way as the inventory file, by encrypting its content using the vault function integrated into Ansible. I'll admit I was being lazy... but in a real production environment, you should never leave identification information in plain text within an Ansible configuration.

Action Management

Once the variables are loaded, Ansible will continue executing the actions described in the tasks folder, always starting with the content of the main.yml file

In this case, the purpose of the main.yml is solely to call other YAML files located within the same folder.

  
---
#Ajout du repo Kubernetes pour la récupération des paquets officiels (installation vanilla)
- name: "Repository Configuration"
  import_tasks: 01-repos.yml
  tags:
    - role_k8s_deploy.repos    

#Lancement de l'installation des prerequis
- name: "Prerequis"
  import_tasks: 02-prerequis.yml
  tags:
    - role_k8s_deploy.prerequis

#Configuration des flux réseau avec ouverture des ports
- name: "iptables configuration"
  import_tasks: 03-iptables.yml
  tags:
    - role_k8s_deploy.iptables 

#Installation du runtime de conteneur "containerd"
- name: "containerd installation"
  import_tasks: 04-containerd.yml
  tags:
    - role_k8s_deploy.containerd

#Création des fichiers de configuration pour le déploiement de Kubernetes
- name: "K8S configuration"
  import_tasks: 05-configure-k8s.yml
  tags:
    - role_k8s_deploy.configure-k8s    

#Configuration et installation des loadbalancer    
- name: "HAproxy configuration"
  import_tasks: 06-configure-haproxy.yml
  tags:
    - role_k8s_deploy.haproxy 

#Création de la configuration traefik
- name: "Traefik config"
  import_tasks: 08-configure-traefik.yml
  tags:
    - role_k8s_deploy.traefik
  

This is to avoid having a single file containing all the tasks to be performed. For better understanding and simpler maintainability, it is recommended to break down your deployment into sub-tasks, each described in specific files.

Task breakdown

Click the image to enlarge.

It is also important to associate tags with each action. The advantage of this is that you can use Ansible by specifying a particular tag to re-run only a portion of the commands.

This can be very useful when updating your deployment, which only affects a part of the installation. There's no need to re-run the entire role.

Get into the habit of choosing a consistent naming convention for your tags and YAML files. In my case, I prefix the YAML files with a number to simplify reading the order of actions. Similarly, my tags always refer to the root name and then have an additional extension as you go deeper into the directory structure.

If we look at the details, here is the content of the files:

01-repos.yml

  
---
#extraction de la version majeure à partir de la variable var_kub_version. La valeur sera positionnée dans une nouvelle variable "var_kub_major_version"
- name: Extract Major Version Kub
  become: yes
  set_fact:
        var_kub_major_version: "v{{  var_kub_version.split('.')[0:2] | join('.')  }}"
  tags: role_k8s_deploy.repos.setversion        

#Deploiement du fichier repos kubernetes.repo dans /etc/yum.repos.d/ via le template kubernetes.repo.j2"
- name: "install kubernetes repo"
  become: yes 
  template:
    src: kubernetes.repo.j2
    dest: "/etc/yum.repos.d/kubernetes.repo"
  tags: role_k8s_deploy.repos.deploy

This file will allow you to add Kubernetes repositories as installation sources on the photonOS VMs.

This corresponds to adding a kubernetes.repo file in /etc/yum.repos.d/kubernetes.repo

The file is built according to the template kubernetes.repo.j2 located in the templates folder, and here is its content:
  
[kubernetes]
name=Kubernetes
baseurl=https://pkgs.k8s.io/core:/stable:/{{  var_kub_major_version  }}/rpm/
enabled=1
gpgcheck=1
gpgkey=https://pkgs.k8s.io/core:/stable:/{{  var_kub_major_version  }}/rpm/repodata/repomd.xml.key
exclude=kubelet kubeadm kubectl cri-tools kubernetes-cni

With each major release of Kubernetes, a new repository is made available. Therefore, before generating the file, an Ansible task will retrieve only the major version from the variable indicated in the main.yml. This version will be used to build the repository file based on the template kubernetes.repo.j2 found in the templates folder.

02-prerequis.yml

This file will deploy a number of settings to ensure that you have operating systems compatible with the Kubernetes prerequisites.

  
---
#Désactivation de la SWARP sur tous les serveurs
- name: Disable swap (if configured).
  become: yes 
  command: swapoff -a
  tags: role_k8s_deploy.prerequis.swap

#Message de debug pour connaitre sur quel type de serveur s'exécute les actions
- debug:
    msg: "{{ tags }}"

#installation des packages sur les control plane (liste des paquets défini dans "main.yml" du dossier "defaults")
- name: Install basic packages for master
  become: yes 
  tdnf:
    update_cache: yes
    name: "{{ var_k8s_packages_master }}"
    state: present
  when: "'TAG-COOLCORP-ROLE-MASTER' in tags"
  tags: role_k8s_deploy.prerequis.packages_master

#installation des packages sur les workers (liste des paquets défini dans "main.yml" du dossier "defaults")  
- name: Install basic packages for worker
  become: yes 
  tdnf:
    update_cache: yes
    name: "{{ var_k8s_packages_worker }}"
    state: present
  when: "'TAG-COOLCORP-ROLE-WORKER' in tags"   
  tags: role_k8s_deploy.prerequis.packages_worker

#suppression des paquets inutiles ou conflictuels (liste des paquets défini dans "main.yml" du dossier "defaults")  
- name: remove non necessary packages
  become: yes 
  tdnf:
    update_cache: yes
    name: "{{ var_remove_packages }}"
    state: absent  
  tags: role_k8s_deploy.prerequis.remove-package   

#copie du binaire helm depuis le dossier "files" vers /usr/local/bin/ mais uniquement sur les control plane
- name: install helm
  become: yes
  copy:
    src: helm
    dest: /usr/local/bin/helm
    owner: "{{ var_admin_user}}"
    mode: u=rwx,g=rx,o=r  
  when: "'TAG-COOLCORP-ROLE-MASTER' in tags or 'TAG-COOLCORP-NETWORK-WEB' in tags"  
  tags: role_k8s_deploy.prerequis.helm

#reboot des machines
- name: Unconditionally reboot the machine with all defaults
  become: yes
  reboot:
  tags: role_k8s_deploy.prerequis.reboot

The first step is to disable swap. Currently, Kubernetes does not support the use of SWAP, although its consideration has been in beta since version 1.28. At the time of writing this article, it is still recommended to disable swap. It can negatively interfere with resource management and the predictability offered by K8S for container orchestration.

In the example cited here, the swapoff -a instruction is directly called via the command module of Ansible. This module should be used sparingly because, as it stands, it does not allow the action to be idempotent, meaning reproducible without modification. One of the many advantages of Ansible is its ability to ensure that the configuration of an asset corresponds to a specific state. This state is described in the YAML file, and normally Ansible only makes changes if they are necessary.

To achieve this, it relies on modules that can determine whether a particular configuration is already in place or needs to be modified. The command module simply executes instructions; by default, these instructions will always be executed, and Ansible will assume that something has been changed... even if that something was already configured correctly.

For example, here, each time the playbook is run, Ansible will consider that it needs to disable swap. This isn't problematic in this case because re-entering the command, even if swap is already disabled, doesn't cause an error, but this isn't always possible. Furthermore, Ansible's output will be misleading, as it will suggest that changes have been made.

To avoid this, you can add execution conditions for the command module or use a script. For example, you could first query the status of something and then, based on the returned value, decide whether to execute the command or not. I haven't gone that far in my usage, but be aware that it remains a good practice to do this when a module is not available to handle your specific need.

In this case, there is a module for managing swap that allows you to avoid using a simple command, but this module is not compatible with PhotonOS.

Next, we install the basic packages. In this case, and thanks to the tag present on the VMs, it's possible to distinguish between the different server roles. Thus, some packages are only deployed on the control plane, others on the worker nodes, and still others only on the load balancers. You can find the list of these packages in the main.yaml file in the defaults directory.

Note that the "linux" package, which corresponds to the base kernel in PhotonOS, is installed on all nodes. This will disable the use of the optimized kernel for ESXi if it was selected during installation (see this article). This is necessary for the proper functioning of Cilium (the chosen network layer).

For each package, this would involve going to each server and typing tdnf install nom_package.

We also remove unnecessary packages.

Next, we install the necessary third-party binaries. In this case, only helm. Helm is a package manager for Kubernetes; it simplifies the deployment of certain applications. Instead of having to manipulate all the required objects with one or more YAML files, Helm allows you to install software in a similar way to a simple OS package using the helm install command. We will use it later. Simply download the Linux version from the vendor's website and place it in the files directory of the Ansible role tree so that it can be used later.

Finally, we reboot the servers to ensure that all prerequisites are loaded for the next steps.

03-iptables.yml

Now comes the part about opening network streams. The nodes in the cluster need to communicate with each other, and some of them also need to be accessible from the outside on certain ports, such as the control plane, which must expose the K8S API.

All of this is very easy thanks to the iptables module in Ansible.

  
---
#Ouverture du post SSH
- name: Open SSH port
  become: yes 
  iptables:
   chain: INPUT
   destination_port: 22
   protocol: tcp
   jump: ACCEPT
  tags: role_k8s_deploy.iptables_ssh

#Usage du mode nft de iptable
- name: iptables get binary
  become: yes 
  #command: update-alternatives --set iptables /usr/sbin/iptables-legacy
  command: update-alternatives --set iptables /usr/sbin/iptables-nft
  register: iptables_alternatives

#Autoriser ICMP
- name: Autorise ICMP
  become: yes 
  iptables:
   chain: INPUT
   protocol: icmp
   jump: ACCEPT
  tags: role_k8s_deploy.iptables_ping

#Ouverture du port de l'agent Kubelet
- name: Open iptable port for kubelet port 
  become: yes 
  iptables:
   chain: INPUT
   destination_port: "{{ var_kubelet_port }}"
   protocol: tcp
   jump: ACCEPT
  tags: role_k8s_deploy.iptables_kubelet

#Ouverture du port UDP pour l'usage de VXLAN par Cilium
- name: Open iptable UDP vxlan port for cilium
  become: yes 
  iptables:
   chain: INPUT
   destination_port: "{{ var_cilium_udp_vxlan_port }}"
   protocol: udp
   jump: ACCEPT
  tags: role_k8s_deploy.iptables_cilium_vxlan-udp 
  when: "'TAG-COOLCORP-ROLE-MASTER' in tags or 'TAG-COOLCORP-ROLE-WORKER' in tags"   

#Ouverture du port TCP pour les health check réalisés par Cilium
- name: Open iptable TCP health port for cilium
  become: yes 
  iptables:
   chain: INPUT
   destination_port: "{{ var_cilium_tcp_healt_port }}"
   protocol: tcp
   jump: ACCEPT
  tags: role_k8s_deploy.iptables_cilium_health-tcp 
  when: "'TAG-COOLCORP-ROLE-MASTER' in tags or 'TAG-COOLCORP-ROLE-WORKER' in tags"   

#Ouverture du port TCP suplementaire pour Cilium
- name: Open iptable TCP obser port for cilium
  become: yes 
  iptables:
   chain: INPUT
   destination_port: "{{ var_cilium_tcp_obser_port }}"
   protocol: tcp
   jump: ACCEPT
  tags: role_k8s_deploy.iptables_cilium_obser-tcp 
  when: "'TAG-COOLCORP-ROLE-MASTER' in tags or 'TAG-COOLCORP-ROLE-WORKER' in tags"  
  
  #Ouverture du port TCP suplementaire pour Cilium
  - name: Open iptable TCP obser port for cilium
    become: yes 
    iptables:
     chain: INPUT
     destination_port: "{{ var_cilium_tcp_relay_port }}"
     protocol: tcp
     jump: ACCEPT
    tags: role_k8s_deploy.iptables_cilium_obser-tcp 
    when: "'TAG-COOLCORP-ROLE-MASTER' in tags or 'TAG-COOLCORP-ROLE-WORKER' in tags"   
  
  #Ouverture du port TCP suplementaire pour Cilium
  - name: Open iptable TCP hubble-peer port for cilium
    become: yes 
    iptables:
     chain: INPUT
     destination_port: "{{ var_cilium_tcp_hubblepeer_port }}"
     protocol: tcp
     jump: ACCEPT
    tags: role_k8s_deploy.iptables_hubblepeer-tcp 
    when: "'TAG-COOLCORP-ROLE-MASTER' in tags or 'TAG-COOLCORP-ROLE-WORKER' in tags"       

#Ouverture du port TCP de l' API Serveur pour les control plane
- name: Open iptable kub API port
  become: yes 
  iptables:
   chain: INPUT
   destination_port: "{{ var_kube_api_port }}"
   protocol: tcp
   jump: ACCEPT
  when: "'TAG-COOLCORP-ROLE-MASTER' in tags or 'TAG-COOLCORP-ROLE-HAPROXY' in tags"
  tags: role_k8s_deploy.iptables_kube-api-port 

#Ouverture du port etcd pour les control plane
- name: Open iptable etcd API port
  become: yes 
  iptables:
   chain: INPUT
   destination_port: "{{ var_etcd_port  }}"
   protocol: tcp
   jump: ACCEPT
  when: "'TAG-COOLCORP-ROLE-MASTER' in tags" 
  tags: role_k8s_deploy.iptables_kube-api-port 

#Ouverture du port etcd pour les control plane 
- name: Open iptable etcd API port member
  become: yes 
  iptables:
   chain: INPUT
   destination_port: "{{ var_etcd_member_port  }}"
   protocol: tcp
   jump: ACCEPT
  when: "'TAG-COOLCORP-ROLE-MASTER' in tags" 
  tags: role_k8s_deploy.iptables_kube-api-port   

#Ouverture du port 80 pour les control planee et les nlb
- name: Open iptable 80
  become: yes 
  iptables:
   chain: INPUT
   destination_port: "80"
   protocol: tcp
   jump: ACCEPT
  when: "'TAG-COOLCORP-ROLE-MASTER' in tags or 'TAG-COOLCORP-ROLE-HAPROXY' in tags"
  tags: role_k8s_deploy.iptables.http 

#Ouverture du port 443 pour les control plane et les nlb
- name: Open iptable 443
  become: yes 
  iptables:
   chain: INPUT
   destination_port: "443"
   protocol: tcp
   jump: ACCEPT
  when: "'TAG-COOLCORP-ROLE-MASTER' in tags or 'TAG-COOLCORP-ROLE-HAPROXY' in tags"
  tags: role_k8s_deploy.iptables.https  

#Ouverture du port 443 pour les worker en dmz
- name: Open iptable 443
  become: yes 
  iptables:
   chain: INPUT
   destination_port: "443"
   protocol: tcp
   jump: ACCEPT
  when: "'TAG-COOLCORP-ROLE-WORKER' in tags and 'TAG-COOLCORP-NETWORK-WEB' in tags"
  tags: role_k8s_deploy.iptables.dmz-https  

#Ouverture du port 80 pour les worker en dmz
- name: Open iptable 80
  become: yes 
  iptables:
   chain: INPUT
   destination_port: "80"
   protocol: tcp
   jump: ACCEPT
  when: "'TAG-COOLCORP-ROLE-WORKER' in tags and 'TAG-COOLCORP-NETWORK-WEB' in tags"
  tags: role_k8s_deploy.iptables.dmz-http   

#ouverture des ports de service node 
- name: Open node service port
  become: yes 
  iptables:
   chain: INPUT
   destination_port: "{{ var_node_service_port }}"
   protocol: tcp
   jump: ACCEPT
  when: "'TAG-COOLCORP-ROLE-WORKER' in tags"  
  tags: role_k8s_deploy.iptables_nodeservice

#Sauvegarde de la conf iptable
- name: save iptables
  become: yes 
  shell: iptables-save > /etc/systemd/scripts/ip4save
  register: iptables_alternatives
  tags: role_k8s_deploy.iptables.backup

#reboot
- name: Unconditionally reboot the machine with all defaults
  become: yes
  reboot:
  tags: role_k8s_deploy.prerequis.reboot

For each stream, you only need to specify the protocol, the application chain (INPUT/OUTPUT/FORWARD), and the expected action.

The final task is to save the iptables configuration to ensure that it is reapplied on each server reboot. Again, the shell module is used, and as with the command module, we could offer a better solution in terms of playbook reusability.

Note also the use of the command module to execute update-alternatives --set iptables /usr/sbin/iptables-nft.

nft for Netfilter Tables is another engine for filtering and manipulating Linux kernel packets; it is more modern and flexible than the traditional iptables engine.

This point is important because it relates to the network driver chosen for Kubernetes (here, Cilium). Depending on the version and type of the driver, it may be necessary to switch between different modes.

Here is a summary of the streams to open:

Stream Source Destination Port Role
SSH any All servers TCP 22 SSH access
ICMP any any ICMP Allow ping
Kubelet All servers All servers TCP 10250 Communication on Kubelet agents
VXLAN All servers All servers UDP 8472 Network communication protocol for Cilium
CILIUM HEALT All servers All servers TCP 4240 Required for Cilium
CILIUM OBSER All servers All servers TCP 4222 Required for Cilium
API any Control plane servers / Load Balancing servers
TCP 6443 Access to the KUB API
ETCD Control plane servers Control plane servers TCP 2379 ETCD replication
ETCD Control plane servers Control plane servers TCP 2380 ETCD replication
NODE PORT any All servers TCP 30000:32767 Ports for Node port type services
TRAEFIK any All servers intended to host a Traefik instance
Load Balancing server
TCP 80
TCP 443
Application exposure

All these ports are defined in the variable file. Note that this matrix should be adapted based on your needs and constraints.

One good practice is to limit access to the API. This is important because the API allows control of the cluster, so it should only be exposed to necessary components (deployment and monitoring).

The same applies to SSH access. Here, I am not filtering further, but in a production environment, it is essential that access to the OS layer is extremely controlled, preferably using a bastion host.

You can also rely on other security components to filter traffic outside of the OS. In any case, it is very important to define your matrix carefully before the project and to restrict yourself to opening only what is necessary.

In the deployed architecture, there are nodes in the DMZ. These nodes must communicate at least with the control plane, and depending on the "add-ons" used, they may require additional port openings, as is the case here with the use of Cilium.

We will have the opportunity to discuss this further, but the kubelet are the K8S agents present on each node. Their role is to start the basic cluster containers and report the host status. It is important that these agents can communicate with each other, especially from nodes to the control plane.

Kubernetes components: source (https://www.codemotion.com/magazine/devops/cloud/discover-kubelet-and-why-its-important-for-kubernetes/)

Click the image to enlarge.

04-containerd.yml

As I mentioned during the presentation of the Kubernetes architecture to be deployed, K8S requires a container runtime that meets the standard OCI (Open Container Initiative) and is compatible with CRI (Container Runtime Interface).

In this case, containerd will be chosen. Even though it is present by default in photonOS, in this example, it is preferable to download the binaries directly from the official website. There is a strong dependency between the version of Kubernetes and the version of containerd. It is crucial to respect the compatibility matrix. Since Kubernetes is deployed here in a vanilla version and therefore independently of the default OS repository, it is preferable to do the same with containerd to avoid being blocked by a version conflict.

  
---
#Récupération des binaire containerd et décompression de ces dernier dans /usr
- name: Download and extract containerd
  become: yes 
  ansible.builtin.unarchive:
    src: "{{ var_containerd_binary }}"
    dest: /usr
    remote_src: yes
  tags: role_k8s_deploy.containerd.containerd
  when: "'TAG-COOLCORP-ROLE-MASTER' in tags or 'TAG-COOLCORP-ROLE-WORKER' in tags" 

#Création du fichier de service pour gérer le démarrage et l'arret de containerd : utilisation du template containerd.service.j2
- name: "Configure containerd service"
  become: yes 
  template:
    src: containerd.service.j2
    dest: "/usr/lib/systemd/system/containerd.service"
  register: containerd_service_file
  tags: role_k8s_deploy.containerd.contrainerd-service
  when: "'TAG-COOLCORP-ROLE-MASTER' in tags or 'TAG-COOLCORP-ROLE-WORKER' in tags" 

#forcer le refresh de la config systemd pour prendre en compte le fichier de service créé précedemment
- name: container reread config
  become: yes  
  ansible.builtin.systemd:
    daemon_reexec: yes
  when: containerd_service_file is changed 

#Activer et démarrer le service containerd  
- name: enable containerd service
  become: yes 
  systemd:
    name: containerd
    state: started
    enabled: True  
  when: "'TAG-COOLCORP-ROLE-MASTER' in tags or 'TAG-COOLCORP-ROLE-WORKER' in tags"   

#Ajouter le module br_netfilter au chargement de containerd
- name: "configure br_netfilter module"
  become: yes 
  template:
    src: containerd.conf.j2
    dest: "/etc/modules-load.d/containerd.conf"
  tags: role_k8s_deploy.containerd.conf-br_netfilter
  when: "'TAG-COOLCORP-ROLE-MASTER' in tags or 'TAG-COOLCORP-ROLE-WORKER' in tags" 

#S'assurer que le module br_netfiler soit chargé
- name: Add the br_netfilter module
  become: yes 
  community.general.modprobe:
    name: br_netfilter
    state: present
  tags: role_k8s_deploy.containerd.add-br_netfilter  
  when: "'TAG-COOLCORP-ROLE-MASTER' in tags or 'TAG-COOLCORP-ROLE-WORKER' in tags" 

#Tweak du kernel pour les besoins K8S 
- name: "configure sysctl"
  become: yes 
  template:
    src: 99-kubernetes-cri.conf.j2
    dest: "/etc/sysctl.d/99-kubernetes-cri.conf"
  register: sysctl_file  
  tags: role_k8s_deploy.containerd.sysctl
  when: "'TAG-COOLCORP-ROLE-MASTER' in tags or 'TAG-COOLCORP-ROLE-WORKER' in tags" 

#Forcer le rechargement de la conf associé au kernel
- name: read sysctlconf
  become: yes 
  shell:  sysctl --system
  when: sysctl_file is changed 
  tags: role_k8s_deploy.containerd.read-sysctl

 #Generer la conf par default de containerd
- name: "configure containerd"
  become: yes 
  ansible.builtin.shell:
    cmd: containerd config default > /etc/containerd/config.toml
  register: containerd_config_file
  tags: srv_k8s.containerd.conf-containerd-config  
  when: "'TAG-COOLCORP-ROLE-MASTER' in tags or 'TAG-COOLCORP-ROLE-WORKER' in tags" 

 #Activer le support des crgroup dans la config containerd
- name: "Activate cgroup"
  become: yes
  replace:
    path: /etc/containerd/config.toml
    regexp: 'SystemdCgroup\s*=\s*false'
    replace: 'SystemdCgroup = true'
  when: "'TAG-COOLCORP-ROLE-MASTER' in tags or 'TAG-COOLCORP-ROLE-WORKER' in tags"
  tags: srv_k8s.containerd.conf-containerd-config         

 #Redemarrer containerd
- name: enable containerd service
  become: yes 
  systemd:
    name: containerd
    state: restarted 
  when: containerd_config_file is changed   

 #Activer les agents kubelet
- name: enable kubelet service
  become: yes 
  systemd:
    name: kubelet
    state: started
    enabled: True
  when: "'TAG-COOLCORP-ROLE-MASTER' in tags or 'TAG-COOLCORP-ROLE-WORKER' in tags"     

       

The service file will be generated from the template containerd.service.j2 located in the templates folder, so that systemctl can start containerd.

Here is the content of the template:

  
[Unit]
Description=containerd container runtime
Documentation=https://containerd.io
After=network.target
[Service]
ExecStartPre=-/sbin/modprobe overlay
ExecStart=/usr/bin/containerd
Restart=always
RestartSec=5
KillMode=process
Delegate=yes
OOMScoreAdjust=-999
LimitNOFILE=1048576
# Having non-zero Limit*s causes performance problems due to accounting overhead
# in the kernel. We recommend using cgroups to do container-local accounting.
LimitNPROC=infinity
LimitCORE=infinity
TasksMax=infinity
[Install]
WantedBy=multi-user.target

This is not sufficient on its own, as other parameters are required, such as enabling certain kernel modules, particularly br_netfilter.

A specific configuration file containerd.conf, created from the template containerd.conf.j2 in the templates folder, is generated and placed in /etc/modules-load.d/

The content is very basic, as it only contains this:

  
br_netfilter

The kernel attributes must also be modified. Usually, the sysctl tool is used, but we will use a template 99-kubernetes-cri.conf.j2 to define the desired values. The generated file 99-kubernetes-cri.conf is then read by sysctl (here, the Ansible shell module is used...the same comment applies as for the command module).

The content of the file 99-kubernetes-cri.conf, placed in /etc/sysctl.d/, is very simple and only serves to enable the kernel's routing functions.

  
  net.ipv4.ip_forward = 1
  net.bridge.bridge-nf-call-ip6tables = 1
  net.bridge.bridge-nf-call-iptables = 1
  net/bridge/bridge-nf-call-arptables = 1
  

The configuration of containerd must also, initially, be generated with the default configuration using the command containerd config default > /etc/containerd/config.toml, and then supplemented with the activation of cgroup usage.

Cgroups, for control groups, are a Linux kernel feature that limits, isolates and monitors the resource usage (CPU, memory, disk, network) of processes. It is a key function for containerization, especially for Kubernetes, which, through containerd, manages the allocation of resources to the different containers running on the cluster.

The replace module used by Ansible will ensure that the value SystemdCgroup is equal to true in the configuration file /etc/containerd/config.toml generated previously.

Once finished, it is possible to start containerd, but also the famous agents kubelet. Even if the cluster is not yet deployed, the agents are already in place.

Conclusion

All nodes are now ready and have all the prerequisites to be integrated into a Kubernetes cluster.

But before that, it will be necessary to continue the Ansible playbook with tasks for preparing the cluster configuration files, including kubeadm. This point will be addressed later.

This article is not intended to be a detailed Ansible tutorial, but I hope it provides a good overview of how to use Ansible to ensure that you have all the necessary components for deploying a K8S cluster, while maintaining flexibility in choosing versions and components to install.

Note that the files described can be improved and optimized. The use of Ansible is part of a continuous improvement process, and it is always possible to revise your playbooks.


To continue the cookbook with the next step, click here