|
9 | 9 | "strconv"
|
10 | 10 |
|
11 | 11 | "github.com/stackitcloud/stackit-cli/internal/pkg/utils"
|
| 12 | + "k8s.io/client-go/tools/clientcmd" |
12 | 13 |
|
13 | 14 | "github.com/stackitcloud/stackit-sdk-go/core/oapierror"
|
14 | 15 | "github.com/stackitcloud/stackit-sdk-go/services/ske"
|
@@ -246,6 +247,45 @@ func ConvertToSeconds(timeStr string) (*string, error) {
|
246 | 247 | return utils.Ptr(strconv.FormatUint(result, 10)), nil
|
247 | 248 | }
|
248 | 249 |
|
| 250 | +// Merge new Kubeconfig into existing Kubeconfig. If it doesn´t exits, creates a new one |
| 251 | +func MergeKubeConfig(pathDestionationKubeConfig, contentNewKubeConfig string) error { |
| 252 | + if contentNewKubeConfig == "" { |
| 253 | + return fmt.Errorf("no data to merge. the new kubeconfig is empty") |
| 254 | + } |
| 255 | + |
| 256 | + newConfig, err := clientcmd.Load([]byte(contentNewKubeConfig)) |
| 257 | + if err != nil { |
| 258 | + return fmt.Errorf("error loading new kubeconfig: %w", err) |
| 259 | + } |
| 260 | + |
| 261 | + // if the destionation kubeconfig does not exist, create a new one |
| 262 | + if _, err := os.Stat(pathDestionationKubeConfig); os.IsNotExist(err) { |
| 263 | + return WriteConfigFile(pathDestionationKubeConfig, contentNewKubeConfig) |
| 264 | + } |
| 265 | + |
| 266 | + existingConfig, err := clientcmd.LoadFromFile(pathDestionationKubeConfig) |
| 267 | + if err != nil { |
| 268 | + return fmt.Errorf("error loading existing kubeconfig: %w", err) |
| 269 | + } |
| 270 | + |
| 271 | + for name, authInfo := range newConfig.AuthInfos { |
| 272 | + existingConfig.AuthInfos[name] = authInfo |
| 273 | + } |
| 274 | + for name, context := range newConfig.Contexts { |
| 275 | + existingConfig.Contexts[name] = context |
| 276 | + } |
| 277 | + for name, cluster := range newConfig.Clusters { |
| 278 | + existingConfig.Clusters[name] = cluster |
| 279 | + } |
| 280 | + |
| 281 | + err = clientcmd.WriteToFile(*existingConfig, pathDestionationKubeConfig) |
| 282 | + if err != nil { |
| 283 | + return fmt.Errorf("error writing merged kubeconfig: %w", err) |
| 284 | + } |
| 285 | + |
| 286 | + return nil |
| 287 | +} |
| 288 | + |
249 | 289 | // WriteConfigFile writes the given data to the given path.
|
250 | 290 | // The directory is created if it does not exist.
|
251 | 291 | func WriteConfigFile(configPath, data string) error {
|
|
0 commit comments