We now have a working system with several tools installed but in most cases we want these tools to work together and reach a specific state before we can start using them. Once we define what that state should look like we also need a simple way to create and tear down environments as needed.
For my use case, that state includes a Kubernetes cluster running Traefik, Prometheus and Argo CD. I automate the environment creation process with a Bash script and Terraform.
Show Bash script
#!/bin/bash
# This script automates the deployment and configuration of a Kubernetes environment using Minikube.
set -e
set -u
set -o pipefail
### script variables
DOMAIN_NAME="" # domain name for the deployment - "domain.xyz"
GITHUB_USERNAME="" # github username - "user"
GITHUB_REPOSITORY="" # github repository name - "argocd"
MINIKUBE_NODES="" # number of minikube nodes to create - "3"
TLS_CERTIFICATE_PATH="" # full path to the tls certificate - "/home/user/.tls/fullchain.crt"
TLS_PRIVATE_KEY_PATH="" # full path to the tls private key - "/home/user/.tls/tls.key"
SSH_PRIVATE_KEY_PATH="" # full path to the ssh private key - "/home/user/.ssh/id_ed25519"
### color variables
GRAY=$'\033[0;90m'
RED=$'\033[0;91m'
GREEN=$'\033[0;92m'
YELLOW=$'\033[0;93m'
BLUE=$'\033[0;94m'
MAGENTA=$'\033[0;95m'
CYAN=$'\033[0;96m'
WHITE=$'\033[0;97m'
RESET=$'\033[0m'
### preflight checks
PREFLIGHT_CHECKS_FAIL="false"
if [[ "${EUID}" -eq 0 ]]; then
printf "%sERROR:%s script running as root\n" "${RED}" "${RESET}"
exit 1
fi
BINARIES=(
docker
minikube
terraform
helm
kubectl
)
for i in "${BINARIES[@]}"; do
if ! command -v "${i}" > /dev/null 2>&1; then
PREFLIGHT_CHECKS_FAIL="true"
printf "%sERROR:%s %s is not installed\n" "${RED}" "${RESET}" "${i}"
fi
done
VARIABLES=(
DOMAIN_NAME
GITHUB_USERNAME
GITHUB_REPOSITORY
MINIKUBE_NODES
TLS_CERTIFICATE_PATH
TLS_PRIVATE_KEY_PATH
SSH_PRIVATE_KEY_PATH
)
for i in "${VARIABLES[@]}"; do
if [[ -z "${!i:-}" ]]; then
PREFLIGHT_CHECKS_FAIL="true"
printf "%sERROR:%s variable \"%s\" is not set\n" "${RED}" "${RESET}" "${i}"
fi
done
FILES=(
TLS_CERTIFICATE_PATH
TLS_PRIVATE_KEY_PATH
SSH_PRIVATE_KEY_PATH
)
for i in "${FILES[@]}"; do
VALUE="${!i}"
if [[ -n "${VALUE}" && ! -f "${VALUE}" ]]; then
PREFLIGHT_CHECKS_FAIL="true"
printf "%sERROR:%s %s file does not exist\n" "${RED}" "${RESET}" "${VALUE}"
fi
done
if [[ "${PREFLIGHT_CHECKS_FAIL}" == "true" ]]; then
exit 1
fi
### reset
for i in {5..1}; do
printf "%s%s%s\n" "${CYAN}" "$i" "${RESET}"
sleep 1
done
if [[ -d "${HOME}/minikube" ]]; then
rm -rf "${HOME}/minikube"
fi
mkdir "${HOME}/minikube"
mkdir "${HOME}/minikube/values"
cd "${HOME}/minikube"
### helm values
cat << 'EOF' > values/traefik.yaml
deployment:
replicas: 2
ingressClass:
enabled: true
isDefaultClass: true
name: traefik
providers:
kubernetesCRD:
ingressClass: traefik
kubernetesIngress:
ingressClass: traefik
logs:
access:
enabled: true
metrics:
prometheus:
service:
enabled: true
serviceMonitor:
enabled: true
ports:
web:
nodePort: 31080
redirections:
entryPoint:
to: websecure
scheme: https
websecure:
asDefault: true
nodePort: 31443
tlsStore:
default:
defaultCertificate:
secretName: default-tls
service:
type: NodePort
resources:
requests:
cpu: "100m"
memory: "128Mi"
limits:
cpu: "1000m"
memory: "1024Mi"
affinity:
podAntiAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
- labelSelector:
matchLabels:
app.kubernetes.io/name: '{{ template "traefik.name" . }}'
app.kubernetes.io/instance: '{{ .Release.Name }}-{{ include "traefik.namespace" . }}'
topologyKey: kubernetes.io/hostname
EOF
cat << EOF > values/kube-prometheus-stack.yaml
crds:
enabled: false
defaultRules:
disabled:
Watchdog: true
alertmanager:
ingress:
enabled: true
ingressClassName: traefik
hosts:
- alertmanager.${DOMAIN_NAME}
alertmanagerSpec:
resources:
requests:
cpu: "100m"
memory: "128Mi"
limits:
cpu: "1000m"
memory: "1024Mi"
grafana:
enabled: false
kubeControllerManager:
enabled: false
kubeEtcd:
enabled: false
kubeScheduler:
enabled: false
prometheusOperator:
kubeletEndpointsEnabled: false
kubeletEndpointSliceEnabled: true
prometheus:
ingress:
enabled: true
ingressClassName: traefik
hosts:
- prometheus.${DOMAIN_NAME}
prometheusSpec:
serviceMonitorSelectorNilUsesHelmValues: false
retention: 30d
resources:
requests:
cpu: "100m"
memory: "128Mi"
limits:
cpu: "1000m"
memory: "1024Mi"
serviceDiscoveryRole: "EndpointSlice"
EOF
cat << EOF > values/argo-cd.yaml
global:
domain: argocd.${DOMAIN_NAME}
configs:
params:
server.insecure: true
server:
ingress:
enabled: true
ingressClassName: traefik
EOF
### terraform manifests
cat << 'EOF' > terraform.tf
terraform {
required_version = ">= 1.8.0"
required_providers {
helm = {
source = "hashicorp/helm"
version = "3.1.1"
}
kubernetes = {
source = "hashicorp/kubernetes"
version = "3.0.1"
}
}
}
EOF
cat << 'EOF' > providers.tf
provider "helm" {
kubernetes = {
config_path = "~/.kube/config"
}
}
provider "kubernetes" {
config_path = "~/.kube/config"
}
EOF
cat << EOF > traefik.tf
resource "kubernetes_namespace_v1" "traefik" {
metadata {
name = "traefik"
}
}
resource "helm_release" "traefik" {
chart = "traefik"
name = "traefik"
namespace = kubernetes_namespace_v1.traefik.id
repository = "https://traefik.github.io/charts"
values = [file("values/traefik.yaml")]
version = "38.0.1"
timeout = 600
max_history = 10
}
resource "kubernetes_secret_v1" "default_tls" {
metadata {
name = "default-tls"
namespace = kubernetes_namespace_v1.traefik.id
}
data = {
"tls.crt" = file("${TLS_CERTIFICATE_PATH}")
"tls.key" = file("${TLS_PRIVATE_KEY_PATH}")
}
type = "kubernetes.io/tls"
}
EOF
cat << 'EOF' > kube-prometheus-stack.tf
resource "kubernetes_namespace_v1" "monitoring" {
metadata {
name = "monitoring"
}
}
resource "helm_release" "prometheus_operator_crds" {
chart = "prometheus-operator-crds"
name = "prometheus-operator-crds"
namespace = kubernetes_namespace_v1.monitoring.id
repository = "https://prometheus-community.github.io/helm-charts"
version = "25.0.1"
timeout = 600
max_history = 10
}
resource "helm_release" "kube_prometheus_stack" {
chart = "kube-prometheus-stack"
name = "kube-prometheus-stack"
namespace = kubernetes_namespace_v1.monitoring.id
repository = "https://prometheus-community.github.io/helm-charts"
values = [file("values/kube-prometheus-stack.yaml")]
version = "80.12.0"
timeout = 600
max_history = 10
}
EOF
cat << EOF > argo-cd.tf
resource "kubernetes_namespace_v1" "argocd" {
metadata {
name = "argocd"
}
}
resource "helm_release" "argocd" {
chart = "argo-cd"
name = "argo-cd"
namespace = kubernetes_namespace_v1.argocd.id
repository = "https://argoproj.github.io/argo-helm"
values = [file("values/argo-cd.yaml")]
version = "9.2.4"
timeout = 600
max_history = 10
}
resource "kubernetes_secret_v1" "github" {
metadata {
name = "github"
namespace = kubernetes_namespace_v1.argocd.id
labels = {
"argocd.argoproj.io/secret-type" = "repository"
}
}
data = {
url = "ssh://git@github.com/${GITHUB_USERNAME}/${GITHUB_REPOSITORY}.git"
sshPrivateKey = file("${SSH_PRIVATE_KEY_PATH}")
}
type = "Opaque"
}
EOF
### setup
minikube delete || true
minikube start --driver="docker" --nodes="${MINIKUBE_NODES}" --addons="metrics-server"
terraform init
terraform apply -auto-approve \
-target="helm_release.prometheus_operator_crds"
terraform apply -auto-approve
### outputs
printf "%sINFO:%s the password for ArgoCD is %s\n" "${CYAN}" "${RESET}" "$(kubectl get secret -n argocd argocd-initial-admin-secret -o jsonpath='{.data.password}' | base64 --decode)"To run the script, you need:
- a domain with
Arecords pointing to your system’s local IP address - a wildcard TLS certificate
- a GitHub account with at least one repository
- an SSH key configured in the GitHub account
Before running the script, make sure to edit it and update the following variables..
DOMAIN_NAME="" # domain name for the deployment - "domain.xyz"
GITHUB_USERNAME="" # github username - "user"
GITHUB_REPOSITORY="" # github repository name - "argocd"
MINIKUBE_NODES="" # number of minikube nodes to create - "3"
TLS_CERTIFICATE_PATH="" # full path to the tls certificate - "/home/user/.tls/fullchain.crt"
TLS_PRIVATE_KEY_PATH="" # full path to the tls private key - "/home/user/.tls/tls.key"
SSH_PRIVATE_KEY_PATH="" # full path to the ssh private key - "/home/user/.ssh/id_ed25519"
In summary, the script first performs a few preflight checks to ensure everything is in order, it then generates Terraform manifests in the ${HOME}/minikube directory and finally applies them in two stages to avoid dependency errors.
Caution
When you run the script it will delete all existing Minikube clusters and contents from the
${HOME}/minikubedirectory.
In the following sections we will see more details about some key components.
Minikube
We use Minikube with the Docker driver. During installation we created a custom Docker network named minikube allowing the nodes to receive predictable IP addresses.
The number of nodes to be created is defined by the MINIKUBE_NODES variable in the script.
Some of the workloads we deploy require at least 2 nodes otherwise some pods will not be scheduled and remain in a Pending state.
HAProxy
To access HTTP workloads running on Minikube we use the HAProxy we installed on our system.
It listens on ports 80 and 443 of the host system and forwards all incoming traffic to the minikube Docker network on ports 31080 and 31443 respectively. For this setup to work, the Kubernetes Ingress Controller (Istio, Traefik, etc) must be configured to create NodePort services on those ports.
We have configured HAProxy with active TCP healthchecks so it routes traffic only to backends that have a server running. I have tried some alternatives to HAProxy but none of them could do this simple thing out of the box.. for example NGINX only offers passive TCP healthchecks in it’s free version and for active TCP healthchecks we need to use their paid version. I also tried Traefik but as of today it doesn’t support any TCP healthchecks for it’s backends.
In general HAProxy just works, we can access it’s dashboard in port 8404 and view it’s logs by doing..
sudo journalctl -u haproxy -f
One alternative approach to the whole “reverse proxy in front of Minikube” thing would be to use MetalLB but I could not make it work consistently with Minikube. That said, it’s been some time since I last tested it and it may work great now.
One disadvantage of this setup is that ports 80 and 443 of the host system are always bound to HAProxy even when Minikube is not running. If this is something that bothers you, disable the autostart of the HAProxy systemd service and start it only when you need it or even better use a different network interface for HAproxy.
Traefik
As discussed in the HAProxy section, our Ingress Controller needs to use NodePort services on ports 31080 and 3144 so we configure this using the Traefik Helm chart values file.
Another thing we configure is a Kubernetes secret on the traefik namespace with the certificate for our domain. Traefik will use this secret to create a TLSStore which will handle TLS for our domain automatically.
After the installation an IngressClass with the name “traefik” will be created and it will be configured to be the default IngressClass of the cluster. This means that we don’t have to set the ingressClassName: field in every Ingress resource we create.
If in the future we decide to use multiple Ingress Controllers we can use this field to select which one will handle each Ingress in a case by case basis..
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
# [...]
spec:
ingressClassName: "traefik"
# [...]
One final note, Traefik evaluates routing rules based on their length and not based on their “specificity” meaning that if we create an Ingress for the host blue.domain.xyz and another one for the host *.domain.xyz the rules that will be created will be..
Host('blue.domain.xyz'HostRegexp('{subdomain:[a-zA-Z0-9-]+}.domain.xyz')
The second rule is longer so it will be evaluated first and since it will match the request to blue.domain.xyz it will always take precedence over the more specific route.
To solve this we can manually set the priority on the Ingress using an annotation..
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
# [...]
annotations:
traefik.ingress.kubernetes.io/router.priority: "1"
# [...]
spec:
# [...]
The priority can be any value between 1 and 1000 (higher is better). We could either annotate the “wildcard” Ingress with a low priority or annotate the “non-wildcard” Ingress with a high priority, either way our problem will be solved.
Prometheus
We install 2 Helm charts related to Prometheus, the prometheus-operator-crds and the kube-prometheus-stack.
We mostly use default values for both except from the way the Prometheus operator detects ServiceMonitor resources. The default behavior is for Prometheus to scrape a ServiceMonitor only when it has matching labels. This is useful if we have multiple Prometheus operators on the same cluster.
In summary the way it works is the following..
- if
serviceMonitorSelectorNilUsesHelmValues: falseis configured in the values file we need to runkubectl get prometheuses.monitoring.coreos.com -n monitoring -o yaml | grep -A8 serviceMonitorSelectorand add the output as labels to ourServiceMonitor - if
serviceMonitorSelectorNilUsesHelmValues: trueis configured in the values file theServiceMonitorwill be scraped automatically
In either case the service monitors can be in any namespace.
After the installation we can access Prometheus at https://prometheus.${DOMAIN_NAME} and Alertmanager at https://alertmanager.${DOMAIN_NAME}.
Argo CD
We install the argo-cd Helm chart and we just configure ingress related settings through the values file. Additionally we create a Kubernetes secret to store the GitHub account credentials and repository information.
The web interface is available at https://argocd.${DOMAIN_NAME}, to login use admin as the username and the output of the following command as the password..
kubectl get secret -n argocd argocd-initial-admin-secret -o jsonpath="{.data.password}" | base64 --decode && echo
Troubleshooting
Usually everything works fine but if there is any issue, start troubleshooting the path of the requests..
- Is DNS pointing to the IP of our system?
- Does HAProxy see the backends as online?
- Do the HAProxy logs show our connection attempts?
- Have all the Helm charts installed correctly?
- Are all the pods running?
This is not an exhaustive list of everything that could have gone wrong but most likely it’s one of these things.
Ongoing Maintenance
To keep everything up to date, we periodically need to edit the Bash script and update the kubernetes and helm Terraform providers, as well as the traefik, kube-prometheus-stack, prometheus-operator-crds, and argo-cd Helm charts.
Finally, if you have not automated the process, don’t forget to generate a new TLS certificate for your domain every 90 days.