Tuesday, April 9, 2024

Automating Deployments with CronJobs in Google Kubernetes Engine (GKE)

In the realm of container orchestration, automation plays a pivotal role in streamlining operations. Google Kubernetes Engine (GKE) offers robust tools for managing containerized applications, and one such tool is CronJobs. CronJobs allow you to schedule and automate repetitive tasks within your Kubernetes clusters. In this guide, we'll delve into setting up CronJobs to automatically scale deployments in a GKE cluster.





Understanding CronJobs


CronJobs operate on a schedule, executing tasks at specified intervals. These tasks can range from routine maintenance chores to scaling applications based on traffic patterns. With CronJobs, you can ensure that your Kubernetes cluster is responsive to changing demands without manual intervention.

Installation and Setup

Before diving into CronJobs, ensure you have kubectl installed. You can install it using the Google Cloud CLI or package managers like apt or yum. Use the following command to install kubectl:

gcloud components install kubectl

Creating a Basic Example

Let's start with a basic example of a CronJob that scales deployments. First, connect to your GKE cluster:

gcloud container clusters get-credentials {MY-CLUSTER-NAME} --region {MY-REGION} --project {MY-PROJECT-ID}

Then, create a namespace:


kubectl create namespace test

Set the namespace for your operations:

kubectl config set-context --current --namespace=test

Now, deploy an application to scale:

kubectl create deployment kubernetes-bootcamp --image=gcr.io/google-samples/kubernetes-bootcamp:v1


Ensure the deployment is successful:

kubectl get deployments

Check the pods:

kubectl get pods


Setting Up Role-Based Access Control (RBAC)

RBAC ensures that only authorized entities can perform specific actions within the cluster. Here's a sample RBAC configuration (default.yaml) for our CronJob:

---
apiVersion: v1
kind: ServiceAccount
metadata:
  name: my-service-account-ksa
  namespace: test
---
kind: Role
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: my-service-account-ksa
  namespace: test
rules:
- apiGroups: ["apps"]
  resources:
  - deployments
  verbs: ["get", "list"]
- apiGroups: ["apps"]
  resources:
  - deployments/scale
  verbs: ["patch"]
---
kind: RoleBinding
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: my-service-account-ksa
  namespace: test
subjects:
- kind: ServiceAccount
  name: my-service-account-ksa
  namespace: test
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: my-service-account-ksa
---


Apply the RBAC configuration:

kubectl apply -f default.yaml

Configuring the CronJob

Now, let's define the CronJob itself (cron.yaml). This CronJob will scale down deployments every 7 minutes:

apiVersion: batch/v1
kind: CronJob
metadata:
  name: cronjob-test
  namespace: test
spec:
  schedule: '*/7 * * * *' # every 7 min 
  concurrencyPolicy: Forbid
  successfulJobsHistoryLimit: 3
  failedJobsHistoryLimit: 3
  jobTemplate:
    spec:
      template:
        metadata:
          annotations:
            cluster-autoscaler.kubernetes.io/safe-to-evict: "true"
        spec:
          serviceAccountName: my-service-account-ksa
          securityContext:
            runAsUser: 1001
            runAsGroup: 1001
            fsGroup: 1001
            supplementalGroups:
              - 1001
          restartPolicy: OnFailure
          containers:
            - name: kubectl
              image: docker.io/bitnami/kubectl
              imagePullPolicy: IfNotPresent
              command:
                - /bin/sh
                - -c
                - kubectl scale deployment kubernetes-bootcamp --namespace=test --replicas=0;
              resources:
                limits:
                  cpu: 100m
                  memory: 100Mi
                requests:
                  cpu: 100m
                  memory: 100Mi
              securityContext:
                allowPrivilegeEscalation: false
                capabilities:
                  drop:
                    - NET_RAW
                runAsGroup: 1001
                runAsUser: 1001


Apply the CronJob configuration:

kubectl apply -f cron.yaml

Verification and Cleanup

Monitor the CronJob's execution:

kubectl get cronjobs --watch

Check the deployments again to ensure scaling:

kubectl get deployments

Finally, if needed, delete the CronJob:

kubectl delete cronjob cronjob-test

Conclusion

CronJobs offer a powerful mechanism for automating tasks within your GKE cluster. By leveraging CronJobs, you can streamline operations, improve resource utilization, and ensure your applications remain responsive to changing demands.


References:






No comments:

Post a Comment

Virtual Threads in Java 21: Simplified Concurrency for Modern Applications

  With Java 21, Virtual Threads have redefined how we approach concurrency, offering a lightweight and efficient way to handle parallel and ...