Converting Spring Boot Property Variables to Environment Variables with Go

Featured image for sharing metadata for article

Since I migrated my personal Spring Boot applications to run on Kubernetes, I've been using Spring Boot's environment variables support to configure the application.

After doing this manually for a while, I've found that it's time to automate it, so I've reached for Go as a means to provide a handy command-line program:

package main

import (
	"fmt"
	"io"
	"os"
	"regexp"
	"strings"
)

func convert(s string) string {
	s = strings.ReplaceAll(s, ".", "_")
	s = strings.ReplaceAll(s, "-", "")

	listRe := regexp.MustCompile(`\[([0-9]+)\]`)
	s = listRe.ReplaceAllString(s, "_${1}_")

	s = strings.ReplaceAll(s, "__", "_")
	return strings.ToUpper(s)
}

func main() {
	data, err := io.ReadAll(os.Stdin)
	if err != nil {
		panic(err)
	}
	propertyAndValue := strings.Split(strings.TrimSuffix(string(data), "\n"), "=")

	if len(propertyAndValue) == 1 {
		fmt.Println(convert(propertyAndValue[0]))
	} else {
		fmt.Println(convert(propertyAndValue[0]) + "=" + propertyAndValue[1])
	}
}

That can be run like so, handling the property's value, as well as list-based configuration:

$ go run main.go <<< spring.main.log-startup-info
SPRING_MAIN_LOGSTARTUPINFO
$ go run main.go <<< spring.main.log-startup-info=1234.foo.bar
SPRING_MAIN_LOGSTARTUPINFO=1234.foo.bar
$ go run main.go <<< my.service[0].other
MY_SERVICE_0_OTHER

Written by Jamie Tanna's profile image Jamie Tanna on , and last updated on .

Content for this article is shared under the terms of the Creative Commons Attribution Non Commercial Share Alike 4.0 International, and code is shared under the Apache License 2.0.

#blogumentation #go #command-line #spring-boot.

Also on:

This post was filed under articles.

Interactions with this post

Interactions with this post

Below you can find the interactions that this page has had using WebMention.

Have you written a response to this post? Let me know the URL:

Do you not have a website set up with WebMention capabilities? You can use Comment Parade.