Skip to content

Instantly share code, notes, and snippets.

@TheBigAleski
Last active November 25, 2024 08:18
Show Gist options
  • Save TheBigAleski/1eeaab2eb12ec01b30bd6032e1e2111e to your computer and use it in GitHub Desktop.
Save TheBigAleski/1eeaab2eb12ec01b30bd6032e1e2111e to your computer and use it in GitHub Desktop.
HTTPS Google Cloud Run function that removes auto-scaling and reduces node groups size for all GKE found in project (projectId passed either in query or body)
const functions = require('@google-cloud/functions-framework');
const container = require('@google-cloud/container');
functions.http('helloHttp', async(req, res) => {
const client = new container.v1.ClusterManagerClient();
projectId = req.query.projectId || req.body.projectId;
const request = {
projectId: projectId,
parent: `projects/${projectId}/locations/-`
};
const [clustersList] = await client.listClusters(request);
var runAgain = false;
var nbOfNodes = 0;
var status = 200;
clustersList.clusters.forEach(async cluster => {
cluster.nodePools.forEach(async nodePool => {
// Disable autoscaling if it's enabled
if(nodePool.autoscaling.enabled) {
runAgain = true;
try {
console.log(`${projectId} - ${cluster.name} - Disabling autoscaling on ${nodePool.name}`);
const autoscalingRequest = {
name: nodePool.selfLink.split('/v1/')[1],
autoscaling: {
enabled: false
}
}
const autoscalingResponse = await client.setNodePoolAutoscaling(autoscalingRequest);
console.log(`${projectId} - ${cluster.name} - ${nodePool.name} - autoscalingResponse:`, JSON.stringify(autoscalingResponse));
// Can't resize right after, we need to wait for operation to end
} catch (error) {
console.log(`${projectId} - ${cluster.name} - ${nodePool.name} - autoscalingError:`, JSON.stringify(error));
}
} else {
try {
nbOfNodes += nodePool.currentNodeCount;
console.log(`${projectId} - ${cluster.name} - Downscaling ${nodePool.name} from ${nodePool.currentNodeCount} to 0`);
const downscalingRequest = {
name: nodePool.selfLink.split('/v1/')[1],
nodeCount: 0
}
const downscalingResponse = await client.setNodePoolSize(downscalingRequest);
console.log(`${projectId} - downscalingResponse:`, JSON.stringify(downscalingResponse));
} catch (error) {
console.log(`${projectId} - ${cluster.name} - ${nodePool.name} - autoscalingError:`, JSON.stringify(error));
runAgain = true;
}
}
});
});
var response = `${projectId} - Downscaled ${clustersList.clusters.length} GKE clusters to 0 nodes.`
response += ` - Turned off ${nbOfNodes} nodes.`
if(runAgain) {
response += " - Call me again!";
status = 428;
}
res.status(status).send(response);
});
{
"dependencies": {
"@google-cloud/functions-framework": "^3.0.0",
"@google-cloud/container": "^5.18.0"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment