Certainly! Implementing an admission controller to prevent running singleton pods in Kubernetes, especially within an Amazon Elastic Kubernetes Service (EKS) cluster, involves several steps. Below is a comprehensive guide covering the rationale, implementation, and deployment aspects.
1. Understanding the Concepts
1.1 Kubernetes Admission Controllers
Admission Controllers are plugins in the Kubernetes API server that intercept requests to modify or validate objects during the creation, update, or deletion of Kubernetes resources. They can enforce policies, validate requests, and mutate objects before they are persisted in etcd.
There are two types of admission controllers:
- Validating Admission Controllers: Validate requests and can reject them based on custom logic.
- Mutating Admission Controllers: Modify or mutate the incoming requests before validation.
1.2 Singleton Pods
A singleton pod refers to a pod that has only a single replica running in the cluster. Singleton pods can be critical components or services that you want to ensure are always running but can also be a point of failure if they are not managed correctly. Preventing unintended singleton pods can help in enforcing desired scalability and high availability practices.
2. Rationale for Preventing Singleton Pods
Preventing singleton pods can be essential for various reasons:
- High Availability: Ensuring that critical services have multiple replicas to avoid single points of failure.
- Scalability: Enforcing minimum replica counts for applications to handle load effectively.
- Compliance: Adhering to organizational policies regarding resource availability and fault tolerance.
By implementing an admission controller to prevent singleton pods, you can enforce these best practices across your EKS cluster.
3. Implementing the Admission Controller
3.1 Approach Overview
To prevent singleton pods, we'll create a Validating Admission Webhook that inspects pod creation requests and rejects any pod that is part of a deployment, statefulset, or other controller with only one replica. This ensures that all managed pods have the desired number of replicas.
3.2 Steps to Implement
-
Develop the Webhook Server:
- Implement a server that listens for admission review requests.
- Parse the incoming pod specifications.
- Determine if the pod is part of a controller with a single replica.
- Reject the request if it violates the singleton policy.
-
Containerize the Webhook Server:
- Package the webhook server into a Docker container.
-
Deploy the Webhook Server in the Cluster:
- Create deployments and services for the webhook server.
-
Configure the Validating Webhook:
- Define a
ValidatingWebhookConfiguration resource that points to the webhook server.
-
Handle Certificates:
- Secure the webhook with TLS certificates, as Kubernetes requires HTTPS for webhooks.
3.3 Detailed Implementation
3.3.1 Developing the Webhook Server
We'll use Go for implementing the webhook server due to its strong support in the Kubernetes ecosystem.
Prerequisites:
- Go installed
- Understanding of Kubernetes API types
- Familiarity with webhooks and HTTP servers
Sample Code:
Below is a simplified example of a validating admission webhook in Go that prevents singleton pods managed by controllers with only one replica.
package main
import (
"crypto/tls"
"encoding/json"
"io/ioutil"
"log"
"net/http"
admissionv1 "k8s.io/api/admission/v1"
appsv1 "k8s.io/api/apps/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
)
type WebhookServer struct {
clientset *kubernetes.Clientset
}
func main() {
config, err := rest.InClusterConfig()
if err != nil {
log.Fatalf("Failed to get in-cluster config: %v", err)
}
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
log.Fatalf("Failed to create clientset: %v", err)
}
server := &WebhookServer{
clientset: clientset,
}
http.HandleFunc("/validate", server.validateHandler)
// Load TLS certificates
tlsCert, err := tls.LoadX509KeyPair("/tls/tls.crt", "/tls/tls.key")
if err != nil {
log.Fatalf("Failed to load key pair: %v", err)
}
serverTLS := &http.Server{
Addr: ":8443",
TLSConfig: &tls.Config{Certificates: []tls.Certificate{tlsCert}},
}
log.Println("Starting webhook server on port 8443")
log.Fatal(serverTLS.ListenAndServeTLS("", ""))
}
func (wh *WebhookServer) validateHandler(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
http.Error(w, "could not read request", http.StatusBadRequest)
return
}
var admissionReviewReq admissionv1.AdmissionReview
if err := json.Unmarshal(body, &admissionReviewReq); err != nil {
http.Error(w, "could not parse admission review", http.StatusBadRequest)
return
}
admissionReviewResp := admissionv1.AdmissionReview{
TypeMeta: admissionReviewReq.TypeMeta,
}
podResource := metav1.GroupVersionResource{Group: "", Version: "v1", Resource: "pods"}
if admissionReviewReq.Request.Resource != podResource {
admissionReviewResp.Response = &admissionv1.AdmissionResponse{
Allowed: true,
}
writeResponse(w, admissionReviewResp)
return
}
var pod corev1.Pod
if err := json.Unmarshal(admissionReviewReq.Request.Object.Raw, &pod); err != nil {
admissionReviewResp.Response = &admissionv1.AdmissionResponse{
Allowed: false,
Result: &metav1.Status{
Message: "Could not unmarshal pod object",
},
}
writeResponse(w, admissionReviewResp)
return
}
// Identify the controller (e.g., Deployment, StatefulSet) managing this pod
ownerReferences := pod.OwnerReferences
if len(ownerReferences) == 0 {
// Standalone pod, decide if you want to allow or disallow
admissionReviewResp.Response = &admissionv1.AdmissionResponse{
Allowed: false,
Result: &metav1.Status{
Message: "Standalone pods are not allowed",
},
}
writeResponse(w, admissionReviewResp)
return
}
// For simplicity, handle only Deployments
for _, owner := range ownerReferences {
if owner.Kind == "ReplicaSet" { // Deployment owns ReplicaSet which owns Pods
rs, err := wh.clientset.AppsV1().ReplicaSets(pod.Namespace).Get(r.Context(), owner.Name, metav1.GetOptions{})
if err != nil {
admissionReviewResp.Response = &admissionv1.AdmissionResponse{
Allowed: false,
Result: &metav1.Status{
Message: "Could not get ReplicaSet",
},
}
writeResponse(w, admissionReviewResp)
return
}
deploy, err := wh.clientset.AppsV1().Deployments(pod.Namespace).Get(r.Context(), rs.OwnerReferences[0].Name, metav1.GetOptions{})
if err != nil {
admissionReviewResp.Response = &admissionv1.AdmissionResponse{
Allowed: false,
Result: &metav1.Status{
Message: "Could not get Deployment",
},
}
writeResponse(w, admissionReviewResp)
return
}
if deploy.Spec.Replicas != nil && *deploy.Spec.Replicas <= 1 {
admissionReviewResp.Response = &admissionv1.AdmissionResponse{
Allowed: false,
Result: &metav1.Status{
Message: "Deployments must have more than one replica",
},
}
writeResponse(w, admissionReviewResp)
return
}
}
// Similarly handle other controller kinds if needed
}
// If all checks pass
admissionReviewResp.Response = &admissionv1.AdmissionResponse{
Allowed: true,
}
writeResponse(w, admissionReviewResp)
}
func writeResponse(w http.ResponseWriter, ar admissionv1.AdmissionReview) {
respBytes, err := json.Marshal(ar)
if err != nil {
http.Error(w, "Could not serialize response", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(respBytes)
}
Explanation:
-
Webhook Server Initialization:
- The server initializes a Kubernetes client to interact with the cluster.
- It sets up an HTTP server listening on port
8443 with TLS.
-
Request Handling (validateHandler):
- The handler reads and unmarshals the admission review request.
- It checks if the resource is a pod.
- It inspects the pod's owner references to identify the managing controller (e.g., ReplicaSet, Deployment).
- It fetches the Deployment and checks the
replicas count.
- If the replica count is less than or equal to one, it rejects the pod creation.
-
Response:
- The server constructs an admission review response indicating whether the pod creation is allowed or denied.
Note: This is a simplified example. In production, you should handle various edge cases, support multiple controllers (e.g., StatefulSets, DaemonSets), and optimize performance (e.g., caching).
3.3.2 Containerizing the Webhook Server
Create a Dockerfile for the webhook server:
FROM golang:1.20-alpine AS builder
WORKDIR /app
COPY . .
RUN go build -o webhook-server .
FROM alpine:latest
RUN apk --no-cache add ca-certificates
WORKDIR /root/
COPY --from=builder /app/webhook-server .
COPY certs/ /tls/ # Assume certificates are stored in the certs directory
ENTRYPOINT ["./webhook-server"]
Build and Push the Docker Image:
docker build -t your-repo/webhook-server:latest .
docker push your-repo/webhook-server:latest
3.3.3 Deploying the Webhook Server in EKS
1. Create a Namespace (optional):
apiVersion: v1
kind: Namespace
metadata:
name: webhook-system
Apply it:
kubectl apply -f namespace.yaml
2. Deploy the Webhook Server:
apiVersion: apps/v1
kind: Deployment
metadata:
name: singleton-pod-webhook
namespace: webhook-system
spec:
replicas: 2
selector:
matchLabels:
app: singleton-pod-webhook
template:
metadata:
labels:
app: singleton-pod-webhook
spec:
containers:
- name: webhook-server
image: your-repo/webhook-server:latest
ports:
- containerPort: 8443
volumeMounts:
- name: webhook-certs
mountPath: /tls
readOnly: true
volumes:
- name: webhook-certs
secret:
secretName: webhook-server-cert
---
apiVersion: v1
kind: Service
metadata:
name: singleton-pod-webhook
namespace: webhook-system
spec:
ports:
- port: 443
targetPort: 8443
selector:
app: singleton-pod-webhook
Apply it:
kubectl apply -f deployment.yaml
3.3.4 Handling TLS Certificates
Kubernetes requires that webhooks use HTTPS. You can use cert-manager to automate certificate management.
1. Install cert-manager:
Follow the official cert-manager installation guide.
2. Create a Certificate and a Secret:
apiVersion: cert-manager.io/v1
kind: Certificate
metadata:
name: webhook-server-cert
namespace: webhook-system
spec:
secretName: webhook-server-cert
issuerRef:
name: letsencrypt
kind: ClusterIssuer
commonName: singleton-pod-webhook.webhook-system.svc
dnsNames:
- singleton-pod-webhook.webhook-system.svc
Apply it:
kubectl apply -f certificate.yaml
Note: Ensure that the Issuer or ClusterIssuer exists and is properly configured.
3.3.5 Configuring the Validating Webhook
Create a ValidatingWebhookConfiguration resource that tells Kubernetes to use your webhook for pod admissions.
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingWebhookConfiguration
metadata:
name: prevent-singleton-pods
webhooks:
- name: prevent.singleton.pods.example.com
rules:
- operations: ["CREATE"]
apiGroups: [""]
apiVersions: ["v1"]
resources: ["pods"]
clientConfig:
service:
name: singleton-pod-webhook
namespace: webhook-system
path: "/validate"
caBundle: <CA_BUNDLE> # To be replaced with actual CA bundle
admissionReviewVersions: ["v1"]
sideEffects: None
Obtaining the CA Bundle:
You need to base64-encode the CA certificate used to sign the webhook server's TLS certificate and insert it into the caBundle field.
kubectl get secret webhook-server-cert -n webhook-system -o jsonpath='{.data.ca\.crt}' | base64 --decode
Replace <CA_BUNDLE> with the actual base64-encoded CA certificate.
Apply the Webhook Configuration:
kubectl apply -f webhook-configuration.yaml
4. Deploying the Admission Controller on EKS
4.1 Prerequisites
- An EKS cluster up and running.
kubectl configured to interact with your EKS cluster.
- Docker and container registry access.
- cert-manager installed in your cluster (optional but recommended).
4.2 Steps to Deploy
-
Build and Push the Webhook Server Image:
- Ensure your webhook server code is ready.
- Build the Docker image.
- Push it to a container registry accessible by your EKS cluster (e.g., Amazon ECR).
-
Deploy the Webhook Server Deployment and Service:
- Apply the Kubernetes manifests for Deployment and Service.
-
Set Up TLS Certificates:
- Use cert-manager or manually create TLS certificates.
- Ensure the webhook server has access to the certificates via Kubernetes Secrets.
-
Create ValidatingWebhookConfiguration:
- Generate and apply the webhook configuration with the correct
caBundle.
-
Verify the Webhook:
- Test by attempting to create pods managed by controllers with singleton replicas to ensure they are rejected.
- Also, test creating pods with multiple replicas to ensure they are allowed.
-
RBAC Configuration:
- Ensure that the webhook server has the necessary permissions to read Deployments, ReplicaSets, etc.
- Create appropriate
Roles and RoleBindings.
Example RBAC Configuration:
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: singleton-pod-webhook-role
rules:
- apiGroups: ["apps"]
resources: ["deployments", "replicasets"]
verbs: ["get", "list", "watch"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: singleton-pod-webhook-rolebinding
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: singleton-pod-webhook-role
subjects:
- kind: ServiceAccount
name: default
namespace: webhook-system
Apply it:
kubectl apply -f rbac.yaml
4.3 Best Practices
- High Availability: Deploy multiple replicas of the webhook server to prevent downtime.
- Timeouts and Failures: Configure appropriate timeouts. If the webhook fails, Kubernetes can be configured to either allow or deny the request based on your preference.
- Monitoring and Logging: Implement robust logging and monitoring for the webhook server to track its performance and any issues.
- Performance Optimization: Ensure the webhook server is efficient to avoid latency in pod creation.
- Security: Limit the webhook's permissions to the minimum required. Secure communication with TLS, and rotate certificates regularly.
5. Testing the Admission Controller
5.1 Create a Deployment with Single Replica
Attempt to create a Deployment manifest with only one replica:
apiVersion: apps/v1
kind: Deployment
metadata:
name: single-replica-deploy
spec:
replicas: 1
selector:
matchLabels:
app: single-replica
template:
metadata:
labels:
app: single-replica
spec:
containers:
- name: nginx
image: nginx:latest
Apply it:
kubectl apply -f single-replica-deploy.yaml
Expected Result:
The creation should be denied with an error message similar to:
Error from server (Forbidden): error when creating "single-replica-deploy.yaml": admission webhook "prevent.singleton.pods.example.com" denied the request: Deployments must have more than one replica
5.2 Create a Deployment with Multiple Replicas
Modify the replicas field to 3 and apply:
spec:
replicas: 3
Apply it:
kubectl apply -f multi-replica-deploy.yaml
Expected Result:
The Deployment should be created successfully.
6. Additional Considerations
6.1 Handling Different Controllers
The sample webhook focuses on Deployments. To make it comprehensive:
- StatefulSets: Check
StatefulSet replicas.
- DaemonSets: Typically run one pod per node; handle accordingly.
- ReplicaSets: Similarly to Deployments.
Update the webhook server logic to handle these controllers based on your policies.
6.2 Exemptions and Whitelisting
Sometimes, certain pods or namespaces might require singleton behavior. Implement logic to allow exemptions, such as:
- Namespace Whitelisting: Exempt specific namespaces from the singleton enforcement.
- Label-Based Whitelisting: Allow pods with specific labels to bypass the checks.
6.3 Scalability and Performance
Ensure that the webhook server can handle the load, especially in large clusters with frequent pod creation events. Optimize the server for performance and consider using caching mechanisms where appropriate.
6.4 Error Handling and Resilience
Implement robust error handling in the webhook server to prevent unintended denials or approvals. Ensure that the server can recover gracefully from failures.
6.5 Documentation and Communication
Document the policies enforced by the admission controller and communicate them to your development and operations teams to prevent confusion and ensure compliance.
7. Conclusion
Implementing a custom Validating Admission Webhook to prevent running singleton pods in an EKS cluster involves developing a webhook server, deploying it securely within the cluster, configuring Kubernetes to use the webhook, and ensuring it adheres to best practices for security, performance, and reliability.
By enforcing such policies, you can enhance the resilience and scalability of your applications running on Kubernetes, ensuring adherence to organizational standards and mitigating risks associated with single points of failure.
References: