Skip to content

Commit c13a625

Browse files
(helm/v1-alpha): Use namePrefix from config/default/kustomization.yaml as prefix for RBAC rules and project name only if this value cannot be found.
1 parent b9c5b7f commit c13a625

File tree

1 file changed

+101
-11
lines changed
  • pkg/plugins/optional/helm/v1alpha/scaffolds

1 file changed

+101
-11
lines changed

pkg/plugins/optional/helm/v1alpha/scaffolds/init.go

Lines changed: 101 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -206,7 +206,7 @@ func (s *initScaffolder) extractWebhooksFromGeneratedFiles() (mutatingWebhooks [
206206
}
207207
webhook := templateswebhooks.DataWebhook{
208208
Name: w.Name,
209-
ServiceName: fmt.Sprintf("%s-webhook-service", s.config.GetProjectName()),
209+
ServiceName: fmt.Sprintf("%s-webhook-service", s.getNamePrefix()),
210210
Path: w.ClientConfig.Service.Path,
211211
FailurePolicy: w.FailurePolicy,
212212
SideEffects: w.SideEffects,
@@ -238,6 +238,8 @@ func (s *initScaffolder) copyConfigFiles() error {
238238
{"config/network-policy", "dist/chart/templates/network-policy", "networkPolicy"},
239239
}
240240

241+
namePrefix := s.getNamePrefix()
242+
241243
for _, dir := range configDirs {
242244
// Check if the source directory exists
243245
if _, err := os.Stat(dir.SrcDir); os.IsNotExist(err) {
@@ -277,19 +279,28 @@ func (s *initScaffolder) copyConfigFiles() error {
277279
}
278280
}
279281

280-
err := copyFileWithHelmLogic(srcFile, destFile, dir.SubDir, s.config.GetProjectName(), hasConvertionalWebhook)
282+
err := copyFileWithHelmLogic(srcFile, destFile, dir.SubDir, namePrefix, hasConvertionalWebhook)
281283
if err != nil {
282284
return err
283285
}
284286
}
285287
}
286288

289+
projectName := s.config.GetProjectName()
290+
291+
if namePrefix != projectName {
292+
err := replacePrefixedNamesInChartFiles("dist/chart", projectName, namePrefix)
293+
if err != nil {
294+
return fmt.Errorf("post-process to ensure customized name prefixed: %w", err)
295+
}
296+
}
297+
287298
return nil
288299
}
289300

290301
// copyFileWithHelmLogic reads the source file, modifies the content for Helm, applies patches
291302
// to spec.conversion if applicable, and writes it to the destination
292-
func copyFileWithHelmLogic(srcFile, destFile, subDir, projectName string, hasConvertionalWebhook bool) error {
303+
func copyFileWithHelmLogic(srcFile, destFile, subDir, namePrefix string, hasConvertionalWebhook bool) error {
293304
if _, err := os.Stat(srcFile); os.IsNotExist(err) {
294305
log.Printf("Source file does not exist: %s", srcFile)
295306
return fmt.Errorf("source file does not exist %q: %w", srcFile, err)
@@ -316,14 +327,14 @@ func copyFileWithHelmLogic(srcFile, destFile, subDir, projectName string, hasCon
316327
"name: {{ .Values.controllerManager.serviceAccountName }}")
317328
contentStr = strings.Replace(contentStr,
318329
"name: metrics-reader",
319-
fmt.Sprintf("name: %s-metrics-reader", projectName), 1)
330+
fmt.Sprintf("name: %s-metrics-reader", namePrefix), 1)
320331

321332
contentStr = strings.ReplaceAll(contentStr,
322333
"name: metrics-auth-role",
323-
fmt.Sprintf("name: %s-metrics-auth-role", projectName))
334+
fmt.Sprintf("name: %s-metrics-auth-role", namePrefix))
324335
contentStr = strings.Replace(contentStr,
325336
"name: metrics-auth-rolebinding",
326-
fmt.Sprintf("name: %s-metrics-auth-rolebinding", projectName), 1)
337+
fmt.Sprintf("name: %s-metrics-auth-rolebinding", namePrefix), 1)
327338

