Scaling pods in aks in python

Viewed 207

I am currently able to scale my aks pods using the following code in Powershell.

kubectl scale --replicas=5 deployment/azure-vote-front

But how could I scale them in python? Searched the whole web, but didn't have much progress. Any leads on this will be really helpful.

1 Answers

Using patch_namespaced_deployment & patch_namespaced_deployment_scale api, you need to pass body = {"spec":{"replicas":no.of replica}} like documented in this answer

Here's a code example:

from kubernetes.client.rest import ApiException
from kubernetes import client,config

configuration = kubernetes.client.Configuration()
TOKENFILE='/run/secrets/kubernetes.io/serviceaccount/token'
with open(TOKENFILE, 'r') as file:
    configuration.api_key['authorization'] = file.read()
configuration.api_key_prefix['authorization'] = 'Bearer'
configuration.host = "https://%s" % os.environ['KUBERNETES_SERVICE_HOST']
configuration.ssl_ca_cert="/run/secrets/kubernetes.io/serviceaccount/ca.crt"

aApiClient = kubernetes.client.ApiClient(configuration)
v1 = kubernetes.client.AppsV1Api(aApiClient)
deploymenttoscale="mydeploymentname"
mynamespace="statenamespacehere"

PAYLOAD={"spec":{"replicas":0}}
try:
    print("scaling %s deployment down to 0" % ())
    resultV1Scale = v1.patch_namespaced_deployment_scale(deploymenttoscale,mynamespace,PAYLOAD)
    print('status: %s' % (resultV1Scale.status))
except ApiException as e:
    print("Exception when calling CoreV1Api->delete_namespaced_pod: %s\n" % e)

Sample output:

scaling mydeploymentname deployment down to 0
status: {'replicas': 1, 'selector': 'app=xyz'}
Related