Step 5: deploying third-party tools

In short
  • Principle of exposing applications hosted within the cluster.
  • Configuration of HAProxy (06-configure-haproxy.yml) as a frontend.
  • Preparation of Traefik (07-configure-traefik.yml) as an Ingress Controller.
  • The API Gateway is starting to compete with Ingress controllers.

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: load balancers are covered in Step 05 - HAProxy and Keepalived Load Balancers. The article remains online for reference.

Introduction

To fully understand the explanations that follow, it is necessary to have read the previous articles.

It is important to keep in mind the target architecture and remember that an Ansible role is proposed to prepare the servers and configurations associated with initializing a K8S cluster.

Once the virtual machines have been deployed using OpenTofu (Terraform), the structure of the Ansible role was presented.

The following articles were intended to cover Ansible actions.

At this stage, we have a set of servers integrating all the minimum requirements needed to be used within a K8S cluster.

Application exposure principle

However, the final external components are still missing, which will allow communication between applications and the cluster.

By default, a Kubernetes cluster runs in a closed circuit. If no default strategy prevents internal communications within the cluster (a point to remember for security), there is no such restriction for exchanges with the outside world.

There are some basic building blocks, such as using a service in NodePort mode and kube-proxy to expose a "Kubernetized" application outside of a cluster.

However, for large-scale and production use, it is necessary to add additional components.

    In the target architecture, we will therefore need two levels of load balancing.

  • A first level outside the cluster. This is provided by the HAproxy solution, which will allow us to have a single entry point for accessing the API and other types of traffic, redirecting them to the nodes in the cluster.
  • A second level inside the cluster. Provided by the Traefik solution, this will allow us to redirect traffic to the correct services within the cluster, which will then redirect it to the appropriate pods. This is known as an Ingress Controller.

This two-level architecture is replicated twice, for the LAN and for the DMZ, since we have decided to use a single cluster.

Rather than lengthy explanations, here's a diagram that summarizes the functionality and target.

Workflow operation

Click the image to enlarge.

It is important to note that the chosen logic is not an absolute truth. Several methodologies and tool choices are possible. Similarly, in a public cloud environment, the first level of load balancing is often provided natively, and a service object can be declared as a LoadBalancer to integrate with the cloud provider's solution.

In my case, I have chosen this schema because my goal is to minimize external load balancing (a transition to HA in VRRP is planned) and focus on internal load balancing features.

Traefik is not the only Ingress Controller. HAproxy could also fulfill this function, and we would have HAProxy both internally and externally to the cluster.

However, I particularly appreciate Traefik, which offers a modern and performant approach.

Ingress Controller

An Ingress Controller, as its name suggests, is responsible for managing Kubernetes ingress objects, which are the objects that handle exposing K8S services to external requests. It is this component that, through the use of these objects, manages the redirection of traffic within the cluster.

It is possible to use one or more Ingress Controllers within the same cluster. We can either use a single software package or declare different software packages. We will talk about Class, and the Ingress objects can be processed by a specific Class of Ingress Controller.

Each Ingress Controller brings its own specific features in addition to its basic role. It can add functionalities such as URL rewriting, load balancing, and certificate management...

Traefik will be deployed as a pod, but unlike all other pods that will run on the cluster, these will be the only ones to offer containers with ports directly attached to the hosts. This is a special use case, but we'll see it later in the Traefik configuration.

Finally, Traefik will be executed on the LAN by the control plane. This is an approach open to criticism, as best practices avoid adding dependencies and roles to the control plane. We could have chosen, as with the DMZ, to run the Traefik instances on the standard nodes.

From my perspective, this logic stems from a desire to better optimize the use of my virtual resources. Sacrificing three servers solely for the control plane in an infrastructure that will not host billions of pods feels like a waste to me.

That's why, at least on the LAN, I have chosen this organization to make better use of my control planes. The impact of this setup is that all external traffic destined for applications within the LAN will pass through one or other of the control planes.

The traffic can then be redirected internally within the cluster to a worker node containing a pod associated with the accessed application.

Regarding the DMZ, the idea of having dedicated Traefik instances is obviously motivated by security constraints.

06-configure-haproxy.yml

