Inject yaml list as jvm argument?

5/15/2019

Trying to use IP pattern filter provided by Micronaut framework. What I want is to inject the configuration at application startup. Right now yaml file takes a list of IPs as input. But to inject the configuration at runtime, how can I pass the list of IP's to this yaml property.

Current scenario

micronaut:
  security:
    enabled: true
    ip-patterns:
      - 127.0.0.1
      - 192.168.1.*

Not sure if the below thing will work

Expected

micronaut:
  security:
    enabled: true
    ip-patterns:${list_of_Ip's}
-- naval jain
java
kubernetes
micronaut
yaml

1 Answer

5/15/2019

The ip-patterns is a list as you know and you can't represent ${} as a list. You can create a custom property source to convert the environment variable into the configuration.

For example:

public class Application {

    public static void main(String[] args) {
        String patternsEnv = System.getenv("SOME_ENV");
        List<String> ipPatterns = Arrays.stream(patternsEnv.split(","))
                .map(StringUtils::trimToNull)
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
        Map<String, Object> map = new HashMap<>(1);
        map.put("micronaut.security.ip-patterns", ipPatterns);
        PropertySource propertySource = new MapPropertySource("ip-patterns", map) {

            @Override
            public int getOrder() {
                return 0;
            }
        };

        Micronaut.build(null)
                .mainClass(Application.class)
                .propertySources(propertySource)
                .start();
    }
}
-- James Kleeh
Source: StackOverflow