Let’s start:
Create a folder for your new project
Open a command prompt an run:
1mkdir kuberenetes.scale
Create the project
1cd kuberenetes.scale
2dotnet new api
Add the references to KubernetesClient
1dotnet add package KubernetesClient -v 1.5.18
2dotnet restore
Create a PodsController.cs with the following code
1using System;
2using System.Collections.Generic;
3using System.Linq;
4using System.Threading.Tasks;
5using k8s;
6using k8s.Models;
7using Microsoft.AspNetCore.JsonPatch;
8using Microsoft.AspNetCore.Mvc;
9using Microsoft.Extensions.Configuration;
10
11namespace kubernetes.scale
12{
13 [Route("api/[controller]")]
14 [ApiController]
15 public class PodsController : ControllerBase
16 {
17 private KubernetesClientConfiguration k8sConfig = null;
18
19 public PodsController(IConfiguration config)
20 {
21 // Reading configuration to know if running inside a cluster or in local mode.
22 var useKubeConfig = bool.Parse(config["UseKubeConfig"]);
23 if (!useKubeConfig)
24 {
25 // Running inside a k8s cluser
26 k8sConfig = KubernetesClientConfiguration.InClusterConfig();
27 }
28 else
29 {
30 // Running on dev machine
31 k8sConfig = KubernetesClientConfiguration.BuildConfigFromConfigFile();
32 }
33 }
34
35 [HttpPatch("scale")]
36 public IActionResult Scale([FromBody]ReplicaRequest request)
37 {
38 // Use the config object to create a client.
39 using (var client = new Kubernetes(k8sConfig))
40 {
41 // Create a json patch for the replicas
42 var jsonPatch = new JsonPatchDocument<V1Scale>();
43 // Set the new number of repplcias
44 jsonPatch.Replace(e => e.Spec.Replicas, request.Replicas);
45 // Creat the patch
46 var patch = new V1Patch(jsonPatch);
47
48 // Patch the "minions" Deployment in the "default" namespace
49 client.PatchNamespacedDeploymentScale(patch, request.Deployment, request.Namespace);
50
51 return NoContent();
52 }
53 }
54 }
55
56 public class ReplicaRequest
57 {
58 public string Deployment { get; set; }
59 public string Namespace { get; set; }
60 public int Replicas { get; set; }
61 }
62}
Replace the contents of the appsettings.Development.json file
Note the UseKubeConfig property is set to true.
1{
2 "Logging": {
3 "LogLevel": {
4 "Default": "Debug",
5 "System": "Information",
6 "Microsoft": "Information"
7 }
8 },
9 "UseKubeConfig": true
10}
Replace the contents of the appsettings.json file
Note the UseKubeConfig property is set to false.
1{
2 "Logging": {
3 "LogLevel": {
4 "Default": "Warning"
5 }
6 },
7 "AllowedHosts": "*",
8 "UseKubeConfig": false
9}
Test the application
Test the app from your dev machine running:
1dotnet run
2curl -k -i -H 'Content-Type: application/json' -d '{"Deployment": "<YOUR DEPLOYMENT NAME>", "Namespace": "<YOUR NAMESPACE>", "Replicas": 3}' -X PATCH https://localhost:5001/api/pods/scale
Note: You must have a valid config file to connect to the k8s cluster.
Please find all the code used in this post here.
Hope it helps!
Comments