Spring Boot Configuration and Secret Management Patterns on Kubernetes
Tags: vault, springboot, kubernetes, microservices
Published: 2021-02-24 13:43:49

---
title: Spring Boot Configuration and Secret Management Patterns on Kubernetes
published: true
date: 2021-02-24 09:11:05 UTC
tags: vault,springboot,kubernetes,microservices
canonical_url: https://hmh.engineering/spring-boot-configuration-and-secret-management-patterns-on-kubernetes-aaf5bb61c4b2
---

![](https://cdn-images-1.medium.com/max/1024/1*RfWGnaA2olNUeD2YuZqxmQ.png)<figcaption>Popular tools and frameworks on k8s</figcaption>

Spring Boot has been a very popular framework for building microservices in the cloud. Working with Spring Boot on Kubernetes has always been fun, but also comes with its own set of challenges as well as presents numerous architectural options ranging from application security, package management, containers, security, service configuration, and secrets management. More recently I have had a chance to evaluate and implement many of these patterns. In this post, I share some of my encounters and learnings in the service configuration and secret management space that I hope will help you on your K8s journey!

### The Norm

A typical _Spring Boot_ microservice configuration includes a bunch of profiles set up through application or bootstrap YAML files. One could better that with a pattern where we have profiles and application YAML files externalized through _Spring Cloud Config_. Now that we have configuration externalized, how about dynamically reloading configuration without application restart? Sure. One could do that with some kind of a job or a task that knows how to perform a [_/actuator/refresh_](https://www.baeldung.com/spring-reloading-properties) once the updated configs have been deployed. Others may choose more of an automated approach with spring cloud bus over Kafka or RabbitMQ to publish state change events and reload applications appropriately.

### Meet the k8s counterpart

At the core of the Kubernetes are concepts such as [ConfigMaps](https://kubernetes.io/docs/concepts/configuration/configmap/) and [Secrets](https://kubernetes.io/docs/concepts/configuration/secret/) that provide a clean separation between sensitive and non-sensitive configurations for your services.

**ConfigMaps and Secrets as Environment variables or files.**

> **The** [**twelve-factor**](https://12factor.net/) **app stores config in _environment variables_** (often shortened to _env vars_ or _env_). Env vars are easy to change between deploys without changing any code; unlike config files, there is little chance of them being checked into the code repo accidentally; and unlike custom config files, or other config mechanisms such as Java System Properties, they are a language- and OS-agnostic standard.

On Kubernetes we have a choice to make configurations sourced from ConfigMaps and Secrets available to the application as environment variables through deployment descriptors such as configMapkeyRef or secretKeyRef .

Another alternative to environment variables is to load _Configmaps_ or _Secrets_ as a file through k8s volumes and volumeMounts where applications also get the benefit of listening to file system change events as configurations may be updated.

**Spring Cloud Kubernetes**

[_Spring Cloud Kubernetes_](https://spring.io/projects/spring-cloud-kubernetes) makes it a lot easier for Spring Boot applications on Kubernetes to leverage these features for service configuration as well as secret management.

![](https://cdn-images-1.medium.com/max/1024/1*9PNFQZF18ii8RUoGl440kA.png)<figcaption>In-Built integration pattern with spring cloud kubernetes for ConfigMaps and Secrets</figcaption>

Along with reading ConfigMaps and Secrets, the application can also watch for changes and be configured to reload itself if there were any changes. This is a pretty cool feature. However, this comes with a level of coupling as well as Kubernetes permission sets required (Such as access to the API Server) that may not be desired for the applications. Starting Spring Cloud 2020.0 release, this feature has been deprecated. Read the deprecation notice for more details. [More details on the deprecation notice can be found here](https://github.com/spring-cloud/spring-cloud-kubernetes/#53-propertysource-reload). What Next?

**Config Watcher**

There is now a config-watcher available that can be deployed as a side-car application that watches for any changes to ConfigMaps or Secrets and is capable of issuing a reload to your application across your _replicaset_. There are a couple of methods to achieve this.

**HTTP — sidecar for config watcher**

![](https://cdn-images-1.medium.com/max/1024/1*922NFz6nNFV4NQ0aaSL4JQ.png)<figcaption>HTTP based config-watcher sidecar</figcaption>

This integration is enabled through the DiscoveryClient where applications can enable this feature with an @EnableDiscoveryClient annotation. The config-watcher can discover pods that match the namespace or pod label configured and issue a refresh against the pods upon a configuration change event for a ConfigMap or Secret.

**Spring Cloud Bus — sidecar for config watcher**

![](https://cdn-images-1.medium.com/max/1024/1*vxDpcWsmkuF5kEY52WyT7Q.png)<figcaption>spring-cloud-bus based config-watcher sidecar</figcaption>

Just like the HTTP option discussed above, the config-watcher also supports Spring Cloud Bus integration over RabbitMQ and Kafka (which I personally had the privilege to contribute to recently. See [Support Kafka for Spring Cloud Kubernetes Configuration Watcher](https://github.com/spring-cloud/spring-cloud-kubernetes/issues/654) for more details). Upon Detecting a change the config-watcher publishes a _ReloadEvent_ that the pods could listen to and perform an application Reload. See the [documentation on cloud bus intergation](https://docs.spring.io/spring-cloud-kubernetes/docs/current/reference/html/index.html#messaging-implementation) for configuration details.

Another useful feature that I was also able to contribute to in this space is the ability to choose between enabling ConfigMaps and/or Secrets (See [spring-cloud-kubernetes-config options and autoconfigure not working with reload](https://github.com/spring-cloud/spring-cloud-kubernetes/issues/635) for more details).

```
spring:
  cloud:
    kubernetes:
      config:
        enabled: true
      secrets:
        enabled: false
      discovery:
        enabled: false
      reload:
        enabled: true
        monitoring-config-maps: true
```

Allows us that extra flexibility for applications that may only need to enable one or the other or both if you may wish.

You can already see the benefits here of using a _sidecar_ container such as the config-watcher either over HTTP or Spring Cloud Bus. Gets us a level of decoupling that is more secured and saves the application from the finer details of watching for configuration changes. While this is a step forward this does not completely get rid of the dependencies on the K8s API Server. See [Strongly discourage applications from talking to the Kubernetes API Server](https://github.com/spring-cloud/spring-cloud-kubernetes/issues/461) for more details.

In general, applications should not need to know that they are running inside Kubernetes. However, _Spring Cloud Kubernetes_ allows you to detect this by automatically enabling a _Kubernetes_ profile (adds onto existing active profiles if you have any already) that one could use to determine the deploy environment. This is useful if we had applications that are deployed on multiple platforms.

### **Consul**

[Consul](https://www.consul.io/) from Hashicorp is a service mesh solution providing a full-featured control plane with service discovery, configuration, and segmentation functionality.

With the [Consul KV](https://www.consul.io/docs/dynamic-app-config/kv), we could store plain key/value or files such as .yaml or .json. Spring Cloud Consul makes it a lot easier for Spring Boot applications to integrate with consul where .yaml files are automatically loaded as part of the spring bootstrap phase and attached to the appropriate profiles making it a great option for externalizing non-sensitive configuration and still benefit from spring profiles. In addition, it also supports an out of the box watcher that keeps track of any changes and automatically reloads any spring components that may have been @RefreshScope .

Consul service mesh enables service-to-service communication with authorization and encryption. Applications can use sidecar proxies in a service mesh configuration to automatically establish TLS connections for inbound and outbound connections without being aware of the network configuration and topology. A great way to secure your services with managed configurations or [Intentions](https://www.consul.io/docs/connect/intentions).

### **Vault**

[Vault](https://www.vaultproject.io/) is another product from HashiCorp that brings in capabilities for secrets management with a variety of secret engine backends such as consul (infra), database (infra), aws (cloud), and its own kv (generic) among others.

Vault KV can be very useful to store simple key/values and supports spring profiles for property sources.

The Database backend supports generating dynamic credentials for your applications and saves you from generating one and persisting it. This can be injected into your data source and also be eligible for lease rotation.

The AWS backend can be used to generate dynamic credentials based on IAM user or STS (assumed\_role and federation\_token) for AWS service integration.

The Consul backend can be used to secure application access to consul. For instance, applications would need a consul token to integrate with consul kv where the token itself is sensitive information and applications need a mechanism to securely request consul tokens and thus integrate with consul kv.

### **Spring Cloud Consul and Spring Cloud Vault**

![](https://cdn-images-1.medium.com/max/1024/1*y3XZNUXAlnGyUXOJbNoNdA.png)<figcaption>A sample microservice template on k8s</figcaption>

Spring Cloud Vault and Spring Cloud Consul can be used together and work pretty well and are great choices for Spring Boot applications integrating with Consul and Vault for service configuration and secrets management. There are some challenges at bootstrap to make sure the consul token is retrieved before asking for non-sensitive configuration from consul kv (Workaround available. See [Consul Tokens from Spring Vault do not get picked up by Spring Cloud Config Consul](https://github.com/spring-cloud/spring-cloud-vault/issues/58) for more details.).

Recently I did run into some issues with the spring cloud vault not supporting AWS STS for temporary credentials behind the AWS Secret Engine. This is being discussed under [Support AWS STS for the vault secrets backend for aws](https://github.com/spring-cloud/spring-cloud-vault/issues/572) and I have a [pull request](https://github.com/spring-cloud/spring-cloud-vault/issues/572) in the works!

### **Vault Agent Injector Sidecar**

Another pattern that could be used with vault and pods on k8s is the sidecar injector option. Provides for an annotation-driven secret injection for your pods that could be a pretty handy way to decouple applications with secret management. This is also a great choice for applications and tech stacks that do not have a comprehensive SDK/library that supports vault integration by abstracting away the details and allowing pods to use mounts and provide secrets as files along with support for lease rotations. See [Agent Sidecar Injector](https://www.vaultproject.io/docs/platform/k8s/injector)for more details.

### Config file processing on Spring Boot 2.4

Starting Spring Boot 2.4 there is a significant change in how configs are loaded in spring boot. For example, Vault could now be used in conjunction with spring.config.import and provides a secured replacement to bootstrap.yaml.

```
spring:
  config:                           
    import: vault://secret/app/pres/dev                              
    activate:                             
      on-profile: "dev"
  datasource:
    username: ${username}
    password: ${password}
```

Read [config file processing](https://spring.io/blog/2020/08/14/config-file-processing-in-spring-boot-2-4) for more details.

If you got this far, you would already know by now that there are a plethora of architectural patterns in this space. :-) There are not any rights or wrongs here and its’ mostly up to you to pick what's best for you/team/projects based on the capability, flexibility, and most importantly security you may be looking for with your configurations and secret management. I hope this post helps you a tiny bit along your k8s journey!

Good Luck and Stay Safe!

Thanks to [Attila Vágó](https://medium.com/u/2053aaf853f5), [Darragh Grace](https://medium.com/u/cc5d990750e3), and [Francislâiny Campos](https://medium.com/u/34d2b81e5dc4) for their feedback on this post!

* * *