-
Notifications
You must be signed in to change notification settings - Fork 38
/
argocd.go
84 lines (70 loc) · 2.42 KB
/
argocd.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package argocd
import (
"os"
"github.com/pkg/errors"
"gopkg.in/yaml.v3"
)
type ArgocdClusterLabels struct {
ClusterTypes string `yaml:"cluster-type"`
ClusterID string `yaml:"cluster-id"`
}
type ArgocdClusterRegisterParameters struct {
Name string `yaml:"name"`
Type string `yaml:"type"`
Labels ArgocdClusterLabels `yaml:"labels"`
APIServer string `yaml:"api_server"`
CertData string `yaml:"certData"`
CaData string `yaml:"caData"`
KeyData string `yaml:"keyData"`
}
type Argock8sRegister struct {
Clusters []ArgocdClusterRegisterParameters `yaml:"clusters"`
}
// ReadArgoK8sRegistrationFile take a argocd cluster file and load it into Argock8sRegister struct
func ReadArgoK8sRegistrationFile(clusterFile []byte) (*Argock8sRegister, error) {
a := &Argock8sRegister{}
if err := yaml.Unmarshal(clusterFile, a); err != nil {
return nil, errors.Wrap(err, "Error unmarshaling Argo k8s cluster YAML definition")
}
return a, nil
}
// UpdateK8sClusterRegistrationFile take a argocd cluster file and Add new Cluster spec
func UpdateK8sClusterRegistrationFile(cluster *Argock8sRegister, newCluster ArgocdClusterRegisterParameters, filePath string) error {
index := -1
for i, clusterValue := range cluster.Clusters {
if clusterValue.Name == newCluster.Name {
index = i
break
}
}
if index != -1 {
cluster.Clusters[index] = newCluster
} else {
cluster.Clusters = append(cluster.Clusters, newCluster)
}
updatedYAML, err := yaml.Marshal(&cluster)
if err != nil {
return errors.Wrapf(err, "Error marshalling YAML: %v:", updatedYAML)
}
err = os.WriteFile(filePath, updatedYAML, 0644)
if err != nil {
return errors.Wrapf(err, "Error writing YAML file: %v", filePath)
}
return nil
}
// DeleteK8sClusterFromRegistrationFile take a argocd cluster file and delete Cluster from spec
func DeleteK8sClusterFromRegistrationFile(cluster *Argock8sRegister, clusterName string, filePath string) error {
for k, v := range cluster.Clusters {
if v.Name == clusterName {
cluster.Clusters = append(cluster.Clusters[:k], cluster.Clusters[k+1:]...)
}
}
updatedYAML, err := yaml.Marshal(&cluster)
if err != nil {
return errors.Wrapf(err, "Error marshalling YAML: %v:", updatedYAML)
}
if err = os.WriteFile(filePath, updatedYAML, 0644); err != nil {
return errors.Wrapf(err, "Error writing YAML file: %v", filePath)
}
return nil
}