Let's now detail the Ansible file 06-configure-haproxy.yml and address external load balancing.

  
---
#installation de HA proxy
- name: Install haproxy
  become: yes 
  tdnf:
    update_cache: yes
    name: "haproxy"
    state: present
  when: "'TAG-COOLCORP-ROLE-HAPROXY' in tags"
  tags: role_k8s_deploy.haproxy.install

#Configuration HA proxy pour le LAN
- name: "Set haproxy LAN configuration"
  become: yes
  template:
    src: "haproxy_lan.cfg.j2"
    dest: "/etc/haproxy/haproxy.cfg"
  when: "'TAG-COOLCORP-ROLE-HAPROXY' in tags and  'TAG-COOLCORP-NETWORK-LAN' in tags"
  tags: role_k8s_deploy.haproxy.haproxy-lan-config
  notify:
      - restart haproxy

#Configuration HA proxy pour la DMZ
- name: "Set haproxy DMZ configuration"
  become: yes
  template:
    src: "haproxy_dmz.cfg.j2"
    dest: "/etc/haproxy/haproxy.cfg"
  when: "'TAG-COOLCORP-ROLE-HAPROXY' in tags and  'TAG-COOLCORP-NETWORK-WEB' in tags"
  tags: role_k8s_deploy.haproxy.haproxy-dmz-config
  notify:
      - restart haproxy

#Demarrer HA proxy
- name: "Start HA proxy"
  become: yes
  systemd:
    name: haproxy
    state: started
  when: "'TAG-COOLCORP-ROLE-HAPROXY' in tags"
  tags: role_k8s_deploy.haproxy.haproxy-service

#S'assurer que HA proxy soit actif au démarrage
- name: "Enable proxy"
  become: yes
  systemd:
    name: haproxy
    enabled: true
  when: "'TAG-COOLCORP-ROLE-HAPROXY' in tags"
  tags: role_k8s_deploy.haproxy.haproxy-service

The file is quite simple. We start by installing HAproxy on the VMs that have the tag TAG-COOLCORP-ROLE-HAPROXY. (see this article for an explanation of how to use VMware tags with Ansible).

Next, we set the configuration for HAproxy on the LAN. As with previous articles, the logic is always the same. We rely on a template located in the templates directory of the Ansible tree, which will be copied to the destination (without the .j2 extension).

During the copy process, the variables present in the template will be replaced with the values declared in the main.yml file in the defaults directory. (Feel free to revisit this section for a better understanding).

Here is the content of the template haproxy_lan.cfg.j2:

 
global
defaults
        timeout client          30s
        timeout server          30s
        timeout connect         30s

frontend k8s_master_node_front
        bind    {{ var_vip_kub_vip }}:{{ var_kube_api_port }}
        default_backend         k8s_master_node_back

backend k8s_master_node_back
        mode                    tcp
        option  tcp-check
        server                  prdk8sctp501 192.168.10.71:{{ var_kube_api_port }} check
        server                  prdk8sctp502 192.168.10.72:{{ var_kube_api_port }} check
        server                  prdk8sctp503 192.168.10.73:{{ var_kube_api_port }} check

frontend k8s_master_traefik_http_front
        bind    {{ var_vip_kub_vip }}:80
        default_backend         k8s_master_traefik_http_back

backend k8s_master_traefik_http_back
        mode                    tcp
        option  tcp-check
        server                  prdk8sctp501 192.168.10.71:80 check
        server                  prdk8sctp502 192.168.10.72:80 check
        server                  prdk8sctp503 192.168.10.73:80 check        

frontend k8s_master_traefik_https_front
        bind    {{ var_vip_kub_vip }}:443
        default_backend         k8s_master_traefik_https_back

backend k8s_master_traefik_https_back
        mode                    tcp
        option  tcp-check
        server                  prdk8sctp501 192.168.10.71:443 check
        server                  prdk8sctp502 192.168.10.72:443 check
        server                  prdk8sctp503 192.168.10.73:443 check        

The template could be improved by making the server names and IP addresses variables. This is an improvement that should be made to make the template more portable.

The goal here isn't to go into detail about HAProxy configuration, but its operation is quite simple.

We define the front-end services (port and IP) to link them to the back-end server (port and IP) to which requests are forwarded.

