Created
November 7, 2020 08:26
-
-
Save uablrek/1436ef3fe30314d6e396e54a31128031 to your computer and use it in GitHub Desktop.
A go program that clears nodePorts for a service on K8s
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"context" | |
"flag" | |
"fmt" | |
"log" | |
"os" | |
core "k8s.io/api/core/v1" | |
meta "k8s.io/apimachinery/pkg/apis/meta/v1" | |
"k8s.io/client-go/kubernetes" | |
"k8s.io/client-go/rest" | |
"k8s.io/client-go/tools/clientcmd" | |
) | |
var version = "unknown" | |
func main() { | |
svc := flag.String("svc", "", "Service to update") | |
namespace := flag.String("n", "default", "Namespace") | |
ver := flag.Bool("version", false, "Print version and quit") | |
flag.Parse() | |
if *ver { | |
fmt.Println(version) | |
os.Exit(0) | |
} | |
if *svc == "" { | |
log.Fatalln("No service specified. Use -help") | |
} | |
removeNodeport(*namespace, *svc) | |
os.Exit(0) | |
} | |
func getClientset() (*kubernetes.Clientset, error) { | |
config, err := rest.InClusterConfig() | |
if err != nil { | |
kubeconfig := | |
clientcmd.NewDefaultClientConfigLoadingRules().GetDefaultFilename() | |
config, err = clientcmd.BuildConfigFromFlags("", kubeconfig) | |
if err != nil { | |
return nil, err | |
} | |
} | |
return kubernetes.NewForConfig(config) | |
} | |
func removeNodeport(namespace, service string) { | |
clientset, err := getClientset() | |
if err != nil { | |
log.Fatalln("Failed to create k8s client; ", err) | |
} | |
svci := clientset.CoreV1().Services(namespace) | |
svc, err := svci.Get(context.TODO(), service, meta.GetOptions{}) | |
if err != nil { | |
log.Fatalf("Failed to get service [%s:%s]; %v\n", namespace, service, err) | |
} | |
// Check that the service has "type: LoadBalancer" | |
if svc.Spec.Type != core.ServiceTypeLoadBalancer { | |
log.Fatalln("Service is not type: LoadBalancer") | |
} | |
if svc.Spec.AllocateLoadBalancerNodePorts == nil { | |
fmt.Println("AllocateLoadBalancerNodePorts nil") | |
} else { | |
fmt.Println("AllocateLoadBalancerNodePorts ", *svc.Spec.AllocateLoadBalancerNodePorts) | |
} | |
for i,_ := range svc.Spec.Ports { | |
svc.Spec.Ports[i].NodePort = 0 | |
} | |
svc, err = svci.Update(context.TODO(), svc, meta.UpdateOptions{}) | |
if err != nil { | |
log.Fatalf("Failed to update service [%s:%s]; %v\n", namespace, service, err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment