-1

I have a yaml file which consist of placeholders to be taken from environment variable. I want to parse it to a custom class. Currently I am using snakeyaml library to parse it and its populating the bean correctly, how can I resolve environment variables using snakeyaml or any other library in Java.

datasource:
  url: {url_environment_variable}
  foo: bar
  username: {user_name_environment_variable}
  password: {password_environment_variable}

@Getter
@Setter
public class DataSource {
private String url;
private String foo;
private String username;
private String password;
}

Parsing code below

Constructor c = new Constructor(MyDataSource.class);
Yaml yaml = new Yaml(c);
MyDataSource myData = yaml.loadAs(inputStream, MyDataSource.class);

The problem is I am yet to find a way to resolve placeholders. People were able to solve it using python and is available in question - How to replace environment variable value in yaml file to be parsed using python script

How can I do the same in Java. I can add a new dependency if required. PS - It's not a Spring Boot Project so standard Spring placeholder replacements can not be used.

AlphaBetaGamma
  • 1,910
  • 16
  • 21

1 Answers1

-1

The easiest way would be to do it in two passes. First deserialize into MyDataSource as you’re doing already. Then use reflection to iterate over all fields of the instance, and if the value starts with a curly brace and ends with one, extract the key, and get the value from System.getenv map. See this answer for code.

If you want to do it in one pass, then you need to use the snakeyaml event-driver parser. For every key, you resolve the value as described above, and then based on the key name, set the corresponding field in the MyDataSource class, either using reflection, or simple if-else. For an example of the event-driven parser, see this class; it’s not Java, it’s Kotlin, but it may be the only JVM language example you’ll find.

Abhijit Sarkar
  • 21,927
  • 20
  • 110
  • 219