SoFunction
Updated on 2025-03-05

Create a new token based on kubeadm using golang script (problem analysis)

illustrate

1. This script is mainly used to solve two problems:

First: In fact, it can be implemented using python scripts, but python has to face the different problems of python2 in centos7 and python3 in openeuler

The second: It is the problem of multi-architecture and offline problems.

Third: Learn the practice of go scripts.

All of the above problems may cause this python script to be less general.

2. Applicable scenarios:

It is temporarily used to cooperate with my previous deployment of high-availability K8S cluster to filter out token information or to directly generate a new token when the token expires.

Other extensions are still under consideration

Logic used by scripts

Resolve command line parameters

// Define command line parameterstokenFlag := ("token", false, "Regenerate the same token information as kubeadm token create --print-join-command")
()

Go

The script uses Go languageflagPackage to parse command line parameters. It defines a name calledtokenFlagThe command line flag of , used to determine whether to regenerate the join command.

cmd command line function

func generateToken() {
	// Call the kubeadm token create --print-join-command command to generate the same token information as kubeadm token create --print-join-command	cmd := ("kubeadm", "token", "create", "--print-join-command")
	 = 
	 = 
	err := ()
	if err != nil {
		("An error occurred while generating token information:", err)
	}
}

Go

generateTokenThe purpose of the function is to regenerate the command to join the cluster. It calls external commandskubeadm token create --print-join-commandto generate new tokens and join commands.

This command is similar to python's ``

Logic for reading and processing file content

// Open the log file		file, err := ("./k8s_init.log")
		if err != nil {
			("Cannot open log file:", err)
			return
		}
		defer ()
		// Create a buffered file reader		scanner := (file)
		// Set flags to track whether the control plane and default rows are found		inControlPlane := false
		inDefaultLine := false
		// Read the file content line by line		for () {
			line := ()
			// If you find a line containing "--control-plane"			if (line, "--control-plane") {
				inControlPlane = true
				(line) // Print control plane lines			} else if inControlPlane && (line, "--discovery-token-ca-cert-hash") {
				(line) // Print related control plane lines				inControlPlane = false
			} else if (line, "kubeadm join") {
				(line) // Print default line				inDefaultLine = true
			} else if inDefaultLine && (line, "--discovery-token-ca-cert-hash") {
				(line) // Print related default lines				inDefaultLine = false
			}
		}
		if err := (); err != nil {
			("An error occurred while reading the file:", err)
		}

Go

This part of the logic is in the main functionelseIn the branch. It opens with the namek8s_init.log, then read the file content line by line, find the identifiers of the control plane and default lines, and print the corresponding lines. This part of the logic distinguishes and outputs control planes and default lines according to the content of the file.

The main function of the script is to determine whether to generate andkubeadm token create --print-join-commandSame token information. if-tokenCommand line parameters are provided and the script will callgenerateTokenThe function generates new token information; otherwise, it reads the file and processes the file contents to distinguish the control plane from the default line and outputs the corresponding information. This allows scripts to be used to generate join commands for Kubernetes clusters or to analyze content in log files.

Complete script

package main
import (
	"bufio"
	"flag"
	"fmt"
	"os"
	"os/exec"
	"strings"
)
func main() {
	// Define command line parameters	tokenFlag := ("token", false, "Regenerate the same token information as kubeadm token create --print-join-command")
	()
	if *tokenFlag {
		generateToken()
	} else {
		// Open the log file		file, err := ("./k8s_init.log")
		if err != nil {
			("Cannot open log file:", err)
			return
		}
		defer ()
		// Create a buffered file reader		scanner := (file)
		// Set flags to track whether the control plane and default rows are found		inControlPlane := false
		inDefaultLine := false
		// Read the file content line by line		for () {
			line := ()
			// If you find a line containing "--control-plane"			if (line, "--control-plane") {
				inControlPlane = true
				(line) // Print control plane lines			} else if inControlPlane && (line, "--discovery-token-ca-cert-hash") {
				(line) // Print related control plane lines				inControlPlane = false
			} else if (line, "kubeadm join") {
				(line) // Print default line				inDefaultLine = true
			} else if inDefaultLine && (line, "--discovery-token-ca-cert-hash") {
				(line) // Print related default lines				inDefaultLine = false
			}
		}
		if err := (); err != nil {
			("An error occurred while reading the file:", err)
		}
	}
}
func generateToken() {
	// Call the kubeadm token create --print-join-command command to generate the same token information as kubeadm token create --print-join-command	cmd := ("kubeadm", "token", "create", "--print-join-command")
	 = 
	 = 
	err := ()
	if err != nil {
		("An error occurred while generating token information:", err)
	}
}

Go

How to use

[root@node1 ~]# ./go_join_amd64 
  kubeadm join :6443 --token abcdef.0123456789abcdef \
        --discovery-token-ca-cert-hash sha256:13ddf570d3d11c5c0cda814e823610dae3922d825b60957c1ea288a666fd8f00 \
        --control-plane 
kubeadm join :6443 --token abcdef.0123456789abcdef \
        --discovery-token-ca-cert-hash sha256:13ddf570d3d11c5c0cda814e823610dae3922d825b60957c1ea288a666fd8f00 
[root@node1 ~]# ./go_join_amd64 -token
kubeadm join :6443 --token 5hygoq.z57dqi3bf2jlk61f --discovery-token-ca-cert-hash sha256:13ddf570d3d11c5c0cda814e823610dae3922d825b60957c1ea288a666fd8f00 

Bash

Summarize

The function just adds a token parameter to refresh the token. It mainly involves learning golang's text processing and execution of cmd commands. These are the first problems encountered by operation and maintenance when writing scripts using go.

Later I thought that the function would be added again, and the writing was very bad. If you have any questions or complaints, please leave a message.

This is the article about using golang scripts to create a new token based on kubeadm. For more related content on creating tokens from golang kubeadm, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!