Since HAProxy LAN is used for load balancing the K8S API, we find the variables var_vip_kub_vip and var_kube_api_port. These variables were previously presented in the previous article, specifically for preparing the kubeadm configuration file.

This is a very basic version of the HAProxy configuration. Many other options are possible, especially regarding availability checks to ensure that the back-end servers respond correctly (just because a connection is made on a port doesn't mean the service is operational).

The HAProxy configuration in the DMZ is practically the same as for the LAN. The template haproxy_dmz.cfg.j2 used is as follows:

 
global
defaults
        timeout client          30s
        timeout server          30s
        timeout connect         30s


frontend k8s_master_traefik_http_front
        bind    {{ var_vip_kub_vip_dmz }}:80
        default_backend         k8s_master_traefik_http_back

backend k8s_master_traefik_http_back
        mode                    tcp
        option  tcp-check
        server                  prdk8snod511 192.168.5.81:80 check
        server                  prdk8snod512 192.168.5.82:80 check
      

frontend k8s_master_traefik_https_front
        bind    {{ var_vip_kub_vip_dmz }}:443
        default_backend         k8s_master_traefik_https_back

backend k8s_master_traefik_https_back
        mode                    tcp
        option  tcp-check
        server                  prdk8snod511 192.168.5.81:443 check
        server                  prdk8snod512 192.168.5.82:443 check
      

Unlike the LAN, we don't handle API load balancing because the API is not exposed in the DMZ (and that's perfectly normal).

Finally, after these Ansible actions, we ensure that the HAProxy service is activated on each server, with automatic startup in case of VM restart.

07-configure-traefik.yml

The Ansible file 07-configure-traefik.yml, which handles actions related to Traefik, is as follows:

 
---
#Création des dossier de reception des configurations
- name: Creates traefik configuration directory for admin user
  become: yes
  file:
    path: "/home/{{ var_admin_user}}/{{ var_vip_kub_endpoint }}/traefik"
    state: directory
    owner: "{{ var_admin_user}}"
    mode: 0770 
    recurse: yes
  when: "'TAG-COOLCORP-ROLE-MASTER' in tags or 'TAG-COOLCORP-NETWORK-WEB' in tags" 
  tags: role_k8s.configure-traefik.directory

#Création de la configuration traefik pour le LAN
- name: "Set traefik lan configuration"
  become: yes
  template:
    src: "traefik-config-lan.yaml.j2"
    dest: "/home/{{ var_admin_user}}/{{ var_vip_kub_endpoint }}/traefik/traefik-config-lan.yaml"
    owner: "{{ var_admin_user}}"  
    mode: 0770   
  when: "'TAG-COOLCORP-ROLE-MASTER' in tags"
  tags: role_k8s.configure-traefik.lanconfig

#Création du compte de service pour Traefik en LAN
- name: "Set traefik service lan account"
  become: yes
  template:
    src: "svc-traefik-lan.yaml.j2"
    dest: "/home/{{ var_admin_user}}/{{ var_vip_kub_endpoint }}/traefik/svc-traefik-lan.yaml"
    owner: "{{ var_admin_user}}"  
    mode: 0770   
  when: "'TAG-COOLCORP-ROLE-MASTER' in tags"
  tags: role_k8s.configure-traefik.servicelanaccount

#Création de la configuration pour le dashboard Traefik en LAN
- name: "Set traefik dashboard lan configuration"
  become: yes
  template:
    src: "traefik-lan-dashboard.yaml.j2"
    dest: "/home/{{ var_admin_user}}/{{ var_vip_kub_endpoint }}/traefik/traefik-lan-dashboard.yaml"
    owner: "{{ var_admin_user}}"  
    mode: 0770   
  when: "'TAG-COOLCORP-ROLE-MASTER' in tags"
  tags: role_k8s.configure-traefik.lan-dashboard

#Création de la configuration traefik pour la DMZ
- name: "Set traefik dmz configuration"
  become: yes
  template:
    src: "traefik-config-dmz.yaml.j2"
    dest: "/home/{{ var_admin_user}}/{{ var_vip_kub_endpoint }}/traefik/traefik-config-dmz.yaml"
    owner: "{{ var_admin_user}}"  
    mode: 0770   
  when: "'TAG-COOLCORP-ROLE-MASTER' in tags"
  tags: role_k8s.configure-traefik.dmzconfig  

#Création du compte de service pour Traefik en DMZ
- name: "Set traefik service dmz account"
  become: yes
  template:
    src: "svc-traefik-dmz.yaml.j2"
    dest: "/home/{{ var_admin_user}}/{{ var_vip_kub_endpoint }}/traefik/svc-traefik-dmz.yaml"
    owner: "{{ var_admin_user}}"  
    mode: 0770   
  when: "'TAG-COOLCORP-ROLE-MASTER' in tags"
  tags: role_k8s.configure-traefik.dmz.servicelanaccount  

#Création de la configuration pour le dashboard Traefik en DMZ
- name: "Set traefik dashboard dmz configuration"
  become: yes
  template:
    src: "traefik-dmz-dashboard.yaml.j2"
    dest: "/home/{{ var_admin_user}}/{{ var_vip_kub_endpoint }}/traefik/traefik-dmz-dashboard.yaml"
    owner: "{{ var_admin_user}}"  
    mode: 0770   
  when: "'TAG-COOLCORP-ROLE-MASTER' in tags"
  tags: role_k8s.configure-traefik.dmz-dashboard  

Initially, we simply prepare the working directories that will host the configurations.

Next, we handle the case of Traefik in the LAN.

The configuration is based on a template traefik-config-lan.yaml.j2, which contains the following:

 
image:
  name: traefik
  tag: "{{ var_version_traefik }}"
  pullPolicy: IfNotPresent
deployment:
  enabled: true
  kind: DaemonSet
  labels:
    network: lan
  podLabels:
    network: lan
providers:
  kubernetesIngress:
    labelSelector: network=lan
  kubernetesCRD:
    enabled: true
    allowCrossNamespace: false
    allowExternalNameServices: false
    allowEmptyServices: false
    namespaces:
       - {{ var_namespace_traefik_prd_lan }}
serviceAccount:
  name: "{{ var_traefik_lan_service_account }}"
logs:
    level: ERROR
hostNetwork: true
ports:
  web:
    port: 80
    ports.web.redirectTo.port: websecure
  websecure:
    port: 443
securityContext:
  capabilities:
    drop: [ALL]
    add: [NET_BIND_SERVICE]
  readOnlyRootFilesystem: true
  runAsGroup: 0
  runAsNonRoot: false
  runAsUser: 0
updateStrategy:
  rollingUpdate:
    maxSurge: 0
    maxUnavailable: 1
  type: RollingUpdate
additionalArguments:
  - "--providers.kubernetesingress.ingressclass=traefik-lan"
  - "--serversTransport.insecureSkipVerify=true"

This configuration file will subsequently be passed as an argument to Helm, the K8S package manager.

Thus, we can "customize" the Traefik deployment by first setting its version using the variable var_version_traefik.

We continue by specifying that we want Traefik to be deployed as a DaemonSet.

We will have the opportunity to discuss this further, but this type of deployment allows, among other things, to automatically add a new instance of Traefik to a new node that meets the necessary conditions for its execution.

Our goal here is to ensure that if a new control plane is deployed tomorrow, it will automatically be used to run a Traefik instance.

Next, we will address an important point.