328339
if strings.Contains(contentStr, ".Values.controllerManager.serviceAccountName") &&
329340
strings.Contains(contentStr, "kind: ServiceAccount") &&
@@ -340,16 +351,16 @@ func copyFileWithHelmLogic(srcFile, destFile, subDir, projectName string, hasCon
340351
}
341352
contentStr = strings.ReplaceAll(contentStr,
342353
"name: leader-election-role",
343-
fmt.Sprintf("name: %s-leader-election-role", projectName))
354+
fmt.Sprintf("name: %s-leader-election-role", namePrefix))
344355
contentStr = strings.Replace(contentStr,
345356
"name: leader-election-rolebinding",
346-
fmt.Sprintf("name: %s-leader-election-rolebinding", projectName), 1)
357+
fmt.Sprintf("name: %s-leader-election-rolebinding", namePrefix), 1)
347358
contentStr = strings.ReplaceAll(contentStr,
348359
"name: manager-role",
349-
fmt.Sprintf("name: %s-manager-role", projectName))
360+
fmt.Sprintf("name: %s-manager-role", namePrefix))
350361
contentStr = strings.Replace(contentStr,
351362
"name: manager-rolebinding",
352-
fmt.Sprintf("name: %s-manager-rolebinding", projectName), 1)
363+
fmt.Sprintf("name: %s-manager-rolebinding", namePrefix), 1)
353364

354365
// The generated files do not include the namespace
355366
if strings.Contains(contentStr, "leader-election-rolebinding") ||
@@ -425,7 +436,7 @@ func copyFileWithHelmLogic(srcFile, destFile, subDir, projectName string, hasCon
425436
{{- include "chart.labels" . | nindent 4 }}`, 1)
426437

427438
// Append project name to webhook service name
428-
contentStr = strings.ReplaceAll(contentStr, "name: webhook-service", "name: "+projectName+"-webhook-service")
439+
contentStr = strings.ReplaceAll(contentStr, "name: webhook-service", "name: "+namePrefix+"-webhook-service")
429440

430441
var wrappedContent string
431442
if isMetricRBACFile(subDir, srcFile) {
@@ -563,3 +574,82 @@ func hasWebhooksWith(c config.Config) bool {
563574

564575
return false
565576
}
577+
578+
// getNamePrefix will return the value from kustomize config so that we can append
579+
// in the RBAC rules manifests. If we be unable to find this value we will use
580+
// the projectName instead.
581+
func (s *initScaffolder) getNamePrefix() string {
582+
filePath := "config/default/kustomization.yaml"
583+
content, err := os.ReadFile(filePath)
584+
if err != nil {
585+
log.Fatalf("failed to read config/default/kustomization.yaml: %s", err)
586+
}
587+
588+
var defaultConfig struct {
589+
NamePrefix string `yaml:"namePrefix"`
590+
}
591+
592+
if err := yaml.Unmarshal(content, &defaultConfig); err != nil {
593+
log.Warnf("failed to parse kustomization.yaml to get namePrefix: %s", err)
594+
log.Warnf("using the project name as a prefix of RBAC and manifests")
595+
return s.config.GetProjectName()
596+
}
597+
598+
cleaned := strings.TrimSuffix(strings.TrimSpace(defaultConfig.NamePrefix), "-")
599+
return cleaned
600+
}
601+
602+
// replacePrefixedNamesInChartFiles replaces project-prefixed in the files which are genarated
603+
// from the templates
604+
func replacePrefixedNamesInChartFiles(rootDir, oldPrefix, newPrefix string) error {
605+
fieldsToCheck := []string{
606+
"name:",
607+
"serviceAccountName:",
608+
"serverName:",
609+
}
610+
611+
return filepath.Walk(rootDir, func(path string, info os.FileInfo, err error) error {
612+
if err != nil {
613+
return err
614+
}
615+
616+
// Skip directories and specifically Chart.yaml
617+
if info.IsDir() || filepath.Base(path) == "Chart.yaml" {
618+
return nil
619+
}
620+
621+
// Process only YAML files
622+
if !(strings.HasSuffix(path, ".yaml") || strings.HasSuffix(path, ".yml")) {
623+
return nil
624+
}
625+
626+
content, err := os.ReadFile(path)
627+
if err != nil {
628+
return fmt.Errorf("failed to read %s: %w", path, err)
629+
}
630+
631+
lines := strings.Split(string(content), "\n")
632+
changed := false
633+
634+
for i, line := range lines {
635+
for _, field := range fieldsToCheck {
636+
trimmed := strings.TrimSpace(line)
637+
if strings.HasPrefix(trimmed, field+" "+oldPrefix) {
638+
lines[i] = strings.Replace(line, oldPrefix, newPrefix, 1)
639+
changed = true
640+
break
641+
}
642+
}
643+
}
644+
645+
if changed {
646+
output := strings.Join(lines, "\n")
647+
if err := os.WriteFile(path, []byte(output), 0644); err != nil {
648+
return fmt.Errorf("failed to write updated file %s: %w", path, err)
649+
}
650+
log.Printf("Updated project-prefixed identifiers in: %s", path)
651+
}
652+
653+
return nil
654+
})
655+
}

0 commit comments

Comments
 (0)