-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
183 lines (146 loc) · 4.29 KB
/
main.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
package main
import (
"fmt"
"github.com/rancher/wrangler-cli"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/valyala/fasttemplate"
"gopkg.in/yaml.v2"
"io/ioutil"
"os"
"path/filepath"
"strings"
)
const (
autoAppsFlag = "autoapps"
argoAPIVersion = "argoproj.io/v1alpha1"
argoAppKind = "Application"
argoProjectKind = "AppProject"
autoAppsEnvPrefix = "AUTOAPPS_"
autoAppsAnnotationSkipDetector = "autoapps-skip-discovery"
)
// App is a bare bones struct barely descriptive enough to recognize ArgoCD Application CRDs
// NOTE: Purposely not using the argoproj types here, keep it simple!
type App struct {
ApiVersion string `yaml:"apiVersion"`
Kind string `yaml:"kind"`
Metadata struct {
Annotations map[string]string `yaml:"annotations"`
}
}
type Generate struct {
BasePath string `name:"basePath" usage:"Base path to begin traversal"`
}
func (g *Generate) Run(cmd *cobra.Command, args []string) error {
if len(args) == 0 {
return cmd.Help()
}
if g.BasePath == "" {
logrus.Fatal("You must specify a --basePath!")
}
projects, apps, err := walkForArgo(g.BasePath)
if err != nil {
logrus.Errorf("Failed to collect apps: %v", err)
}
// Print out rendered projects to stdout for ArgoCD to read
fmt.Print(strings.Join(projects, "\n---\n"))
fmt.Println("---")
// Print out rendered apps to stdout for ArgoCD to read
fmt.Print(strings.Join(apps, "\n---\n"))
return nil
}
func main() {
root := cli.Command(&Generate{}, cobra.Command{
Short: "Base path",
Long: "Base path long description",
})
cli.Main(root)
}
func walkForArgo(base string) (projects []string, apps []string, err error) {
var appsData [][]byte
var projectData [][]byte
err = filepath.Walk(base, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
// Only care about valid yaml files
if ext := filepath.Ext(path); ext == ".yaml" || ext == ".yml" {
data, err := ioutil.ReadFile(path)
if err != nil {
return err
}
// Check AppProjects
if ok := isAutoApp(data, argoAPIVersion, argoProjectKind); ok {
projectData = append(appsData, data)
}
// Check Applications
if ok := isAutoApp(data, argoAPIVersion, argoAppKind); ok {
appsData = append(appsData, data)
}
}
return nil
})
if err != nil {
return projects, apps, err
}
// Render project template
for _, data := range projectData {
rendered := renderTemplate(string(data))
// Determine if we need to skip it once it's read
include := isAutoApp([]byte(rendered), argoAPIVersion, argoProjectKind)
if include {
projects = append(projects, rendered)
}
}
// Render apps template
for _, data := range appsData {
rendered := renderTemplate(string(data))
// Determine if we need to skip it once it's read
include := isAutoApp([]byte(rendered), argoAPIVersion, argoAppKind)
if include {
apps = append(apps, rendered)
}
}
return projects, apps, nil
}
// isAutoApp returns true/false based on whether or not a valid yaml file is a non skipped valid Application CR
func isAutoApp(data []byte, apiVersion string, kind string) bool {
var a App
isApp := false
err := yaml.Unmarshal(data, &a)
if err != nil {}
// Check if this is an app
if a.ApiVersion == apiVersion && a.Kind == kind {
isApp = true
}
// Check if application is supposed to be skipped
if val, ok := a.Metadata.Annotations[autoAppsAnnotationSkipDetector]; ok {
if val == "true" {
isApp = false
}
}
return isApp
}
func renderTemplate(template string) string {
t := fasttemplate.New(template, "{{", "}}")
validEnvs := currentEnvToMap(autoAppsEnvPrefix)
rendered := t.ExecuteString(validEnvs)
return rendered
}
// currentEnvToMap will search for all environment variables with `prefix`, and convert their values into a map suitable for fasttemplate
func currentEnvToMap(prefix string) map[string]interface{} {
envs := make(map[string]interface{})
for _, e := range os.Environ() {
pair := strings.SplitN(e, "=", 2)
// Trim detector prefix
if strings.HasPrefix(pair[0], prefix) {
trimmed := strings.TrimPrefix(pair[0], prefix)
envs[trimmed] = pair[1]
}
// Always include ARGOCD_ variables
if strings.HasPrefix(pair[0], "ARGOCD_") {
envs[pair[0]] = pair[1]
}
}
return envs
}