Traefik can be installed (and used) within a K8S cluster in two ways:

  • kubernetesIngress: This is the standard integration of an Ingress Controller. With this method, there is no need to modify your cluster significantly. You define a label (here network=lan), and any Ingress object that has this label will be processed by Traefik.
  • kubernetesCRD: This is the advanced integration. CRD stands for Custom Resource Definition. This indicates that Traefik will be installed by adding new object definitions to the Kubernetes API. This will allow for more extensive configurations and simplify the use of Traefik. The disadvantage of this method is that it customizes the Kubernetes API. In an OnPrem environment, with a standard installation as described on this site, this is not a problem. However, in a public cloud environment or any "Kube As A Service" offering, it is very unlikely that you will be able to extend the Kubernetes API. Therefore, even though "Custom Resource Definitions" are used in many cases (and not just for Traefik), it is advisable to use them as little as possible. If tomorrow you want to switch to a hybrid architecture or migrate to a managed offering, you will need to stay as close as possible to the standard K8S API.

  • In our case, both integrations will be used. In most cases, I will prefer working with classic Ingress objects.

    But sometimes, to use more advanced or Traefik-specific features, I may need to use a custom object. In this latter case, I will limit the scope to a specific namespace represented by the variable var_namespace_traefik_prd_lan.

    To function, Traefik must communicate with the cluster's API, so it needs an internal service account authorized to interact with it. This account will be handled later, but its name is contained in the variable var_traefik_lan_service_account.

    Next comes the section related to what I explained earlier, namely exposing pods from Traefik directly on the host's ports, using the hostNetwork: true option.

    These same ports are defined just below. The first one, called web, listens on port 80 and has an option to automatically redirect all incoming traffic to port 443, named websecure. (And that's how you do HTTPS redirection simply and by default).

    You can define as many ports as you want, including UDP. If some of your applications need to be exposed on a port other than 80 or 443, then you will need to declare them at this level.

    Note that the names web and websecure are purely arbitrary; you can choose any names you want for the ports, but it is important to reference them correctly later.

    The rest of the options are specific to the usage in this context, and also deal with how instances will be updated in case of an upgrade. I won't go into detail.

    The last two important options are found in the additionalArguments section.

    The first line, --providers.kubernetesingress.ingressclass= traefik-lan, allows you to name the class of this ingress controller, as I explained previously.

    The second one, --serversTransport.insecureSkipVerify= true, allows Traefik to communicate in the backend with services that have invalid certificates. This is not ideal in terms of security, but it is much easier to manage. If you are able to, I encourage you not to use this option.

    The following actions defined in the Ansible file deal with the service account, which is also based on a template svc-traefik-lan.yaml.j2

     
    apiVersion: v1
    kind: ServiceAccount
    metadata:
      name: "{{ var_traefik_lan_service_account }}"
      namespace: "{{ var_namespace_traefik_prd_lan }}"
    

    As with everything else, a service account is an object. We could let Traefik create a default account, but declaring it gives us better visibility into its usage and, more importantly, avoids it being confused with the account used by the Traefik instances in the DMZ.

    Another template is then used: traefik-lan-dashboard.yaml.j2.

     
    apiVersion: traefik.io/v1alpha1
    kind: IngressRoute
    metadata:
      name: traefik-lan-dashboard
      namespace: "{{ var_namespace_traefik_prd_lan }}"
    spec:
      entryPoints:
        - websecure
      routes:
        - kind: Rule
          match: Host(`{{ var_url_traefik_lan }}`) && (PathPrefix(`/api`) || PathPrefix(`/dashboard`))
          services:
            - name: api@internal
              kind: TraefikService
          middlewares:
            - name: traefik-dashboard-lan-auth # Referencing the BasicAuth middleware
              namespace: {{ var_namespace_traefik_prd_lan }}
      tls:
         secretName: sec-certif-traefik-k8s-lan
    ---
    apiVersion: traefik.io/v1alpha1
    kind: Middleware
    metadata:
      name: traefik-dashboard-lan-auth
      namespace: {{ var_namespace_traefik_prd_lan }}
    spec:
      basicAuth:
        secret: sec-traefik-dashboard-lan-password
      

    This file will allow you to expose the dashboard provided by Traefik. It will be exposed on the URL var_url_traefik_lan, and the object will be created in var_namespace_traefik_prd_lan.

    This is a very basic dashboard, but it is very useful for getting an overview of the status of Traefik and its associated objects.

    Even though it only provides read access, it's a good idea to protect it with authentication. This is the role of the Middleware object, which, when combined with the IngressRoute object, will display a prompt requiring a login/password when accessing the URL.

    I won't go into detail at this level, but this file refers to objects located in the API branch traefik.io/v1alpha1. This is an additional API branch that doesn't exist by default, but it will be added because we will use the aforementioned Custom Resource Definition.

    For the DMZ section, it's exactly the same. Only the templates vary slightly, but their content differs very little from the LAN.

    The configuration file traefik-config-dmz.yaml.j2:

     
    image:
      name: traefik
      tag: "{{ var_version_traefik }}"
      pullPolicy: IfNotPresent
    deployment:
      enabled: true
      kind: DaemonSet
      labels:
        network: dmz
      podLabels:
        network: dmz
    providers:
      kubernetesIngress:
        labelSelector: network=dmz
      kubernetesCRD:
        enabled: true
        allowCrossNamespace: false
        allowExternalNameServices: false
        allowEmptyServices: false
        namespaces:
           - {{ var_namespace_traefik_prd_dmz }}
    serviceAccount:
      name: "{{ var_traefik_dmz_service_account }}"
    logs:
        level: ERROR
    hostNetwork: true
    ports:
      web:
        port: 80
        ports.web.redirectTo.port: websecure
      websecure:
        port: 443
    securityContext:
      capabilities:
        drop: [ALL]
        add: [NET_BIND_SERVICE]
      readOnlyRootFilesystem: true
      runAsGroup: 0
      runAsNonRoot: false
      runAsUser: 0
    updateStrategy:
      rollingUpdate:
        maxSurge: 0
        maxUnavailable: 1
      type: RollingUpdate
    additionalArguments:
      - "--providers.kubernetesingress.ingressclass=traefik-dmz"
      - "--serversTransport.insecureSkipVerify=true"
    

    The service account file svc-traefik-dmz.yaml.j2:

     
    apiVersion: v1
    kind: ServiceAccount
    metadata:
      name: "{{ var_traefik_dmz_service_account }}"
      namespace: "{{ var_namespace_traefik_prd_dmz }}"
    

    The file for the dashboard traefik-dmz-dashboard.yaml.j2:

     
    apiVersion: traefik.io/v1alpha1
    kind: IngressRoute
    metadata:
      name: traefik-dmz-dashboard
      namespace: "{{ var_namespace_traefik_prd_dmz }}"
    spec:
      entryPoints:
        - websecure
      routes:
        - kind: Rule
          match: Host(`{{ var_url_traefik_dmz }}`) && (PathPrefix(`/api`) || PathPrefix(`/dashboard`))
          services:
            - name: api@internal
              kind: TraefikService
          middlewares:
            - name: traefik-dashboard-dmz-auth # Referencing the BasicAuth middleware
              namespace: {{ var_namespace_traefik_prd_dmz }}
      tls:
         secretName: sec-certif-traefik-k8s-dmz
    ---
    apiVersion: traefik.io/v1alpha1
    kind: Middleware
    metadata:
      name: traefik-dashboard-dmz-auth
      namespace: {{ var_namespace_traefik_prd_dmz }}
    spec:
      basicAuth:
        secret: sec-traefik-dashboard-dmz-password
      

    Conclusion

    The preparation of third-party components that allow applications to be exposed outside the cluster is now complete. It's possible that not everything is clear at this stage, but more information and explanations will be provided during implementation.

    What's important to remember is the overall logic with the principle of two-level load balancing and the use of two Traefik instances.

  • One is represented by the traefik-lan Ingress Controller class. It will be deployed on the control plane and responsible for processing ingress only declared within the LAN, which is the exposure of applications internal to a company, for example (intranet).
  • The other is represented by the traefik-dmz Ingress Controller class. It will be deployed on the nodes in the DMZ and responsible for processing ingress only declared within the DMZ, which is the exposure of applications outside a company (website).

  • Each of these instances is independent of each other and does not see what its counterpart handles. They both communicate with the K8S API, but via a dedicated account and do not have the same level of visibility into the cluster.

    Once again, these architectural choices are not mandatory. You are free to implement many different schemes. This is precisely the strength of the Kubernetes ecosystem. Its modularity, even if it may seem complex at first, allows you to consider numerous scenarios and combine basic components with a wide range of third-party products that add specific features.

    In any case, it is important that you fully understand what you are doing and why you are doing it. In the age of AI, it is becoming increasingly easy to generate K8S infrastructure configurations. I myself use them more and more, but be careful about what is proposed and how you express your needs. You could end up deploying risky workflows and objects without even realizing it.

    Finally, at the time of writing this article, the API associated with Ingress is being challenged by the Gateway API, which includes new objects. Kubernetes is constantly evolving, and it is possible that the Gateway API will gradually become the new standard, or at least become the solution for handling more complex routing cases and providing better network traffic management. This may give rise to a dedicated topic.

    To continue the cookbook, click here.