How to stop/start an elastic cluster in AKS

Hi everyone,

I need to find a way to stop an elastic cluster for some cost savings, I am looking how to do it and start the cluster only when it's required.

could you please share some guidance for this?

Thanks a lot

Stop Elastic Cluster Script

#!/bin/bash

# Name of your Elasticsearch cluster
CLUSTER_NAME="my-elastic-cluster"
NAMESPACE="default"

# Check if kubectl is available
if ! command -v kubectl &> /dev/null
then
    echo "kubectl could not be found. Please install kubectl and ensure it's in your PATH."
    exit 1
fi

# Function to check if the cluster exists
cluster_exists() {
    kubectl get elasticsearch $CLUSTER_NAME -n $NAMESPACE &> /dev/null
    return $?
}

# Check if the cluster exists
if ! cluster_exists; then
    echo "Elasticsearch cluster $CLUSTER_NAME does not exist in namespace $NAMESPACE."
    exit 1
fi

# Update the cluster spec to scale down to 0 nodes
echo "Scaling down the Elasticsearch cluster $CLUSTER_NAME to 0 nodes..."
kubectl patch elasticsearch/$CLUSTER_NAME \
    -n $NAMESPACE \
    --type='json' \
    -p='[{"op": "replace", "path": "/spec/nodeSets/0/count", "value":0}]'

# Wait for the cluster to scale down
echo "Waiting for the cluster to scale down..."
kubectl wait --for=condition=Ready=False elasticsearch/$CLUSTER_NAME -n $NAMESPACE --timeout=10m

# Confirm the cluster is stopped
echo "Cluster $CLUSTER_NAME should now be stopped. Checking status:"
kubectl get elasticsearch/$CLUSTER_NAME -n $NAMESPACE -o jsonpath='{.status.phase}'

Start Elastic Cluster Script

#!/bin/bash

CLUSTER_NAME="my-elastic-cluster"
NAMESPACE="default"
# Number of nodes to scale to
NODE_COUNT=3

# Check if kubectl is available
if ! command -v kubectl &> /dev/null
then
    echo "kubectl could not be found. Please install kubectl and ensure it's in your PATH."
    exit 1
fi

# Function to check if the cluster exists
cluster_exists() {
    kubectl get elasticsearch $CLUSTER_NAME -n $NAMESPACE &> /dev/null
    return $?
}

# Check if the cluster exists
if ! cluster_exists; then
    echo "Elasticsearch cluster $CLUSTER_NAME does not exist in namespace $NAMESPACE."
    exit 1
fi

# Update the cluster spec to scale up to the desired number of nodes
echo "Scaling up the Elasticsearch cluster $CLUSTER_NAME to $NODE_COUNT nodes..."
kubectl patch elasticsearch/$CLUSTER_NAME \
    -n $NAMESPACE \
    --type='json' \
    -p='[{"op": "replace", "path": "/spec/nodeSets/0/count", "value":'$NODE_COUNT'}]'

# Wait for the cluster to scale up
echo "Waiting for the cluster to scale up..."
kubectl wait --for=condition=Ready elasticsearch/$CLUSTER_NAME -n $NAMESPACE --timeout=10m

# Confirm the cluster is running
echo "Cluster $CLUSTER_NAME should now be running. Checking status:"
kubectl get elasticsearch/$CLUSTER_NAME -n $NAMESPACE -o jsonpath='{.status.phase}'