diff --git a/multi/multi__embedding_the_config_server.html b/multi/multi__embedding_the_config_server.html index 1b51f5f6..b520a7ed 100644 --- a/multi/multi__embedding_the_config_server.html +++ b/multi/multi__embedding_the_config_server.html @@ -1,21 +1,13 @@ - 5. Embedding the Config Server

5. Embedding the Config Server

The Config Server runs best as a standalone application, but if you -need to you can embed it in another application. Just use the -@EnableConfigServer annotation. An optional property that can be -useful in this case is spring.cloud.config.server.bootstrap which is -a flag to indicate that the server should configure itself from its -own remote repository. The flag is off by default because it can delay -startup, but when embedded in another application it makes sense to -initialize the same way as any other application.

[Note]Note

It should be obvious, but remember that if you use the bootstrap -flag the config server will need to have its name and repository URI -configured in bootstrap.yml.

To change the location of the server endpoints you can (optionally) -set spring.cloud.config.server.prefix, e.g. "/config", to serve the -resources under a prefix. The prefix should start but not end with a -"/". It is applied to the @RequestMappings in the Config Server -(i.e. underneath the Spring Boot prefixes server.servletPath and -server.contextPath).

If you want to read the configuration for an application directly from -the backend repository (instead of from the config server) that’s -basically an embedded config server with no endpoints. You can switch -off the endpoints entirely if you don’t use the @EnableConfigServer -annotation (just set spring.cloud.config.server.bootstrap=true).

\ No newline at end of file + 5. Embedding the Config Server

5. Embedding the Config Server

The Config Server runs best as a standalone application. +However, if need be, you can embed it in another application. +To do so, use the @EnableConfigServer annotation. +An optional property named spring.cloud.config.server.bootstrap can be useful in this case is. +It is a flag to indicate whether the server should configure itself from its own remote repository. +By default, the flag is off, because it can delay startup. +However, when embedded in another application, it makes sense to initialize the same way as any other application.

[Note]Note

If you use the bootstrap flag, the config server needs to have its name and repository URI configured in bootstrap.yml.

To change the location of the server endpoints, you can (optionally) set spring.cloud.config.server.prefix (for example, /config), to serve the resources under a prefix. +The prefix should start but not end with a /. +It is applied to the @RequestMappings in the Config Server (that is, underneath the Spring Boot server.servletPath and server.contextPath prefixes).

If you want to read the configuration for an application directly from the backend repository (instead of from the config server), you +basically wat an embedded config server with no endpoints. +You can switch off the endpoints entirely by not using the @EnableConfigServer annotation (set spring.cloud.config.server.bootstrap=true).

\ No newline at end of file diff --git a/multi/multi__push_notifications_and_spring_cloud_bus.html b/multi/multi__push_notifications_and_spring_cloud_bus.html index e6264d34..59438f54 100644 --- a/multi/multi__push_notifications_and_spring_cloud_bus.html +++ b/multi/multi__push_notifications_and_spring_cloud_bus.html @@ -1,30 +1,11 @@ - 6. Push Notifications and Spring Cloud Bus

6. Push Notifications and Spring Cloud Bus

Many source code repository providers (like Github, Gitlab, Gitee or Bitbucket -for instance) will notify you of changes in a repository through a -webhook. You can configure the webhook via the provider’s user -interface as a URL and a set of events in which you are -interested. For instance -Github -will POST to the webhook with a JSON body containing a list of -commits, and a header "X-Github-Event" equal to "push". If you add a -dependency on the spring-cloud-config-monitor library and activate -the Spring Cloud Bus in your Config Server, then a "/monitor" endpoint -is enabled.

When the webhook is activated the Config Server will send a -RefreshRemoteApplicationEvent targeted at the applications it thinks -might have changed. The change detection can be strategized, but by -default it just looks for changes in files that match the application -name (e.g. "foo.properties" is targeted at the "foo" application, and -"application.properties" is targeted at all applications). The strategy -if you want to override the behaviour is PropertyPathNotificationExtractor -which accepts the request headers and body as parameters and returns a list -of file paths that changed.

The default configuration works out of the box with Github, Gitlab, Gitee or -Bitbucket. In addition to the JSON notifications from Github, Gitlab, Gitee -or Bitbucket you can trigger a change notification by POSTing to -"/monitor" with a form-encoded body parameters path={name}. This will -broadcast to applications matching the "{name}" pattern (can contain -wildcards).

[Note]Note

the RefreshRemoteApplicationEvent will only be transmitted if -the spring-cloud-bus is activated in the Config Server and in the -client application.

[Note]Note

the default configuration also detects filesystem changes in -local git repositories (the webhook is not used in that case but as -soon as you edit a config file a refresh will be broadcast).

\ No newline at end of file + 6. Push Notifications and Spring Cloud Bus

6. Push Notifications and Spring Cloud Bus

Many source code repository providers (such as Github, Gitlab, Gitee, or Bitbucket) notify you of changes in a repository through a webhook. +You can configure the webhook through the provider’s user interface as a URL and a set of events in which you are interested. +For instance, Github uses a POST to the webhook with a JSON body containing a list of commits and a header (X-Github-Event) set to push. +If you add a dependency on the spring-cloud-config-monitor library and activate the Spring Cloud Bus in your Config Server, then a /monitor endpoint is enabled.

When the webhook is activated, the Config Server sends a RefreshRemoteApplicationEvent targeted at the applications it thinks might have changed. +The change detection can be strategized. +However, by default, it looks for changes in files that match the application name (for example, foo.properties is targeted at the foo application, while application.properties is targeted at all applications). +The strategy to use when you want to override the behavior is PropertyPathNotificationExtractor, which accepts the request headers and body as parameters and returns a list of file paths that changed.

The default configuration works out of the box with Github, Gitlab, Gitee, or Bitbucket. +In addition to the JSON notifications from Github, Gitlab, Gitee, or Bitbucket, you can trigger a change notification by POSTing to /monitor with form-encoded body parameters in the pattern of path={name}. +Doing so broadcasts to applications matching the {name} pattern (which can contain wildcards).

[Note]Note

The RefreshRemoteApplicationEvent is transmitted only if the spring-cloud-bus is activated in both the Config Server and in the client application.

[Note]Note

The default configuration also detects filesystem changes in local git repositories. In that case, the webhook is not used. However, as soon as you edit a config file, a refresh is broadcast.

\ No newline at end of file diff --git a/multi/multi__quick_start.html b/multi/multi__quick_start.html index d7ad1feb..6fc3a9f0 100644 --- a/multi/multi__quick_start.html +++ b/multi/multi__quick_start.html @@ -1,38 +1,23 @@ - 1. Quick Start

1. Quick Start

Start the server:

$ cd spring-cloud-config-server
-$ ../mvnw spring-boot:run

The server is a Spring Boot application so you can run it from your -IDE instead if you prefer (the main class is -ConfigServerApplication). Then try out a client:

$ curl localhost:8888/foo/development
+   1. Quick Start

1. Quick Start

This quick start walks through using both the server and the client of Spring Cloud Config Server.

First, start the server, as follows:

$ cd spring-cloud-config-server
+$ ../mvnw spring-boot:run

The server is a Spring Boot application, so you can run it from your IDE if you prefer to do so (the main class is ConfigServerApplication).

Next try out a client, as follows:

$ curl localhost:8888/foo/development
 {"name":"foo","label":"master","propertySources":[
   {"name":"https://github.com/scratches/config-repo/foo-development.properties","source":{"bar":"spam"}},
   {"name":"https://github.com/scratches/config-repo/foo.properties","source":{"foo":"bar"}}
-]}

The default strategy for locating property sources is to clone a git -repository (at spring.cloud.config.server.git.uri) and use it to -initialize a mini SpringApplication. The mini-application’s -Environment is used to enumerate property sources and publish them -via a JSON endpoint.

The HTTP service has resources in the form:

/{application}/{profile}[/{label}]
+]}

The default strategy for locating property sources is to clone a git repository (at spring.cloud.config.server.git.uri) and use it to initialize a mini SpringApplication. +The mini-application’s Environment is used to enumerate property sources and publish them at a JSON endpoint.

The HTTP service has resources in the following form:

/{application}/{profile}[/{label}]
 /{application}-{profile}.yml
 /{label}/{application}-{profile}.yml
 /{application}-{profile}.properties
-/{label}/{application}-{profile}.properties

where the "application" is injected as the spring.config.name in the -SpringApplication (i.e. what is normally "application" in a regular -Spring Boot app), "profile" is an active profile (or comma-separated -list of properties), and "label" is an optional git label (defaults to -"master".)

Spring Cloud Config Server pulls configuration for remote clients -from a git repository (which must be provided):

spring:
+/{label}/{application}-{profile}.properties

where application is injected as the spring.config.name in the SpringApplication (what is normally application in a regular Spring Boot app), profile is an active profile (or comma-separated list of properties), and label is an optional git label (defaults to master.)

Spring Cloud Config Server pulls configuration for remote clients from a git repository (which must be provided), as shown in the following example:

spring:
   cloud:
     config:
       server:
         git:
-          uri: https://github.com/spring-cloud-samples/config-repo

1.1 Client Side Usage

To use these features in an application, just build it as a Spring -Boot application that depends on spring-cloud-config-client (e.g. see -the test cases for the config-client, or the sample app). The most -convenient way to add the dependency is via a Spring Boot starter -org.springframework.cloud:spring-cloud-starter-config. There is also a -parent pom and BOM (spring-cloud-starter-parent) for Maven users and a -Spring IO version management properties file for Gradle and Spring CLI -users. Example Maven configuration:

pom.xml.  + uri: https://github.com/spring-cloud-samples/config-repo

1.1 Client Side Usage

To use these features in an application, you can build it as a Spring Boot application that depends on spring-cloud-config-client (for an example, see the test cases for the config-client or the sample application). +The most convenient way to add the dependency is with a Spring Boot starter org.springframework.cloud:spring-cloud-starter-config. +There is also a parent pom and BOM (spring-cloud-starter-parent) for Maven users and a Spring IO version management properties file for Gradle and Spring CLI users. The following example shows a typical Maven configuration:

pom.xml. 

   <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
@@ -74,7 +59,7 @@ users. Example Maven configuration:

pom.xml.  </build> <!-- repositories also needed for snapshots and milestones -->

-

Then you can create a standard Spring Boot application, like this simple HTTP server:

@SpringBootApplication
+

Now you can create a standard Spring Boot application, such as the following HTTP server:

@SpringBootApplication
 @RestController
 public class Application {
 
@@ -87,19 +72,12 @@ public class Application {
         SpringApplication.run(Application.class, args);
     }
 
-}

When it runs it will pick up the external configuration from the -default local config server on port 8888 if it is running. To modify -the startup behaviour you can change the location of the config server -using bootstrap.properties (like application.properties but for -the bootstrap phase of an application context), e.g.

spring.cloud.config.uri: http://myconfigserver.com

The bootstrap properties will show up in the /env endpoint as a -high-priority property source, e.g.

$ curl localhost:8080/env
+}

When this HTTP server runs, it picks up the external configuration from the default local config server (if it is running) on port 8888. +To modify the startup behavior, you can change the location of the config server by using bootstrap.properties (similar to application.properties but for the bootstrap phase of an application context), as shown in the following example:

spring.cloud.config.uri: http://myconfigserver.com

The bootstrap properties show up in the /env endpoint as a high-priority property source, as shown in the following example.

$ curl localhost:8080/env
 {
   "profiles":[],
   "configService:https://github.com/spring-cloud-samples/config-repo/bar.properties":{"foo":"bar"},
   "servletContextInitParams":{},
   "systemProperties":{...},
   ...
-}

(a property source called "configService:<URL of remote -repository>/<file name>" contains the property "foo" with value -"bar" and is highest priority).

[Note]Note

the URL in the property source name is the git repository not -the config server URL.

\ No newline at end of file +}

A property source called ``configService:<URL of remote repository>/<file name> contains the foo property with a value of bar and is highest priority.

[Note]Note

The URL in the property source name is the git repository, not the config server URL.

\ No newline at end of file diff --git a/multi/multi__serving_alternative_formats.html b/multi/multi__serving_alternative_formats.html index d89facda..1a0c399d 100644 --- a/multi/multi__serving_alternative_formats.html +++ b/multi/multi__serving_alternative_formats.html @@ -1,25 +1,9 @@ - 3. Serving Alternative Formats

3. Serving Alternative Formats

The default JSON format from the environment endpoints is perfect for -consumption by Spring applications because it maps directly onto the -Environment abstraction. If you prefer you can consume the same data -as YAML or Java properties by adding a suffix to the resource path -(".yml", ".yaml" or ".properties"). This can be useful for consumption -by applications that do not care about the structure of the JSON -endpoints, or the extra metadata they provide, for example an -application that is not using Spring might benefit from the simplicity -of this approach.

The YAML and properties representations have an additional flag -(provided as a boolean query parameter resolvePlaceholders) to -signal that placeholders in the source documents, in the standard -Spring ${…​} form, should be resolved in the output where possible -before rendering. This is a useful feature for consumers that don’t -know about the Spring placeholder conventions.

[Note]Note

there are limitations in using the YAML or properties formats, -mainly in relation to the loss of metadata. The JSON is structured as -an ordered list of property sources, for example, with names that -correlate with the source. The YAML and properties forms are coalesced -into a single map, even if the origin of the values has multiple -sources, and the names of the original source files are lost. The YAML -representation is not necessarily a faithful representation of the -YAML source in a backing repository either: it is constructed from a -list of flat property sources, and assumptions have to be made about -the form of the keys.

\ No newline at end of file + 3. Serving Alternative Formats

3. Serving Alternative Formats

The default JSON format from the environment endpoints is perfect for consumption by Spring applications, because it maps directly onto the Environment abstraction. +If you prefer, you can consume the same data as YAML or Java properties by adding a suffix (".yml", ".yaml" or ".properties") to the resource path. +This can be useful for consumption by applications that do not care about the structure of the JSON endpoints or the extra metadata they provide (for example, an application that is not using Spring might benefit from the simplicity of this approach).

The YAML and properties representations have an additional flag (provided as a boolean query parameter called resolvePlaceholders) to signal that placeholders in the source documents (in the standard Spring ${…​} form) should be resolved in the output before rendering, where possible. +This is a useful feature for consumers that do not know about the Spring placeholder conventions.

[Note]Note

There are limitations in using the YAML or properties formats, mainly in relation to the loss of metadata. +For example, the JSON is structured as an ordered list of property sources, with names that correlate with the source. +The YAML and properties forms are coalesced into a single map, even if the origin of the values has multiple sources, and the names of the original source files are lost. +Also, the YAML representation is not necessarily a faithful representation of the YAML source in a backing repository either. It is constructed from a list of flat property sources, and assumptions have to be made about the form of the keys.

\ No newline at end of file diff --git a/multi/multi__serving_plain_text.html b/multi/multi__serving_plain_text.html index 1d2e02af..7892d605 100644 --- a/multi/multi__serving_plain_text.html +++ b/multi/multi__serving_plain_text.html @@ -1,21 +1,12 @@ - 4. Serving Plain Text

4. Serving Plain Text

Instead of using the Environment abstraction (or one of the -alternative representations of it in YAML or properties format) your -applications might need generic plain text configuration files, -tailored to their environment. The Config Server provides these -through an additional endpoint at /{name}/{profile}/{label}/{path} -where "name", "profile" and "label" have the same meaning as the -regular environment endpoint, but "path" is a file name -(e.g. log.xml). The source files for this endpoint are located in -the same way as for the environment endpoints: the same search path is -used as for properties or YAML files, but instead of aggregating all -matching resources, only the first one to match is returned.

After a resource is located, placeholders in the normal format -(${…​}) are resolved using the effective Environment for the -application name, profile and label supplied. In this way the resource -endpoint is tightly integrated with the environment -endpoints. Example, if you have this layout for a GIT (or SVN) -repository:

application.yml
+   4. Serving Plain Text

4. Serving Plain Text

Instead of using the Environment abstraction (or one of the alternative representations of it in YAML or properties format), your applications might need generic plain-text configuration files that are tailored to their environment. +The Config Server provides these through an additional endpoint at /{name}/{profile}/{label}/{path}, where name, profile, and label have the same meaning as the regular environment endpoint, but path is a file name (such as log.xml). +The source files for this endpoint are located in the same way as for the environment endpoints. +The same search path is used for properties and YAML files. +However, instead of aggregating all matching resources, only the first one to match is returned.

After a resource is located, placeholders in the normal format (${…​}) are resolved by using the effective Environment for the supplied application name, profile, and label. +In this way, the resource endpoint is tightly integrated with the environment endpoints. +Consider the following example for a GIT or SVN repository:

application.yml
 nginx.conf

where nginx.conf looks like this:

server {
     listen              80;
     server_name         ${nginx.server.name};
@@ -27,14 +18,12 @@ nginx.conf

where nginx.conf looks like this profiles: development nginx: server: - name: develop.com

then the /foo/default/master/nginx.conf resource looks like this:

server {
+    name: develop.com

The /foo/default/master/nginx.conf resource might be as follows:

server {
     listen              80;
     server_name         example.com;
 }

and /foo/development/master/nginx.conf like this:

server {
     listen              80;
     server_name         develop.com;
-}
[Note]Note

Just like the source files for environment configuration, the -"profile" is used to resolve the file name, so if you want a -profile-specific file then /*/development/*/logback.xml will be -resolved by a file called logback-development.xml (in preference -to logback.xml).

[Note]Note

If you do not want to supply the label and let the server use the default label, you can supply a useDefaultLabel request parameter. So, the above example for the default profile could look like /foo/default/nginx.conf?useDefaultLabel.

\ No newline at end of file +}
[Note]Note

As with the source files for environment configuration, the profile is used to resolve the file name. +So, if you want a profile-specific file, /*/development/*/logback.xml can be resolved by a file called logback-development.xml (in preference to logback.xml).

[Note]Note

If you do not want to supply the label and let the server use the default label, you can supply a useDefaultLabel request parameter. +So, the preceding example for the default profile could be /foo/default/nginx.conf?useDefaultLabel.

\ No newline at end of file diff --git a/multi/multi__spring_cloud_config_client.html b/multi/multi__spring_cloud_config_client.html index c58d32ca..d198929d 100644 --- a/multi/multi__spring_cloud_config_client.html +++ b/multi/multi__spring_cloud_config_client.html @@ -1,38 +1,18 @@ - 7. Spring Cloud Config Client

7. Spring Cloud Config Client

A Spring Boot application can take immediate advantage of the Spring -Config Server (or other external property sources provided by the -application developer), and it will also pick up some additional -useful features related to Environment change events.

7.1 Config First Bootstrap

This is the default behaviour for any application which has the Spring -Cloud Config Client on the classpath. When a config client starts up -it binds to the Config Server (via the bootstrap configuration -property spring.cloud.config.uri) and initializes Spring -Environment with remote property sources.

The net result of this is that all client apps that want to consume -the Config Server need a bootstrap.yml (or an environment variable) -with the server address in spring.cloud.config.uri (defaults to -"http://localhost:8888").

7.2 Discovery First Bootstrap

If you are using a `DiscoveryClient implementation, such as Spring Cloud Netflix -and Eureka Service Discovery or Spring Cloud Consul (Spring Cloud Zookeeper does -not support this yet), then you can have the Config Server register with the -Discovery Service if you want to, but in the default "Config First" mode, -clients won’t be able to take advantage of the registration.

If you prefer to use DiscoveryClient to locate the Config Server, you can do -that by setting spring.cloud.config.discovery.enabled=true (default -"false"). The net result of that is that client apps all need a -bootstrap.yml (or an environment variable) with the appropriate discovery -configuration. For example, with Spring Cloud Netflix, you need to define the -Eureka server address, e.g. in eureka.client.serviceUrl.defaultZone. The -price for using this option is an extra network round trip on start up to -locate the service registration. The benefit is that the Config Server -can change its co-ordinates, as long as the Discovery Service is a fixed point. The -default service id is "configserver" but you can change that on the -client with spring.cloud.config.discovery.serviceId (and on the server -in the usual way for a service, e.g. by setting spring.application.name).

The discovery client implementations all support some kind of metadata -map (e.g. for Eureka we have eureka.instance.metadataMap). Some -additional properties of the Config Server may need to be configured -in its service registration metadata so that clients can connect -correctly. If the Config Server is secured with HTTP Basic you can -configure the credentials as "username" and "password". And if the -Config Server has a context path you can set "configPath". Example, -for a Config Server that is a Eureka client:

bootstrap.yml.  + 7. Spring Cloud Config Client

7. Spring Cloud Config Client

A Spring Boot application can take immediate advantage of the Spring Config Server (or other external property sources provided by the application developer). +It also picks up some additional useful features related to Environment change events.

7.1 Config First Bootstrap

The default behavior for any application that has the Spring Cloud Config Client on the classpath is as follows: +When a config client starts, it binds to the Config Server (through the spring.cloud.config.uri bootstrap configuration property) and initializes Spring Environment with remote property sources.

The net result of this behavior is that all client applciations that want to consume the Config Server need a bootstrap.yml (or an environment variable) with the server address set in spring.cloud.config.uri (it defaults to "http://localhost:8888").

7.2 Discovery First Bootstrap

If you use a `DiscoveryClient implementation, such as Spring Cloud Netflix and Eureka Service Discovery or Spring Cloud Consul, you can have the Config Server register with the Discovery Service. +However, in the default “Config First” mode, clients cannot take advantage of the registration.

If you prefer to use DiscoveryClient to locate the Config Server, you can do so by setting spring.cloud.config.discovery.enabled=true (the default is false). +The net result of doing so is that client applications all need a bootstrap.yml (or an environment variable) with the appropriate discovery configuration. +For example, with Spring Cloud Netflix, you need to define the Eureka server address (for example, in eureka.client.serviceUrl.defaultZone). +The price for using this option is an extra network round trip on startup, to locate the service registration. +The benefit is that, as long as the Discovery Service is a fixed point, the Config Server can change its coordinates. +The default service ID is configserver, but you can change that on the client by setting spring.cloud.config.discovery.serviceId (and on the server, in the usual way for a service, such as by setting spring.application.name).

The discovery client implementations all support some kind of metadata map (for example, we have eureka.instance.metadataMap for Eureka). +Some additional properties of the Config Server may need to be configured in its service registration metadata so that clients can connect correctly. +If the Config Server is secured with HTTP Basic, you can configure the credentials as username and password. +Also, if the Config Server has a context path, you can set configPath. +For example, the following YAML file is for a Config Server that is a Eureka client:

bootstrap.yml. 

eureka:
   instance:
     ...
@@ -40,57 +20,44 @@ for a Config Server that is a Eureka client:

bootstrap.yml.  user: osufhalskjrtl password: lviuhlszvaorhvlo5847 configPath: /config

-

7.3 Config Client Fail Fast

In some cases, it may be desirable to fail startup of a service if -it cannot connect to the Config Server. If this is the desired -behavior, set the bootstrap configuration property -spring.cloud.config.fail-fast=true and the client will halt with -an Exception.

7.4 Config Client Retry

If you expect that the config server may occasionally be unavailable when -your app starts, you can ask it to keep trying after a failure. First you need -to set spring.cloud.config.fail-fast=true, and then you need to add -spring-retry and spring-boot-starter-aop to your classpath. The default -behaviour is to retry 6 times with an initial backoff interval of 1000ms and an -exponential multiplier of 1.1 for subsequent backoffs. You can configure these -properties (and others) using spring.cloud.config.retry.* configuration properties.

[Tip]Tip

To take full control of the retry add a @Bean of type -RetryOperationsInterceptor with id "configServerRetryInterceptor". Spring -Retry has a RetryInterceptorBuilder that makes it easy to create one.

7.5 Locating Remote Configuration Resources

The Config Service serves property sources from /{name}/{profile}/{label}, where the default bindings in the client app are

  • "name" = ${spring.application.name}
  • "profile" = ${spring.profiles.active} (actually Environment.getActiveProfiles())
  • "label" = "master"

All of them can be overridden by setting spring.cloud.config.* -(where * is "name", "profile" or "label"). The "label" is useful for -rolling back to previous versions of configuration; with the default -Config Server implementation it can be a git label, branch name or -commit id. Label can also be provided as a comma-separated list, in -which case the items in the list are tried on-by-one until one succeeds. -This can be useful when working on a feature branch, for instance, -when you might want to align the config label with your branch, but -make it optional (e.g. spring.cloud.config.label=myfeature,develop).

7.6 Security

If you use HTTP Basic security on the server then clients just need to -know the password (and username if it isn’t the default). You can do -that via the config server URI, or via separate username and password -properties, e.g.

bootstrap.yml.  +

7.3 Config Client Fail Fast

In some cases, you may want to fail startup of a service if it cannot connect to the Config Server. +If this is the desired behavior, set the bootstrap configuration property spring.cloud.config.fail-fast=true to make the client halt with an Exception.

7.4 Config Client Retry

If you expect that the config server may occasionally be unavailable when your application starts, you can make it keep trying after a failure. +First, you need to set spring.cloud.config.fail-fast=true. +Then you need to add spring-retry and spring-boot-starter-aop to your classpath. +The default behavior is to retry six times with an initial backoff interval of 1000ms and an exponential multiplier of 1.1 for subsequent backoffs. +You can configure these properties (and others) by setting the spring.cloud.config.retry.* configuration properties.

[Tip]Tip

To take full control of the retry behavior, add a @Bean of type RetryOperationsInterceptor with an ID of configServerRetryInterceptor. +Spring Retry has a RetryInterceptorBuilder that supports creating one.

7.5 Locating Remote Configuration Resources

The Config Service serves property sources from /{name}/{profile}/{label}, where the default bindings in the client app are as follows:

  • "name" = ${spring.application.name}
  • "profile" = ${spring.profiles.active} (actually Environment.getActiveProfiles())
  • "label" = "master"

You can override all of them by setting spring.cloud.config.* (where * is name, profile or label). +The label is useful for rolling back to previous versions of configuration. +With the default Config Server implementation, it can be a git label, branch name, or commit ID. +Label can also be provided as a comma-separated list. +In that case, the items in the list are tried one by one until one succeeds. +This behavior can be useful when working on a feature branch. +For instance, you might want to align the config label with your branch but make it optional (in that case, use spring.cloud.config.label=myfeature,develop).

7.6 Security

If you use HTTP Basic security on the server, clients need to know the password (and username if it is not the default). +You can specify the username and password through the config server URI or via separate username and password properties, as shown in the following example:

bootstrap.yml. 

spring:
   cloud:
     config:
      uri: https://user:secret@myconfig.mycompany.com

-

or

bootstrap.yml.  +

The following example shows an alternate way to pass the same information:

bootstrap.yml. 

spring:
   cloud:
     config:
      uri: https://myconfig.mycompany.com
      username: user
      password: secret

-

The spring.cloud.config.password and spring.cloud.config.username -values override anything that is provided in the URI.

If you deploy your apps on Cloud Foundry then the best way to provide -the password is through service credentials, e.g. in the URI, since -then it doesn’t even need to be in a config file. An example which -works locally and for a user-provided service on Cloud Foundry named -"configserver":

bootstrap.yml.  +

The spring.cloud.config.password and spring.cloud.config.username values override anything that is provided in the URI.

If you deploy your apps on Cloud Foundry, the best way to provide the password is through service credentials (such as in the URI, since it does not need to be in a config file). +The following example works locally and for a user-provided service on Cloud Foundry named configserver:

bootstrap.yml. 

spring:
   cloud:
     config:
      uri: ${vcap.services.configserver.credentials.uri:http://user:password@localhost:8888}

-

If you use another form of security you might need to provide a -RestTemplate to the ConfigServicePropertySourceLocator (e.g. by -grabbing it in the bootstrap context and injecting one).

7.6.1 Health Indicator

The Config Client supplies a Spring Boot Health Indicator that attempts to load configuration from Config Server. The health indicator can be disabled by setting health.config.enabled=false. The response is also cached for performance reasons. The default cache time to live is 5 minutes. To change that value set the health.config.time-to-live property (in milliseconds).

7.6.2 Providing A Custom RestTemplate

In some cases you might need to customize the requests made to the config server from -the client. Typically this involves passing special Authorization headers to -authenticate requests to the server. To provide a custom RestTemplate follow the -steps below.

  1. Create a new configuration bean with an implementation of PropertySourceLocator.

CustomConfigServiceBootstrapConfiguration.java.  +

If you use another form of security, you might need to provide a RestTemplate to the ConfigServicePropertySourceLocator (for example, by grabbing it in the bootstrap context and injecting it).

7.6.1 Health Indicator

The Config Client supplies a Spring Boot Health Indicator that attempts to load configuration from the Config Server. +The health indicator can be disabled by setting health.config.enabled=false. +The response is also cached for performance reasons. +The default cache time to live is 5 minutes. +To change that value, set the health.config.time-to-live property (in milliseconds).

7.6.2 Providing A Custom RestTemplate

In some cases, you might need to customize the requests made to the config server from the client. +Typically, doing so involves passing special Authorization headers to authenticate requests to the server. +To provide a custom RestTemplate:

  1. Create a new configuration bean with an implementation of PropertySourceLocator, as shown in the following example:

CustomConfigServiceBootstrapConfiguration.java. 

@Configuration
 public class CustomConfigServiceBootstrapConfiguration {
     @Bean
@@ -101,17 +68,16 @@ steps below.

  1. return configServicePropertySourceLocator; } }

-

  1. In resources/META-INF create a file called -spring.factories and specify your custom configuration.

spring.factories.  +

  1. In resources/META-INF, create a file called +spring.factories and specify your custom configuration, as shown in the following example:

spring.factories. 

org.springframework.cloud.bootstrap.BootstrapConfiguration = com.my.config.client.CustomConfigServiceBootstrapConfiguration

-

7.6.3 Vault

When using Vault as a backend to your config server the client will need to -supply a token for the server to retrieve values from Vault. This token -can be provided within the client by setting spring.cloud.config.token -in bootstrap.yml.

bootstrap.yml.  +

7.6.3 Vault

When using Vault as a backend to your config server, the client needs to supply a token for the server to retrieve values from Vault. +This token can be provided within the client by setting spring.cloud.config.token +in bootstrap.yml, as shown in the following example:

bootstrap.yml. 

spring:
   cloud:
     config:
       token: YourVaultToken

-

7.7 Vault

7.7.1 Nested Keys In Vault

Vault supports the ability to nest keys in a value stored in Vault. For example

echo -n '{"appA": {"secret": "appAsecret"}, "bar": "baz"}' | vault write secret/myapp -

This command will write a JSON object to your Vault. To access these values in Spring -you would use the traditional dot(.) annotation. For example

@Value("${appA.secret}")
-String name = "World";

The above code would set the name variable to appAsecret.

\ No newline at end of file +

7.7 Nested Keys In Vault

Vault supports the ability to nest keys in a value stored in Vault, as shown in the following example:

echo -n '{"appA": {"secret": "appAsecret"}, "bar": "baz"}' | vault write secret/myapp -

This command writes a JSON object to your Vault. +To access these values in Spring, you would use the traditional dot(.) annotation, as shown in the following example

@Value("${appA.secret}")
+String name = "World";

The preceding code would sets the value of the name variable to appAsecret.

\ No newline at end of file diff --git a/multi/multi__spring_cloud_config_server.html b/multi/multi__spring_cloud_config_server.html index 6fc7a844..f2198e02 100644 --- a/multi/multi__spring_cloud_config_server.html +++ b/multi/multi__spring_cloud_config_server.html @@ -1,9 +1,8 @@ - 2. Spring Cloud Config Server

2. Spring Cloud Config Server

The Server provides an HTTP, resource-based API for external -configuration (name-value pairs, or equivalent YAML content). The -server is easily embeddable in a Spring Boot application using the -@EnableConfigServer annotation. So this app is a config server:

ConfigServer.java.  + 2. Spring Cloud Config Server

2. Spring Cloud Config Server

Spring Cloud Config Server provides an HTTP resource-based API for external configuration (name-value pairs or equivalent YAML content). +The server is embeddable in a Spring Boot application, by using the @EnableConfigServer annotation. +Consequently, the following application is a config server:

ConfigServer.java. 

@SpringBootApplication
 @EnableConfigServer
 public class ConfigServer {
@@ -11,103 +10,61 @@ server is easily embeddable in a Spring Boot application using the
     SpringApplication.run(ConfigServer.class, args);
   }
 }

-

Like all Spring Boot apps it runs on port 8080 by default, but you -can switch it to the conventional port 8888 in various ways. The -easiest, which also sets a default configuration repository, -is by launching it with spring.config.name=configserver (there -is a configserver.yml in the Config Server jar). Another is -to use your own application.properties, e.g.

application.properties.  +

Like all Spring Boot applications, it runs on port 8080 by default, but you can switch it to the more conventional port 8888 in various ways. +The easiest, which also sets a default configuration repository, is by launching it with spring.config.name=configserver (there is a configserver.yml in the Config Server jar). +Another is to use your own application.properties, as shown in the following example:

application.properties. 

server.port: 8888
 spring.cloud.config.server.git.uri: file://${user.home}/config-repo

-

where ${user.home}/config-repo is a git repository containing -YAML and properties files.

[Note]Note

in Windows you need an extra "/" in the file URL if it is -absolute with a drive prefix, e.g. file:///${user.home}/config-repo.

[Tip]Tip

Here’s a recipe for creating the git repository in the example -above:

$ cd $HOME
+

where ${user.home}/config-repo is a git repository containing YAML and properties files.

[Note]Note

On Windows, you need an extra "/" in the file URL if it is absolute with a drive prefix (for example,file:///${user.home}/config-repo).

[Tip]Tip

The following listing shows a recipe for creating the git repository in the preceding example:

$ cd $HOME
 $ mkdir config-repo
 $ cd config-repo
 $ git init .
 $ echo info.foo: bar > application.properties
 $ git add -A .
-$ git commit -m "Add application.properties"
[Warning]Warning

using the local filesystem for your git repository is -intended for testing only. Use a server to host your -configuration repositories in production.

[Warning]Warning

the initial clone of your configuration repository will -be quick and efficient if you only keep text files in it. If you start -to store binary files, especially large ones, you may experience -delays on the first request for configuration and/or out of memory -errors in the server.

2.1 Environment Repository

Where do you want to store the configuration data for the Config -Server? The strategy that governs this behaviour is the -EnvironmentRepository, serving Environment objects. This -Environment is a shallow copy of the domain from the Spring -Environment (including propertySources as the main feature). The -Environment resources are parametrized by three variables:

  • {application} maps to "spring.application.name" on the client side;
  • {profile} maps to "spring.profiles.active" on the client (comma separated list); and
  • {label} which is a server side feature labelling a "versioned" set of config files.

Repository implementations generally behave just like a Spring Boot -application loading configuration files from a "spring.config.name" -equal to the {application} parameter, and "spring.profiles.active" -equal to the {profiles} parameter. Precedence rules for profiles are -also the same as in a regular Boot application: active profiles take -precedence over defaults, and if there are multiple profiles the last -one wins (like adding entries to a Map).

Example: a client application has this bootstrap configuration:

bootstrap.yml.  +$ git commit -m "Add application.properties"

[Warning]Warning

Using the local filesystem for your git repository is intended for testing only. +You should use a server to host your configuration repositories in production.

[Warning]Warning

The initial clone of your configuration repository can be quick and efficient if you keep only text files in it. +If you store binary files, especially large ones, you may experience delays on the first request for configuration or encounter out of memory errors in the server.

2.1 Environment Repository

Where should you store the configuration data for the Config Server? +The strategy that governs this behaviour is the EnvironmentRepository, serving Environment objects. +This Environment is a shallow copy of the domain from the Spring Environment (including propertySources as the main feature). +The Environment resources are parametrized by three variables:

  • {application}, which maps to spring.application.name on the client side.
  • {profile}, which maps to spring.profiles.active on the client (comma-separated list).
  • {label}, which is a server side feature labelling a "versioned" set of config files.

Repository implementations generally behave like a Spring Boot application, loading configuration files from a spring.config.name equal to the {application} parameter, and spring.profiles.active equal to the {profiles} parameter. +Precedence rules for profiles are also the same as in a regular Spring Boot application: Active profiles take precedence over defaults, and, if there are multiple profiles, the last one wins (similar to adding entries to a Map).

The following sample client application has this bootstrap configuration:

bootstrap.yml. 

spring:
   application:
     name: foo
   profiles:
     active: dev,mysql

-

(as usual with a Spring Boot application, these properties could also -be set as environment variables or command line arguments).

If the repository is file-based, the server will create an -Environment from application.yml (shared between all clients), and -foo.yml (with foo.yml taking precedence). If the YAML files have -documents inside them that point to Spring profiles, those are applied -with higher precedence (in order of the profiles listed), and if -there are profile-specific YAML (or properties) files these are also -applied with higher precedence than the defaults. Higher precedence -translates to a PropertySource listed earlier in the -Environment. (These are the same rules as apply in a standalone -Spring Boot application.)

2.1.1 Git Backend

The default implementation of EnvironmentRepository uses a Git -backend, which is very convenient for managing upgrades and physical -environments, and also for auditing changes. To change the location of -the repository you can set the "spring.cloud.config.server.git.uri" -configuration property in the Config Server (e.g. in -application.yml). If you set it with a file: prefix it should work -from a local repository so you can get started quickly and easily -without a server, but in that case the server operates directly on the -local repository without cloning it (it doesn’t matter if it’s not -bare because the Config Server never makes changes to the "remote" -repository). To scale the Config Server up and make it highly -available, you would need to have all instances of the server pointing -to the same repository, so only a shared file system would work. Even -in that case it is better to use the ssh: protocol for a shared -filesystem repository, so that the server can clone it and use a local -working copy as a cache.

This repository implementation maps the {label} parameter of the -HTTP resource to a git label (commit id, branch name or tag). If the -git branch or tag name contains a slash ("/") then the label in the -HTTP URL should be specified with the special string "(_)" instead (to -avoid ambiguity with other URL paths). For example, if the label is -foo/bar, replacing the slash would result in a label that looks like -foo(_)bar. The inclusion of the special string "(_)" can also be -applied to the {application} parameter. Be careful with the brackets -in the URL if you are using a command line client like curl (e.g. -escape them from the shell with quotes '').

Placeholders in Git URI

Spring Cloud Config Server supports a git repository URL with -placeholders for the {application} and {profile} (and {label} if -you need it, but remember that the label is applied as a git label -anyway). So you can easily support a "one repo per application" policy -using (for example):

spring:
+

(As usual with a Spring Boot application, these properties could also be set by environment variables or command line arguments).

If the repository is file-based, the server creates an +Environment from application.yml (shared between all clients) and +foo.yml (with foo.yml taking precedence). +If the YAML files have documents inside them that point to Spring profiles, those are applied with higher precedence (in order of the profiles listed). +If there are profile-specific YAML (or properties) files, these are also applied with higher precedence than the defaults. +Higher precedence translates to a PropertySource listed earlier in the Environment. +(These same rules apply in a standalone Spring Boot application.)

2.1.1 Git Backend

The default implementation of EnvironmentRepository uses a Git backend, which is very convenient for managing upgrades and physical +environments and for auditing changes. +To change the location of the repository, you can set the spring.cloud.config.server.git.uri configuration property in the Config Server (for example in application.yml). +If you set it with a file: prefix, it should work from a local repository so that you can get started quickly and easily without a server. However, in that case, the server operates directly on the local repository without cloning it (it does not matter if it is not bare because the Config Server never makes changes to the "remote" repository). +To scale the Config Server up and make it highly available, you need to have all instances of the server pointing to the same repository, so only a shared file system would work. +Even in that case, it is better to use the ssh: protocol for a shared filesystem repository, so that the server can clone it and use a local working copy as a cache.

This repository implementation maps the {label} parameter of the HTTP resource to a git label (commit id, branch name, or tag). +If the git branch or tag name contains a slash (/), then the label in the HTTP URL should instead be specified with the special string $$_$$ (to avoid ambiguity with other URL paths). +For example, if the label is foo/bar, replacing the slash would result in the following label: foo($$_$$)bar. +The inclusion of the special string ($$_$$) can also be applied to the {application} parameter. +If you use a command-line client such as curl, be careful with the brackets in the URL — you should +escape them from the shell with single quotes ('').

Placeholders in Git URI

Spring Cloud Config Server supports a git repository URL with placeholders for the {application} and {profile} (and {label} if you need it, but remember that the label is applied as a git label anyway). +So you can support a “one repository per application” policy by using a structure similar to the following:

spring:
   cloud:
     config:
       server:
         git:
-          uri: https://github.com/myorg/{application}

or a "one repo per profile" policy using a similar pattern but with -{profile}.

Additionally, using the special string "(_)" within your -{application} parameters can enable support for multiple -organizations (for example):

spring:
+          uri: https://github.com/myorg/{application}

You can also support a “one repository per profile” policy by using a similar pattern but with +{profile}.

Additionally, using the special string "($$_$$)" within your {application} parameters can enable support for multiple +organizations, as shown in the following example:

spring:
   cloud:
     config:
       server:
         git:
-          uri: https://github.com/{application}

where {application} is provided at request time in the format -"organization(_)application".

Pattern Matching and Multiple Repositories

There is also support for more complex requirements with pattern -matching on the application and profile name. The pattern format is a -comma-separated list of {application}/{profile} names with wildcards -(where a pattern beginning with a wildcard may need to be -quoted). Example:

spring:
+          uri: https://github.com/{application}

where {application} is provided at request time in the following format: organization($$_$$)application.

Pattern Matching and Multiple Repositories

Spring Cloud Config also includes support for more complex requirements with pattern +matching on the application and profile name. +The pattern format is a comma-separated list of {application}/{profile} names with wildcards (note that a pattern beginning with a wildcard may need to be quoted), as shown in the following example:

spring:
   cloud:
     config:
       server:
@@ -120,20 +77,10 @@ quoted). Example:

              uri: https://github.com/special/config-repo
             local:
               pattern: local*
-              uri: file:/home/configsvc/config-repo

If {application}/{profile} does not match any of the patterns, it -will use the default uri defined under -"spring.cloud.config.server.git.uri". In the above example, for the -"simple" repository, the pattern is simple/* (i.e. it only matches -one application named "simple" in all profiles). The "local" -repository matches all application names beginning with "local" in all -profiles (the /* suffix is added automatically to any pattern that -doesn’t have a profile matcher).

[Note]Note

the "one-liner" short cut used in the "simple" example above can -only be used if the only property to be set is the URI. If you need to -set anything else (credentials, pattern, etc.) you need to use the full -form.

The pattern property in the repo is actually an array, so you can -use a YAML array (or [0], [1], etc. suffixes in properties files) -to bind to multiple patterns. You may need to do this if you are going -to run apps with multiple profiles. Example:

spring:
+              uri: file:/home/configsvc/config-repo

If {application}/{profile} does not match any of the patterns, it uses the default URI defined under spring.cloud.config.server.git.uri. +In the above example, for the “simple” repository, the pattern is simple/* (it only matches one application named simple in all profiles). The “local” repository matches all application names beginning with local in all profiles (the /* suffix is added automatically to any pattern that does not have a profile matcher).

[Note]Note

The “one-liner” short cut used in the “simple” example can be used only if the only property to be set is the URI. +If you need to set anything else (credentials, pattern, and so on) you need to use the full form.

The pattern property in the repo is actually an array, so you can use a YAML array (or [0], [1], etc. suffixes in properties files) to bind to multiple patterns. +You may need to do so if you are going to run apps with multiple profiles, as shown in the following example:

spring:
   cloud:
     config:
       server:
@@ -149,24 +96,17 @@ to run apps with multiple profiles. Example:

              pattern:
                 - '*/qa'
                 - '*/production'
-              uri: https://github.com/staging/config-repo
[Note]Note

Spring Cloud will guess that a pattern containing a profile that -doesn’t end in * implies that you actually want to match a list of -profiles starting with this pattern (so */staging is a shortcut for -["*/staging", "*/staging,*"]). This is common where you need to run -apps in the "development" profile locally but also the "cloud" profile -remotely, for instance.

Every repository can also optionally store config files in -sub-directories, and patterns to search for those directories can be -specified as searchPaths. For example at the top level:

spring:
+              uri: https://github.com/staging/config-repo
[Note]Note

Spring Cloud guesses that a pattern containing a profile that does not end in * implies that you actually want to match a list of profiles starting with this pattern (so */staging is a shortcut for ["*/staging", "*/staging,*"], and so on). +This is common where, for instance, you need to run applications in the “development” profile locally but also the “cloud” profile remotely.

Every repository can also optionally store config files in sub-directories, and patterns to search for those directories can be specified as searchPaths. +The following example shows a config file at the top level:

spring:
   cloud:
     config:
       server:
         git:
           uri: https://github.com/spring-cloud-samples/config-repo
-          searchPaths: foo,bar*

In this example the server searches for config files in the top level -and in the "foo/" sub-directory and also any sub-directory whose name -begins with "bar".

By default the server clones remote repositories when configuration -is first requested. The server can be configured to clone the repositories -at startup. For example at the top level:

spring:
+          searchPaths: foo,bar*

In the preceding example, the server searches for config files in the top level and in the foo/ sub-directory and also any sub-directory whose name begins with bar.

By default, the server clones remote repositories when configuration +is first requested. +The server can be configured to clone the repositories at startup, as shown in the following top-level example:

spring:
   cloud:
     config:
       server:
@@ -183,48 +123,33 @@ at startup. For example at the top level:

                uri: http://git/team-b/config-repo.git
             team-c:
                 pattern: team-c-*
-                uri: http://git/team-a/config-repo.git

In this example the server clones team-a’s config-repo on startup before it -accepts any requests. All other repositories will not be cloned until -configuration from the repository is requested.

[Note]Note

Setting a repository to be cloned when the Config Server starts up can -help to identify a misconfigured configuration source (e.g., an invalid -repository URI) quickly, while the Config Server is starting up. With -cloneOnStart not enabled for a configuration source, the Config Server may -start successfully with a misconfigured or invalid configuration source and -not detect an error until an application requests configuration from that -configuration source.

Authentication

To use HTTP basic authentication on the remote repository add the -"username" and "password" properties separately (not in the URL), -e.g.

spring:
+                uri: http://git/team-a/config-repo.git

In the preceding example, the server clones team-a’s config-repo on startup, before it +accepts any requests. +All other repositories are not cloned until configuration from the repository is requested.

[Note]Note

Setting a repository to be cloned when the Config Server starts up can help to identify a misconfigured configuration source (such as an invalid repository URI) quickly, while the Config Server is starting up. +With cloneOnStart not enabled for a configuration source, the Config Server may start successfully with a misconfigured or invalid configuration source and not detect an error until an application requests configuration from that configuration source.

Authentication

To use HTTP basic authentication on the remote repository, add the username and password properties separately (not in the URL), as shown in the following example:

spring:
   cloud:
     config:
       server:
         git:
           uri: https://github.com/spring-cloud-samples/config-repo
           username: trolley
-          password: strongpassword

If you don’t use HTTPS and user credentials, SSH should also work out -of the box when you store keys in the default directories (~/.ssh) -and the uri points to an SSH location, -e.g. "git@github.com:configuration/cloud-configuration". It is important that an entry for the Git server be present in the ~/.ssh/known_hosts file and that it is in ssh-rsa format. Other formats (like ecdsa-sha2-nistp256) are not supported. To avoid surprises, you should ensure that only one entry is present in the known_hosts file for the Git server and that it is matching with the URL you provided to the config server. If you used a hostname in the URL, you want to have exactly that in the known_hosts file, not the IP. -The repository is accessed using JGit, so any documentation you find on -that should be applicable. HTTPS proxy settings can be set in -~/.git/config or in the same way as for any other JVM process via -system properties (-Dhttps.proxyHost and -Dhttps.proxyPort).

[Tip]Tip

If you don’t know where your ~/.git directory is use git config ---global to manipulate the settings (e.g. git config --global -http.sslVerify false).

Authentication with AWS CodeCommit

AWS CodeCommit authentication can also be -done. AWS CodeCommit uses an authentication helper when using Git from the command line. This helper is not -used with the JGit library, so a JGit CredentialProvider for AWS CodeCommit will be created if the Git -URI matches the AWS CodeCommit pattern. AWS CodeCommit URIs always look like -https://git-codecommit.${AWS_REGION}.amazonaws.com/${repopath}.

If you provide a username and password with an AWS CodeCommit URI, then these must be -the AWS accessKeyId and secretAccessKey -to be used to access the repository. If you do not specify a username and password, -then the accessKeyId and secretAccessKey will be retrieved using the -AWS Default Credential Provider Chain.

If your Git URI matches the CodeCommit URI pattern (above) then you must provide -valid AWS credentials in the username and password, or in one of the locations supported -by the default credential provider chain. AWS EC2 instances may use -IAM Roles for EC2 Instances.

Note: The aws-java-sdk-core jar is an optional dependency. If the aws-java-sdk-core jar is not on your -classpath, then the AWS Code Commit credential provider will not be created regardless of the git server URI.

Git SSH configuration using properties

By default, the JGit library used by Spring Cloud Config Server uses SSH configuration files such as ~/.ssh/known_hosts and /etc/ssh/ssh_config when connecting to Git repositories using an SSH URI. -In cloud environments such as Cloud Foundry, the local filesystem may be ephemeral or not easily accessible. For cases such as these, SSH configuration can be set using -Java properties. In order to activate property based SSH configuration, the property spring.cloud.config.server.git.ignoreLocalSshSettings must be set to true. -Example:

  spring:
+          password: strongpassword

If you do not use HTTPS and user credentials, SSH should also work out of the box when you store keys in the default directories (~/.ssh) and the URI points to an SSH location, such as git@github.com:configuration/cloud-configuration. +It is important that an entry for the Git server be present in the ~/.ssh/known_hosts file and that it is in ssh-rsa format. +Other formats (such as ecdsa-sha2-nistp256) are not supported. +To avoid surprises, you should ensure that only one entry is present in the known_hosts file for the Git server and that it matches the URL you provided to the config server. +If you use a hostname in the URL, you want to have exactly that (not the IP) in the known_hosts file. +The repository is accessed by using JGit, so any documentation you find on that should be applicable. +HTTPS proxy settings can be set in ~/.git/config or (in the same way as for any other JVM process) with +system properties (-Dhttps.proxyHost and -Dhttps.proxyPort).

[Tip]Tip

If you do not know where your ~/.git directory is, use git config --global to manipulate the settings (for example, git config --global http.sslVerify false).

Authentication with AWS CodeCommit

Spring Cloud Config Server also supports AWS CodeCommit authentication. +AWS CodeCommit uses an authentication helper when using Git from the command line. +This helper is not used with the JGit library, so a JGit CredentialProvider for AWS CodeCommit is created if the Git URI matches the AWS CodeCommit pattern. +AWS CodeCommit URIs follow this pattern://git-codecommit.${AWS_REGION}.amazonaws.com/${repopath}.

If you provide a username and password with an AWS CodeCommit URI, they must be the AWS accessKeyId and secretAccessKey that provide access to the repository. +If you do not specify a username and password, the accessKeyId and secretAccessKey are retrieved by using the AWS Default Credential Provider Chain.

If your Git URI matches the CodeCommit URI pattern (shown earlier), you must provide valid AWS credentials in the username and password or in one of the locations supported by the default credential provider chain. +AWS EC2 instances may use IAM Roles for EC2 Instances.

[Note]Note

The aws-java-sdk-core jar is an optional dependency. +If the aws-java-sdk-core jar is not on your classpath, the AWS Code Commit credential provider is not created, regardless of the git server URI.

Git SSH configuration using properties

By default, the JGit library used by Spring Cloud Config Server uses SSH configuration files such as ~/.ssh/known_hosts and /etc/ssh/ssh_config when connecting to Git repositories by using an SSH URI. +In cloud environments such as Cloud Foundry, the local filesystem may be ephemeral or not easily accessible. +For those cases, SSH configuration can be set by using Java properties. +In order to activate property-based SSH configuration, the spring.cloud.config.server.git.ignoreLocalSshSettings property must be set to true, as shown in the following example:

  spring:
     cloud:
       config:
         server:
@@ -260,30 +185,22 @@ Example:

69pcVH/4rmLbXdcmNYGm6iu+MlPQk4BUZknHSmVHIFdJ0EPupVaQ8RHT
-                         -----END RSA PRIVATE KEY-----

Table 2.1. SSH Configuration properties

Property NameRemarks

ignoreLocalSshSettings

If true, use property based SSH config instead of file based. Must be set at as spring.cloud.config.server.git.ignoreLocalSshSettings, not inside a repository definition.

privateKey

Valid SSH private key. Must be set if ignoreLocalSshSettings is true and Git URI is SSH format

hostKey

Valid SSH host key. Must be set if hostKeyAlgorithm is also set

hostKeyAlgorithm

One of ssh-dss, ssh-rsa, ecdsa-sha2-nistp256, ecdsa-sha2-nistp384 ,ecdsa-sha2-nistp521. Must be set if hostKey is also set

strictHostKeyChecking

true or false. If false, ignore errors with host key

knownHostsFile

Location of custom .known_hosts file

preferredAuthentications

Override server authentication method order. This should allow evade login prompts if server has keyboard-interactive authentication before publickey method.


Placeholders in Git Search Paths

Spring Cloud Config Server also supports a search path with -placeholders for the {application} and {profile} (and {label} if -you need it). Example:

spring:
+                         -----END RSA PRIVATE KEY-----

The following table describes the SSH configuration properties.

Table 2.1. SSH Configuration Properties

Property NameRemarks

ignoreLocalSshSettings

If true, use property-based instead of file-based SSH config. Must be set at as spring.cloud.config.server.git.ignoreLocalSshSettings, not inside a repository definition.

privateKey

Valid SSH private key. Must be set if ignoreLocalSshSettings is true and Git URI is SSH format.

hostKey

Valid SSH host key. Must be set if hostKeyAlgorithm is also set.

hostKeyAlgorithm

One of ssh-dss, ssh-rsa, ecdsa-sha2-nistp256, ecdsa-sha2-nistp384, or ecdsa-sha2-nistp521. Must be set if hostKey is also set.

strictHostKeyChecking

true or false. If false, ignore errors with host key.

knownHostsFile

Location of custom .known_hosts file.

preferredAuthentications

Override server authentication method order. This should allow for evading login prompts if server has keyboard-interactive authentication before the publickey method.


Placeholders in Git Search Paths

Spring Cloud Config Server also supports a search path with placeholders for the {application} and {profile} (and {label} if +you need it), as shown in the following example:

spring:
   cloud:
     config:
       server:
         git:
           uri: https://github.com/spring-cloud-samples/config-repo
-          searchPaths: '{application}'

searches the repository for files in the same name as the directory -(as well as the top level). Wildcards are also valid in a search -path with placeholders (any matching directory is included in the -search).

Force pull in Git Repositories

As mentioned before Spring Cloud Config Server makes a clone of the -remote git repository and if somehow the local copy gets dirty (e.g. -folder content changes by OS process) so Spring Cloud Config Server -cannot update the local copy from remote repository.

To solve this there is a force-pull property that will make Spring Cloud -Config Server force pull from remote repository if the local copy is dirty. -Example:

spring:
+          searchPaths: '{application}'

The preceding listing causes a search of the repository for files in the same name as the directory (as well as the top level). +Wildcards are also valid in a search path with placeholders (any matching directory is included in the search).

Force pull in Git Repositories

As mentioned earlier, Spring Cloud Config Server makes a clone of the remote git repository in case the local copy gets dirty (for example, +folder content changes by an OS process) such that Spring Cloud Config Server cannot update the local copy from remote repository.

To solve this issue, there is a force-pull property that makes Spring Cloud Config Server force pull from the remote repository if the local copy is dirty, as shown in the following example:

spring:
   cloud:
     config:
       server:
         git:
           uri: https://github.com/spring-cloud-samples/config-repo
-          force-pull: true

If you have a multiple repositories configuration you can configure the -force-pull property per repository. Example:

spring:
+          force-pull: true

If you have a multiple-repositories configuration, you can configure the force-pull property per repository, as shown in the following example:

spring:
   cloud:
     config:
       server:
@@ -314,49 +231,29 @@ Example:

      server:
         git:
           uri: https://github.com/spring-cloud-samples/config-repo
-          deleteUntrackedBranches: true
[Note]Note

The default value for deleteUntrackedBranches property is false.

2.1.2 Version Control Backend Filesystem Use

[Warning]Warning

With VCS based backends (git, svn) files are checked out or cloned to the local filesystem. By default they are put in the system temporary directory with a prefix of config-repo-. On linux, for example it could be /tmp/config-repo-<randomid>. Some operating systems routinely clean out temporary directories. This can lead to unexpected behaviour such as missing properties. To avoid this problem, change the directory Config Server uses, by setting spring.cloud.config.server.git.basedir or spring.cloud.config.server.svn.basedir to a directory that does not reside in the system temp structure.

2.1.3 File System Backend

There is also a "native" profile in the Config Server that doesn’t use -Git, but just loads the config files from the local classpath or file -system (any static URL you want to point to with -"spring.cloud.config.server.native.searchLocations"). To use the -native profile just launch the Config Server with -"spring.profiles.active=native".

[Note]Note

Remember to use the file: prefix for file resources (the -default without a prefix is usually the classpath). Just as with any -Spring Boot configuration you can embed ${}-style environment -placeholders, but remember that absolute paths in Windows require an -extra "/", e.g. file:///${user.home}/config-repo

[Warning]Warning

The default value of the searchLocations is identical to a -local Spring Boot application (so [classpath:/, classpath:/config, -file:./, file:./config]). This does not expose the -application.properties from the server to all clients because any -property sources present in the server are removed before being sent -to the client.

[Tip]Tip

A filesystem backend is great for getting started quickly and -for testing. To use it in production you need to be sure that the -file system is reliable, and shared across all instances of the -Config Server.

The search locations can contain placeholders for {application}, -{profile} and {label}. In this way you can segregate the -directories in the path, and choose a strategy that makes sense for -you (e.g. sub-directory per application, or sub-directory per -profile).

If you don’t use placeholders in the search locations, this repository -also appends the {label} parameter of the HTTP resource to a suffix -on the search path, so properties files are loaded from each search -location and a subdirectory with the same name as the label (the -labelled properties take precedence in the Spring Environment). Thus -the default behaviour with no placeholders is the same as adding a -search location ending with /{label}/. For example file:/tmp/config -is the same as file:/tmp/config,file:/tmp/config/{label}. This behavior can be -disabled by setting spring.cloud.config.server.native.addLabelLocations=false.

2.1.4 Vault Backend

Spring Cloud Config Server also supports Vault as a backend.

For more information on Vault see the Vault quickstart guide.

To enable the config server to use a Vault backend you can run your config server -with the vault profile. For example in your config server’s application.properties -you can add spring.profiles.active=vault.

By default the config server will assume your Vault server is running at -http://127.0.0.1:8200. It also will assume that the name of backend -is secret and the key is application. All of these defaults can be -configured in your config server’s application.properties. Below is a -table of configurable Vault properties. All properties are prefixed with -spring.cloud.config.server.vault.

NameDefault Value

host

127.0.0.1

port

8200

scheme

http

backend

secret

defaultKey

application

profileSeparator

,

All configurable properties can be found in -org.springframework.cloud.config.server.environment.VaultEnvironmentRepository.

With your config server running you can make HTTP requests to the server to retrieve -values from the Vault backend. To do this you will need a token for your Vault server.

First place some data in you Vault. For example

$ vault write secret/application foo=bar baz=bam
-$ vault write secret/myapp foo=myappsbar

Now make the HTTP request to your config server to retrieve the values.

$ curl -X "GET" "http://localhost:8888/myapp/default" -H "X-Config-Token: yourtoken"

You should see a response similar to this after making the above request.

{
+          deleteUntrackedBranches: true
[Note]Note

The default value for deleteUntrackedBranches property is false.

2.1.2 Version Control Backend Filesystem Use

[Warning]Warning

With VCS-based backends (git, svn), files are checked out or cloned to the local filesystem. +By default, they are put in the system temporary directory with a prefix of config-repo-. +On linux, for example, it could be /tmp/config-repo-<randomid>. +Some operating systems routinely clean out temporary directories. +This can lead to unexpected behavior, such as missing properties. +To avoid this problem, change the directory that Config Server uses by setting spring.cloud.config.server.git.basedir or spring.cloud.config.server.svn.basedir to a directory that does not reside in the system temp structure.

2.1.3 File System Backend

There is also a “native” profile in the Config Server that does not use Git but loads the config files from the local classpath or file system (any static URL you want to point to with spring.cloud.config.server.native.searchLocations). +To use the native profile, launch the Config Server with spring.profiles.active=native.

[Note]Note

Remember to use the file: prefix for file resources (the default without a prefix is usually the classpath). +As with any Spring Boot configuration, you can embed ${}-style environment placeholders, but remember that absolute paths in Windows require an extra / (for example, file:///${user.home}/config-repo).

[Warning]Warning

The default value of the searchLocations is identical to a local Spring Boot application (that is, [classpath:/, classpath:/config, +file:./, file:./config]). +This does not expose the application.properties from the server to all clients, because any property sources present in the server are removed before being sent to the client.

[Tip]Tip

A filesystem backend is great for getting started quickly and for testing. +To use it in production, you need to be sure that the file system is reliable and shared across all instances of the Config Server.

The search locations can contain placeholders for {application}, {profile}, and {label}. +In this way, you can segregate the directories in the path and choose a strategy that makes sense for you (such as subdirectory per application or subdirectory per profile).

If you do not use placeholders in the search locations, this repository also appends the {label} parameter of the HTTP resource to a suffix on the search path, so properties files are loaded from each search location and a subdirectory with the same name as the label (the labelled properties take precedence in the Spring Environment). +Thus, the default behaviour with no placeholders is the same as adding a search location ending with /{label}/. +For example, file:/tmp/config is the same as file:/tmp/config,file:/tmp/config/{label}. +This behavior can be disabled by setting spring.cloud.config.server.native.addLabelLocations=false.

2.1.4 Vault Backend

Spring Cloud Config Server also supports Vault as a backend.

For more information on Vault, see the Vault quick start guide.

To enable the config server to use a Vault backend, you can run your config server with the vault profile. +For example, in your config server’s application.properties, you can add spring.profiles.active=vault.

By default, the config server assumes that your Vault server runs at http://127.0.0.1:8200. +It also assumes that the name of backend is secret and the key is application. +All of these defaults can be configured in your config server’s application.properties. +The following table describes configurable Vault properties:

NameDefault Value

host

127.0.0.1

port

8200

scheme

http

backend

secret

defaultKey

application

profileSeparator

,

[Important]Important

All of the properties in the preceding table must be prefixed with spring.cloud.config.server.vault.

All configurable properties can be found in org.springframework.cloud.config.server.environment.VaultEnvironmentRepository.

With your config server running, you can make HTTP requests to the server to retrieve +values from the Vault backend. +To do so, you need a token for your Vault server.

First, place some data in you Vault, as shown in the following example:

$ vault write secret/application foo=bar baz=bam
+$ vault write secret/myapp foo=myappsbar

Second, make an HTTP request to your config server to retrieve the values, as shown in the following example:

$ curl -X "GET" "http://localhost:8888/myapp/default" -H "X-Config-Token: yourtoken"

You should see a response similar to the following:

{
    "name":"myapp",
    "profiles":[
       "default"
@@ -379,50 +276,23 @@ $ vault write secret/myapp foo=myappsbar

Now make the HTTP request to yo } } ] -}

Multiple Properties Sources

When using Vault you can provide your applications with multiple properties sources. -For example, assume you have written data to the following paths in Vault.

secret/myApp,dev
+}

Multiple Properties Sources

When using Vault, you can provide your applications with multiple properties sources. +For example, assume you have written data to the following paths in Vault:

secret/myApp,dev
 secret/myApp
 secret/application,dev
-secret/application

Properties written to secret/application are available to -all applications using the Config Server. An -application with the name myApp would have any properties -written to secret/myApp and secret/application available to it. -When myApp has the dev profile enabled then properties written to -all of the above paths would be available to it, with properties in -the first path in the list taking priority over the others.

2.1.5 Sharing Configuration With All Applications

File Based Repositories

With file-based (i.e. git, svn and native) repositories, resources -with file names in application* are shared between all client -applications (so application.properties, application.yml, -application-*.properties etc.). You can use resources with these -file names to configure global defaults and have them overridden by -application-specific files as necessary.

The #_property_overrides[property overrides] feature can also be used -for setting global defaults, and with placeholders applications are -allowed to override them locally.

[Tip]Tip

With the "native" profile (local file system backend) it is -recommended that you use an explicit search location that isn’t part -of the server’s own configuration. Otherwise the application* -resources in the default search locations are removed because they are -part of the server.

Vault Server

When using Vault as a backend you can share configuration with -all applications by placing configuration in -secret/application. For example, if you run this Vault command

$ vault write secret/application foo=bar baz=bam

All applications using the config server will have the properties -foo and baz available to them.

2.1.6 JDBC Backend

Spring Cloud Config Server supports JDBC (relation database) as a -backend for configuration properties. You can enable this feature by -adding spring-jdbc to the classpath, and using the "jdbc" profile, -or by adding a bean of type JdbcEnvironmentRepository. Spring Boot -will configure a data source if you include the right dependencies on -the classpath (see the user guide for more details on that).

The database needs to have a table called "PROPERTIES" with columns -"APPLICATION", "PROFILE", "LABEL" (with the usual Environment -meaning), plus "KEY" and "VALUE" for the key and value pairs in -Properties style. All fields are of type String in Java, so you can -make them VARCHAR of whatever length you need. Property values -behave in the same way as they would if they came from Spring Boot -properties files named {application}-{profile}.properties, including -all the encryption and decryption, which will be applied as -post-processing steps (i.e. not in the repository implementation -directly).

2.1.7 Composite Environment Repositories

In some scenarios you may wish to pull configuration data from multiple -environment repositories. To do this you can just enable -multiple profiles in your config server’s application properties or YAML file. -If, for example, you want to pull configuration data from a Git repository -as well as a SVN repository you would set the following properties for your -configuration server.

spring:
+secret/application

Properties written to secret/application are available to all applications using the Config Server. +An application with the name, myApp, would have any properties written to secret/myApp and secret/application available to it. +When myApp has the dev profile enabled, properties written to all of the above paths would be available to it, with properties in the first path in the list taking priority over the others.

2.1.5 Sharing Configuration With All Applications

Sharing configuration between all applications varies according to which approach you take, as described in the following topics:

File Based Repositories

With file-based (git, svn, and native) repositories, resources with file names in application* (application.properties, application.yml, application-*.properties, and so on) are shared between all client applications. +You can use resources with these file names to configure global defaults and have them be overridden by application-specific files as necessary.

The #_property_overrides[property overrides] feature can also be used for setting global defaults, with placeholders applications +allowed to override them locally.

[Tip]Tip

With the “native” profile (a local file system backend) , you should use an explicit search location that is not part of the server’s own configuration. +Otherwise, the application* resources in the default search locations get removed because they are part of the server.

Vault Server

When using Vault as a backend, you can share configuration with all applications by placing configuration in secret/application. +For example, if you run the following Vault command, all applications using the config server will have the properties foo and baz available to them:

$ vault write secret/application foo=bar baz=bam

2.1.6 JDBC Backend

Spring Cloud Config Server supports JDBC (relational database) as a backend for configuration properties. +You can enable this feature by adding spring-jdbc to the classpath and using the jdbc profile or by adding a bean of type JdbcEnvironmentRepository. +If you include the right dependencies on the classpath (see the user guide for more details on that), Spring Boot configures a data source.

The database needs to have a table called PROPERTIES with columns called APPLICATION, PROFILE, and LABEL (with the usual Environment meaning), plus KEY and VALUE for the key and value pairs in Properties style. +All fields are of type String in Java, so you can make them VARCHAR of whatever length you need. +Property values behave in the same way as they would if they came from Spring Boot properties files named {application}-{profile}.properties, including all the encryption and decryption, which will be applied as post-processing steps (that is, not in the repository implementation directly).

2.1.7 Composite Environment Repositories

In some scenarios, you may wish to pull configuration data from multiple environment repositories. +To do so, you can enable multiple profiles in your config server’s application properties or YAML file. +If, for example, you want to pull configuration data from a Git repository as well as an SVN repository, you can set the following properties for your configuration server:

spring:
   profiles:
     active: git, svn
   cloud:
@@ -433,48 +303,26 @@ configuration server.

          order: 2
         git:
           uri: file:///path/to/git/repo
-          order: 1

In addition to each repo specifying a URI, you can also specify an order property. -The order property allows you to specify the priority order for all your repositories. -The lower the numerical value of the order property the higher priority it will have. -The priority order of a repository will help resolve any potential conflicts between -repositories that contain values for the same properties.

[Note]Note

Any type of failure when retrieving values from an environment repositoy -will result in a failure for the entire composite environment.

[Note]Note

When using a composite environment it is important that all repos contain -the same label(s). If you have an environment similar to the one above and you request -configuration data with the label master but the SVN -repo does not contain a branch called master the entire request will fail.

Custom Composite Environment Repositories

It is also possible to provide your own EnvironmentRepository bean -to be included as part of a composite environment in addition to -using one of the environment repositories from Spring Cloud. To do this your bean -must implement the EnvironmentRepository interface. If you would like to control -the priority of you custom EnvironmentRepository within the composite -environment you should also implement the Ordered interface and override the -getOrdered method. If you do not implement the Ordered interface then your -EnvironmentRepository will be given the lowest priority.

2.1.8 Property Overrides

The Config Server has an "overrides" feature that allows the operator -to provide configuration properties to all applications that cannot be -accidentally changed by the application using the normal Spring Boot -hooks. To declare overrides just add a map of name-value pairs to -spring.cloud.config.server.overrides. For example

spring:
+          order: 1

In addition to each repository specifying a URI, you can also specify an order property. +The order property lets you specify the priority order for all your repositories. +The lower the numerical value of the order property, the higher priority it has. +The priority order of a repository helps resolve any potential conflicts between repositories that contain values for the same properties.

[Note]Note

Any type of failure when retrieving values from an environment repository results in a failure for the entire composite environment.

[Note]Note

When using a composite environment, it is important that all repositories contain the same labels. +If you have an environment similar to the one in the preceding example and you request configuration data with the master label but the SVN repository does not contain a branch called master, the entire request fails.

Custom Composite Environment Repositories

In addition to using one of the environment repositories from Spring Cloud, you can also provide your own EnvironmentRepository bean to be included as part of a composite environment. +To do so, your bean must implement the EnvironmentRepository interface. +If you want to control the priority of your custom EnvironmentRepository within the composite environment, you should also implement the Ordered interface and override the getOrdered method. +If you do not implement the Ordered interface, your EnvironmentRepository is given the lowest priority.

2.1.8 Property Overrides

The Config Server has an “overrides” feature that lets the operator provide configuration properties to all applications. +The overridden properties cannot be accidentally changed by the application with the normal Spring Boot hooks. +To declare overrides, add a map of name-value pairs to spring.cloud.config.server.overrides, as shown in the following example:

spring:
   cloud:
     config:
       server:
         overrides:
-          foo: bar

will cause all applications that are config clients to read foo=bar -independent of their own configuration. (Of course an application can -use the data in the Config Server in any way it likes, so overrides -are not enforceable, but they do provide useful default behaviour if -they are Spring Cloud Config clients.)

[Tip]Tip

Normal, Spring environment placeholders with "${}" can be escaped -(and resolved on the client) by using backslash ("\") to escape the -"$" or the "{", e.g. \${app.foo:bar} resolves to "bar" unless the -app provides its own "app.foo". Note that in YAML you don’t need to -escape the backslash itself, but in properties files you do, when you -configure the overrides on the server.

You can change the priority of all overrides in the client to be more -like default values, allowing applications to supply their own values -in environment variables or System properties, by setting the flag -spring.cloud.config.overrideNone=true (default is false) in the -remote repository.

2.2 Health Indicator

Config Server comes with a Health Indicator that checks if the configured -EnvironmentRepository is working. By default it asks the EnvironmentRepository -for an application named app, the default profile and the default -label provided by the EnvironmentRepository implementation.

You can configure the Health Indicator to check more applications -along with custom profiles and custom labels, e.g.

spring:
+          foo: bar

The preceding examples causes all applications that are config clients to read foo=bar, independent of their own configuration.

[Note]Note

A configuration system cannot force an application to use configuration data in any particular way. +Consequently, overrides are not enforceable. +However, they do provide useful default behavior for Spring Cloud Config clients.

[Tip]Tip

Normally, Spring environment placeholders with ${} can be escaped (and resolved on the client) by using backslash (\) to escape the $ or the {. +For example, \${app.foo:bar} resolves to bar, unless the app provides its own app.foo.

[Note]Note

In YAML, you do not need to escape the backslash itself. +However, in properties files, you do need to escape the backslash, when you configure the overrides on the server.

You can change the priority of all overrides in the client to be more like default values, letting applications supply their own values in environment variables or System properties, by setting the spring.cloud.config.overrideNone=true flag (the default is false) in the remote repository.

2.2 Health Indicator

Config Server comes with a Health Indicator that checks whether the configured EnvironmentRepository is working. +By default, it asks the EnvironmentRepository for an application named app, the default profile, and the default label provided by the EnvironmentRepository implementation.

You can configure the Health Indicator to check more applications along with custom profiles and custom labels, as shown in the following example:

spring:
   cloud:
     config:
       server:
@@ -484,115 +332,55 @@ along with custom profiles and custom labels, e.g.

              label: mylabel
             myservice-dev:
               name: myservice
-              profiles: development

You can disable the Health Indicator by setting spring.cloud.config.server.health.enabled=false.

2.3 Security

You are free to secure your Config Server in any way that makes sense -to you (from physical network security to OAuth2 bearer -tokens), and Spring Security and Spring Boot make it easy to do pretty -much anything.

To use the default Spring Boot configured HTTP Basic security, just -include Spring Security on the classpath (e.g. through -spring-boot-starter-security). The default is a username of "user" -and a randomly generated password, which isn’t going to be very useful -in practice, so we recommend you configure the password (via -spring.security.user.password) and encrypt it (see below for instructions -on how to do that).

2.4 Encryption and Decryption

[Important]Important

Prerequisites: to use the encryption and decryption features -you need the full-strength JCE installed in your JVM (it’s not there by default). -You can download the "Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files" -from Oracle, and follow instructions for installation (essentially replace the 2 policy files -in the JRE lib/security directory with the ones that you downloaded).

If the remote property sources contain encrypted content (values -starting with {cipher}) they will be decrypted before sending to -clients over HTTP. The main advantage of this set up is that the -property values don’t have to be in plain text when they are "at rest" -(e.g. in a git repository). If a value cannot be decrypted it is -removed from the property source and an additional property is added -with the same key, but prefixed with "invalid." and a value that means -"not applicable" (usually "<n/a>"). This is largely to prevent cipher -text being used as a password and accidentally leaking.

If you are setting up a remote config repository for config client -applications it might contain an application.yml like this, for -instance:

application.yml.  + profiles: development

You can disable the Health Indicator by setting spring.cloud.config.server.health.enabled=false.

2.3 Security

You can secure your Config Server in any way that makes sense to you (from physical network security to OAuth2 bearer tokens), because Spring Security and Spring Boot offer support for many security arrangements.

To use the default Spring Boot-configured HTTP Basic security, include Spring Security on the classpath (for example, through spring-boot-starter-security). +The default is a username of user and a randomly generated password. A random password is not useful in practice, so we recommend you configure the password (by setting spring.security.user.password) and encrypt it (see below for instructions on how to do that).

2.4 Encryption and Decryption

[Important]Important

To use the encryption and decryption features you need the full-strength JCE installed in your JVM (it is not included by default). +You can download the “Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files” from Oracle and follow the installation instructions (essentially, you need to replace the two policy files in the JRE lib/security directory with the ones that you downloaded).

If the remote property sources contain encrypted content (values starting with {cipher}), they are decrypted before sending to clients over HTTP. +The main advantage of this setup is that the property values need not be in plain text when they are “at rest” (for example, in a git repository). +If a value cannot be decrypted, it is removed from the property source and an additional property is added with the same key but prefixed with invalid and a value that means “not applicable” (usually <n/a>). +This is largely to prevent cipher text being used as a password and accidentally leaking.

If you set up a remote config repository for config client applications, it might contain an application.yml similar to the following:

application.yml. 

spring:
   datasource:
     username: dbuser
     password: '{cipher}FKSAJDFGYOS8F7GLHAKERGFHLSAJ'

-

Encrypted values in a .properties file must not be wrapped in quotes, otherwise the value will not be decrypted:

application.properties.  +

Encrypted values in a .properties file must not be wrapped in quotes. Otherwise, the value is not decrypted. The following example shows values that would work:

application.properties. 

spring.datasource.username: dbuser
 spring.datasource.password: {cipher}FKSAJDFGYOS8F7GLHAKERGFHLSAJ

-

You can safely push this plain text to a shared git repository and the -secret password is protected.

The server also exposes /encrypt and /decrypt endpoints (on the -assumption that these will be secured and only accessed by authorized -agents). If you are editing a remote config file you can use the Config Server -to encrypt values by POSTing to the /encrypt endpoint, e.g.

$ curl localhost:8888/encrypt -d mysecret
-682bc583f4641835fa2db009355293665d2647dade3375c0ee201de2a49f7bda
[Note]Note

If the value you are encrypting has characters in it that need to be URL encoded you should use -the --data-urlencode option to curl to make sure they are encoded properly.

[Tip]Tip

Be sure not to include any of the curl command statistics in the encrypted value. -Outputting the value to a file can help avoid this problem.

The inverse operation is also available via /decrypt (provided the server is -configured with a symmetric key or a full key pair):

$ curl localhost:8888/decrypt -d 682bc583f4641835fa2db009355293665d2647dade3375c0ee201de2a49f7bda
-mysecret
[Tip]Tip

If you are testing like this with curl, then use ---data-urlencode (instead of -d) or set an explicit Content-Type: -text/plain to make sure curl encodes the data correctly when there -are special characters ('+' is particularly tricky).

Take the encrypted value and add the {cipher} prefix before you put -it in the YAML or properties file, and before you commit and push it -to a remote, potentially insecure store.

The /encrypt and /decrypt endpoints also both accept paths of the -form /*/{name}/{profiles} which can be used to control cryptography -per application (name) and profile when clients call into the main -Environment resource.

[Note]Note

to control the cryptography in this granular way you must also -provide a @Bean of type TextEncryptorLocator that creates a -different encryptor per name and profiles. The one that is provided -by default does not do this (so all encryptions use the same key).

The spring command line client (with Spring Cloud CLI extensions -installed) can also be used to encrypt and decrypt, e.g.

$ spring encrypt mysecret --key foo
+

You can safely push this plain text to a shared git repository, and the secret password remains protected.

The server also exposes /encrypt and /decrypt endpoints (on the assumption that these are secured and only accessed by authorized agents). +If you edit a remote config file, you can use the Config Server to encrypt values by POSTing to the /encrypt endpoint, as shown in the following example:

$ curl localhost:8888/encrypt -d mysecret
+682bc583f4641835fa2db009355293665d2647dade3375c0ee201de2a49f7bda
[Note]Note

If the value you encrypt has characters in it that need to be URL encoded, you should use the --data-urlencode option to curl to make sure they are encoded properly.

[Tip]Tip

Be sure not to include any of the curl command statistics in the encrypted value. +Outputting the value to a file can help avoid this problem.

The inverse operation is also available through /decrypt (provided the server is +configured with a symmetric key or a full key pair), as shown in the following example:

$ curl localhost:8888/decrypt -d 682bc583f4641835fa2db009355293665d2647dade3375c0ee201de2a49f7bda
+mysecret
[Tip]Tip

If you testing with curl, then use --data-urlencode (instead of -d) or set an explicit Content-Type: text/plain to make sure curl encodes the data correctly when there are special characters ('+' is particularly tricky).

Take the encrypted value and add the {cipher} prefix before you put it in the YAML or properties file and before you commit and push it to a remote (potentially insecure) store.

The /encrypt and /decrypt endpoints also both accept paths in the form of /*/{name}/{profiles}, which can be used to control cryptography on a per-application (name) and per-profile basis when clients call into the main environment resource.

[Note]Note

To control the cryptography in this granular way, you must also provide a @Bean of type TextEncryptorLocator that creates a different encryptor per name and profiles. +The one that is provided by default does not do so (all encryptions use the same key).

The spring command line client (with Spring Cloud CLI extensions +installed) can also be used to encrypt and decrypt, as shown in the following example:

$ spring encrypt mysecret --key foo
 682bc583f4641835fa2db009355293665d2647dade3375c0ee201de2a49f7bda
 $ spring decrypt --key foo 682bc583f4641835fa2db009355293665d2647dade3375c0ee201de2a49f7bda
-mysecret

To use a key in a file (e.g. an RSA public key for encryption) prepend -the key value with "@" and provide the file path, e.g.

$ spring encrypt mysecret --key @${HOME}/.ssh/id_rsa.pub
-AQAjPgt3eFZQXwt8tsHAVv/QHiY5sI2dRcR+...

The key argument is mandatory (despite having a -- prefix).

2.5 Key Management

The Config Server can use a symmetric (shared) key or an asymmetric -one (RSA key pair). The asymmetric choice is superior in terms of -security, but it is often more convenient to use a symmetric key since -it is just a single property value to configure in the bootstrap.properties.

To configure a symmetric key you just need to set encrypt.key to a -secret String (or use an enviroment variable ENCRYPT_KEY to keep it -out of plain text configuration files).

To configure an asymmetric key you can either set the key as a -PEM-encoded text value (in encrypt.key), or via a keystore (e.g. as -created by the keytool utility that comes with the JDK). The -keystore properties are encrypt.keyStore.* with * equal to

  • location (a Resource location),
  • password (to unlock the keystore) and
  • alias (to identify which key in the store is to be -used).

The encryption is done with the public key, and a private key is -needed for decryption. Thus in principle you can configure only the -public key in the server if you only want to do encryption (and are -prepared to decrypt the values yourself locally with the private -key). In practice you might not want to do that because it spreads the -key management process around all the clients, instead of -concentrating it in the server. On the other hand it’s a useful option -if your config server really is relatively insecure and only a -handful of clients need the encrypted properties.

2.6 Creating a Key Store for Testing

To create a keystore for testing you can do something like this:

$ keytool -genkeypair -alias mytestkey -keyalg RSA \
+mysecret

To use a key in a file (such as an RSA public key for encryption), prepend +the key value with "@" and provide the file path, as shown in the following example:

$ spring encrypt mysecret --key @${HOME}/.ssh/id_rsa.pub
+AQAjPgt3eFZQXwt8tsHAVv/QHiY5sI2dRcR+...
[Note]Note

The --key argument is mandatory (despite having a -- prefix).

2.5 Key Management

The Config Server can use a symmetric (shared) key or an asymmetric one (RSA key pair). +The asymmetric choice is superior in terms of security, but it is often more convenient to use a symmetric key since it is a single property value to configure in the bootstrap.properties.

To configure a symmetric key, you need to set encrypt.key to a secret String (or use the ENCRYPT_KEY environment variable to keep it out of plain-text configuration files).

To configure an asymmetric key, you can either set the key as a PEM-encoded text value (in encrypt.key) or use a keystore (such as the keystore created by the keytool utility that comes with the JDK). +The following table describes the keystore properties:

PropertyDescription

encrypt.keyStore.location

Contains a Resource location

encrypt.keyStore.password

Holds the password that unlocks the keystore

encrypt.keyStore.alias

Identifies which key in the store to use

The encryption is done with the public key, and a private key is +needed for decryption. +Thus, in principle, you can configure only the public key in the server if you want to only encrypt (and are prepared to decrypt the values yourself locally with the private key). +In practice, you might not want to do decrypt locally, because it spreads the key management process around all the clients, instead of +concentrating it in the server. +On the other hand, it can be a useful option if your config server is relatively insecure and only a handful of clients need the encrypted properties.

2.6 Creating a Key Store for Testing

To create a keystore for testing, you can use a command resembling the following:

$ keytool -genkeypair -alias mytestkey -keyalg RSA \
   -dname "CN=Web Server,OU=Unit,O=Organization,L=City,S=State,C=US" \
-  -keypass changeme -keystore server.jks -storepass letmein

Put the server.jks file in the classpath (for instance) and then in -your bootstrap.yml for the Config Server:

encrypt:
+  -keypass changeme -keystore server.jks -storepass letmein

Put the server.jks file in the classpath (for instance) and then, in +your bootstrap.yml, for the Config Server, create the following settings:

encrypt:
   keyStore:
     location: classpath:/server.jks
     password: letmein
     alias: mytestkey
-    secret: changeme

2.7 Using Multiple Keys and Key Rotation

In addition to the {cipher} prefix in encrypted property values, the -Config Server looks for {name:value} prefixes (zero or many) before -the start of the (Base64 encoded) cipher text. The keys are passed to -a TextEncryptorLocator which can do whatever logic it needs to -locate a TextEncryptor for the cipher. If you have configured a -keystore (encrypt.keystore.location) the default locator will look -for keys in the store with aliases as supplied by the "key" prefix, -i.e. with a cipher text like this:

foo:
-  bar: `{cipher}{key:testkey}...`

the locator will look for a key named "testkey". A secret can also be -supplied via a {secret:…​} value in the prefix, but if it is not -the default is to use the keystore password (which is what you get -when you build a keytore and don’t specify a secret). If you do -supply a secret it is recommended that you also encrypt the secrets -using a custom SecretLocator.

Key rotation is hardly ever necessary on cryptographic grounds if the -keys are only being used to encrypt a few bytes of configuration data -(i.e. they are not being used elsewhere), but occasionally you might -need to change the keys if there is a security breach for instance. In -that case all the clients would need to change their source config -files (e.g. in git) and use a new {key:…​} prefix in all the -ciphers, checking beforehand of course that the key alias is available -in the Config Server keystore.

[Tip]Tip

the {name:value} prefixes can also be added to plaintext posted -to the /encrypt endpoint, if you want to let the Config Server -handle all encryption as well as decryption.

2.8 Serving Encrypted Properties

Sometimes you want the clients to decrypt the configuration locally, -instead of doing it in the server. In that case you can still have -/encrypt and /decrypt endpoints (if you provide the encrypt.* -configuration to locate a key), but you need to explicitly switch off -the decryption of outgoing properties using -spring.cloud.config.server.encrypt.enabled=false. If you don’t care -about the endpoints, then it should work if you configure neither the -key nor the enabled flag.

\ No newline at end of file + secret: changeme

2.7 Using Multiple Keys and Key Rotation

In addition to the {cipher} prefix in encrypted property values, the Config Server looks for zero or more {name:value} prefixes before the start of the (Base64 encoded) cipher text. +The keys are passed to a TextEncryptorLocator, which can do whatever logic it needs to locate a TextEncryptor for the cipher. +If you have configured a keystore (encrypt.keystore.location), the default locator looks for keys with aliases supplied by the key prefix, with a cipher text like resembling the following:

foo:
+  bar: `{cipher}{key:testkey}...`

The locator looks for a key named "testkey". +A secret can also be supplied by using a {secret:…​} value in the prefix. +However, if it is not supplied, the default is to use the keystore password (which is what you get when you build a keytore and do not specify a secret). +If you do supply a secret, you should also encrypt the secret using a custom SecretLocator.

When the keys are being used only to encrypt a few bytes of configuration data (that is, they are not being used elsewhere), key rotation is hardly ever necessary on cryptographic grounds. +However, you might occasionally need to change the keys (for example, in the event of a security breach). +In that case, all the clients would need to change their source config files (for example, in git) and use a new {key:…​} prefix in all the ciphers. +Note that the clients need to first check that the key alias is available in the Config Server keystore.

[Tip]Tip

If you want to let the Config Server handle all encryption as well as decryption, the {name:value} prefixes can also be added as plain text posted to the /encrypt endpoint, .

2.8 Serving Encrypted Properties

Sometimes you want the clients to decrypt the configuration locally, instead of doing it in the server. +In that case, if you provide the encrypt.* configuration to locate a key, you can still have /encrypt and /decrypt endpoints, but you need to explicitly switch off the decryption of outgoing properties by setting spring.cloud.config.server.encrypt.enabled=false. +If you do not care about the endpoints, it should work if you do not configure either the key or the enabled flag.

\ No newline at end of file diff --git a/multi/multi_pr01.html b/multi/multi_pr01.html index 728ec0b3..33d04f94 100644 --- a/multi/multi_pr01.html +++ b/multi/multi_pr01.html @@ -1,3 +1,7 @@ -

2.0.0.BUILD-SNAPSHOT

Spring Cloud Config provides server and client-side support for externalized configuration in a distributed system. With the Config Server you have a central place to manage external properties for applications across all environments. The concepts on both client and server map identically to the Spring Environment and PropertySource abstractions, so they fit very well with Spring applications, but can be used with any application running in any language. As an application moves through the deployment pipeline from dev to test and into production you can manage the configuration between those environments and be certain that applications have everything they need to run when they migrate. The default implementation of the server storage backend uses git so it easily supports labelled versions of configuration environments, as well as being accessible to a wide range of tooling for managing the content. It is easy to add alternative implementations and plug them in with Spring configuration.

\ No newline at end of file +

2.0.0.BUILD-SNAPSHOT

Spring Cloud Config provides server-side and client-side support for externalized configuration in a distributed system. With the Config Server, you have a central place to manage external properties for applications across all environments. +The concepts on both client and server map identically to the Spring Environment and PropertySource abstractions, so they fit very well with Spring applications but can be used with any application running in any language. +As an application moves through the deployment pipeline from dev to test and into production, you can manage the configuration between those environments and be certain that applications have everything they need to run when they migrate. +The default implementation of the server storage backend uses git, so it easily supports labelled versions of configuration environments as well as being accessible to a wide range of tooling for managing the content. +It is easy to add alternative implementations and plug them in with Spring configuration.

\ No newline at end of file diff --git a/multi/multi_spring-cloud-config.html b/multi/multi_spring-cloud-config.html index 09455401..596c842f 100644 --- a/multi/multi_spring-cloud-config.html +++ b/multi/multi_spring-cloud-config.html @@ -1,3 +1,3 @@ - Spring Cloud Config

Spring Cloud Config


Table of Contents

1. Quick Start
1.1. Client Side Usage
2. Spring Cloud Config Server
2.1. Environment Repository
2.1.1. Git Backend
Placeholders in Git URI
Pattern Matching and Multiple Repositories
Authentication
Authentication with AWS CodeCommit
Git SSH configuration using properties
Placeholders in Git Search Paths
Force pull in Git Repositories
Deleting untracked branches in Git Repositories
2.1.2. Version Control Backend Filesystem Use
2.1.3. File System Backend
2.1.4. Vault Backend
Multiple Properties Sources
2.1.5. Sharing Configuration With All Applications
File Based Repositories
Vault Server
2.1.6. JDBC Backend
2.1.7. Composite Environment Repositories
Custom Composite Environment Repositories
2.1.8. Property Overrides
2.2. Health Indicator
2.3. Security
2.4. Encryption and Decryption
2.5. Key Management
2.6. Creating a Key Store for Testing
2.7. Using Multiple Keys and Key Rotation
2.8. Serving Encrypted Properties
3. Serving Alternative Formats
4. Serving Plain Text
5. Embedding the Config Server
6. Push Notifications and Spring Cloud Bus
7. Spring Cloud Config Client
7.1. Config First Bootstrap
7.2. Discovery First Bootstrap
7.3. Config Client Fail Fast
7.4. Config Client Retry
7.5. Locating Remote Configuration Resources
7.6. Security
7.6.1. Health Indicator
7.6.2. Providing A Custom RestTemplate
7.6.3. Vault
7.7. Vault
7.7.1. Nested Keys In Vault
\ No newline at end of file + Spring Cloud Config

Spring Cloud Config


Table of Contents

1. Quick Start
1.1. Client Side Usage
2. Spring Cloud Config Server
2.1. Environment Repository
2.1.1. Git Backend
Placeholders in Git URI
Pattern Matching and Multiple Repositories
Authentication
Authentication with AWS CodeCommit
Git SSH configuration using properties
Placeholders in Git Search Paths
Force pull in Git Repositories
Deleting untracked branches in Git Repositories
2.1.2. Version Control Backend Filesystem Use
2.1.3. File System Backend
2.1.4. Vault Backend
Multiple Properties Sources
2.1.5. Sharing Configuration With All Applications
File Based Repositories
Vault Server
2.1.6. JDBC Backend
2.1.7. Composite Environment Repositories
Custom Composite Environment Repositories
2.1.8. Property Overrides
2.2. Health Indicator
2.3. Security
2.4. Encryption and Decryption
2.5. Key Management
2.6. Creating a Key Store for Testing
2.7. Using Multiple Keys and Key Rotation
2.8. Serving Encrypted Properties
3. Serving Alternative Formats
4. Serving Plain Text
5. Embedding the Config Server
6. Push Notifications and Spring Cloud Bus
7. Spring Cloud Config Client
7.1. Config First Bootstrap
7.2. Discovery First Bootstrap
7.3. Config Client Fail Fast
7.4. Config Client Retry
7.5. Locating Remote Configuration Resources
7.6. Security
7.6.1. Health Indicator
7.6.2. Providing A Custom RestTemplate
7.6.3. Vault
7.7. Nested Keys In Vault
\ No newline at end of file diff --git a/single/spring-cloud-config.html b/single/spring-cloud-config.html index 286d5538..81ff758b 100644 --- a/single/spring-cloud-config.html +++ b/single/spring-cloud-config.html @@ -1,38 +1,27 @@ - Spring Cloud Config

Spring Cloud Config


Table of Contents

1. Quick Start
1.1. Client Side Usage
2. Spring Cloud Config Server
2.1. Environment Repository
2.1.1. Git Backend
Placeholders in Git URI
Pattern Matching and Multiple Repositories
Authentication
Authentication with AWS CodeCommit
Git SSH configuration using properties
Placeholders in Git Search Paths
Force pull in Git Repositories
Deleting untracked branches in Git Repositories
2.1.2. Version Control Backend Filesystem Use
2.1.3. File System Backend
2.1.4. Vault Backend
Multiple Properties Sources
2.1.5. Sharing Configuration With All Applications
File Based Repositories
Vault Server
2.1.6. JDBC Backend
2.1.7. Composite Environment Repositories
Custom Composite Environment Repositories
2.1.8. Property Overrides
2.2. Health Indicator
2.3. Security
2.4. Encryption and Decryption
2.5. Key Management
2.6. Creating a Key Store for Testing
2.7. Using Multiple Keys and Key Rotation
2.8. Serving Encrypted Properties
3. Serving Alternative Formats
4. Serving Plain Text
5. Embedding the Config Server
6. Push Notifications and Spring Cloud Bus
7. Spring Cloud Config Client
7.1. Config First Bootstrap
7.2. Discovery First Bootstrap
7.3. Config Client Fail Fast
7.4. Config Client Retry
7.5. Locating Remote Configuration Resources
7.6. Security
7.6.1. Health Indicator
7.6.2. Providing A Custom RestTemplate
7.6.3. Vault
7.7. Vault
7.7.1. Nested Keys In Vault

2.0.0.BUILD-SNAPSHOT

Spring Cloud Config provides server and client-side support for externalized configuration in a distributed system. With the Config Server you have a central place to manage external properties for applications across all environments. The concepts on both client and server map identically to the Spring Environment and PropertySource abstractions, so they fit very well with Spring applications, but can be used with any application running in any language. As an application moves through the deployment pipeline from dev to test and into production you can manage the configuration between those environments and be certain that applications have everything they need to run when they migrate. The default implementation of the server storage backend uses git so it easily supports labelled versions of configuration environments, as well as being accessible to a wide range of tooling for managing the content. It is easy to add alternative implementations and plug them in with Spring configuration.

1. Quick Start

Start the server:

$ cd spring-cloud-config-server
-$ ../mvnw spring-boot:run

The server is a Spring Boot application so you can run it from your -IDE instead if you prefer (the main class is -ConfigServerApplication). Then try out a client:

$ curl localhost:8888/foo/development
+   Spring Cloud Config

Spring Cloud Config


2.0.0.BUILD-SNAPSHOT

Spring Cloud Config provides server-side and client-side support for externalized configuration in a distributed system. With the Config Server, you have a central place to manage external properties for applications across all environments. +The concepts on both client and server map identically to the Spring Environment and PropertySource abstractions, so they fit very well with Spring applications but can be used with any application running in any language. +As an application moves through the deployment pipeline from dev to test and into production, you can manage the configuration between those environments and be certain that applications have everything they need to run when they migrate. +The default implementation of the server storage backend uses git, so it easily supports labelled versions of configuration environments as well as being accessible to a wide range of tooling for managing the content. +It is easy to add alternative implementations and plug them in with Spring configuration.

1. Quick Start

This quick start walks through using both the server and the client of Spring Cloud Config Server.

First, start the server, as follows:

$ cd spring-cloud-config-server
+$ ../mvnw spring-boot:run

The server is a Spring Boot application, so you can run it from your IDE if you prefer to do so (the main class is ConfigServerApplication).

Next try out a client, as follows:

$ curl localhost:8888/foo/development
 {"name":"foo","label":"master","propertySources":[
   {"name":"https://github.com/scratches/config-repo/foo-development.properties","source":{"bar":"spam"}},
   {"name":"https://github.com/scratches/config-repo/foo.properties","source":{"foo":"bar"}}
-]}

The default strategy for locating property sources is to clone a git -repository (at spring.cloud.config.server.git.uri) and use it to -initialize a mini SpringApplication. The mini-application’s -Environment is used to enumerate property sources and publish them -via a JSON endpoint.

The HTTP service has resources in the form:

/{application}/{profile}[/{label}]
+]}

The default strategy for locating property sources is to clone a git repository (at spring.cloud.config.server.git.uri) and use it to initialize a mini SpringApplication. +The mini-application’s Environment is used to enumerate property sources and publish them at a JSON endpoint.

The HTTP service has resources in the following form:

/{application}/{profile}[/{label}]
 /{application}-{profile}.yml
 /{label}/{application}-{profile}.yml
 /{application}-{profile}.properties
-/{label}/{application}-{profile}.properties

where the "application" is injected as the spring.config.name in the -SpringApplication (i.e. what is normally "application" in a regular -Spring Boot app), "profile" is an active profile (or comma-separated -list of properties), and "label" is an optional git label (defaults to -"master".)

Spring Cloud Config Server pulls configuration for remote clients -from a git repository (which must be provided):

spring:
+/{label}/{application}-{profile}.properties

where application is injected as the spring.config.name in the SpringApplication (what is normally application in a regular Spring Boot app), profile is an active profile (or comma-separated list of properties), and label is an optional git label (defaults to master.)

Spring Cloud Config Server pulls configuration for remote clients from a git repository (which must be provided), as shown in the following example:

spring:
   cloud:
     config:
       server:
         git:
-          uri: https://github.com/spring-cloud-samples/config-repo

1.1 Client Side Usage

To use these features in an application, just build it as a Spring -Boot application that depends on spring-cloud-config-client (e.g. see -the test cases for the config-client, or the sample app). The most -convenient way to add the dependency is via a Spring Boot starter -org.springframework.cloud:spring-cloud-starter-config. There is also a -parent pom and BOM (spring-cloud-starter-parent) for Maven users and a -Spring IO version management properties file for Gradle and Spring CLI -users. Example Maven configuration:

pom.xml.  + uri: https://github.com/spring-cloud-samples/config-repo

1.1 Client Side Usage

To use these features in an application, you can build it as a Spring Boot application that depends on spring-cloud-config-client (for an example, see the test cases for the config-client or the sample application). +The most convenient way to add the dependency is with a Spring Boot starter org.springframework.cloud:spring-cloud-starter-config. +There is also a parent pom and BOM (spring-cloud-starter-parent) for Maven users and a Spring IO version management properties file for Gradle and Spring CLI users. The following example shows a typical Maven configuration:

pom.xml. 

   <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
@@ -74,7 +63,7 @@ users. Example Maven configuration:

pom.xml.  </build> <!-- repositories also needed for snapshots and milestones -->

-

Then you can create a standard Spring Boot application, like this simple HTTP server:

@SpringBootApplication
+

Now you can create a standard Spring Boot application, such as the following HTTP server:

@SpringBootApplication
 @RestController
 public class Application {
 
@@ -87,25 +76,17 @@ public class Application {
         SpringApplication.run(Application.class, args);
     }
 
-}

When it runs it will pick up the external configuration from the -default local config server on port 8888 if it is running. To modify -the startup behaviour you can change the location of the config server -using bootstrap.properties (like application.properties but for -the bootstrap phase of an application context), e.g.

spring.cloud.config.uri: http://myconfigserver.com

The bootstrap properties will show up in the /env endpoint as a -high-priority property source, e.g.

$ curl localhost:8080/env
+}

When this HTTP server runs, it picks up the external configuration from the default local config server (if it is running) on port 8888. +To modify the startup behavior, you can change the location of the config server by using bootstrap.properties (similar to application.properties but for the bootstrap phase of an application context), as shown in the following example:

spring.cloud.config.uri: http://myconfigserver.com

The bootstrap properties show up in the /env endpoint as a high-priority property source, as shown in the following example.

$ curl localhost:8080/env
 {
   "profiles":[],
   "configService:https://github.com/spring-cloud-samples/config-repo/bar.properties":{"foo":"bar"},
   "servletContextInitParams":{},
   "systemProperties":{...},
   ...
-}

(a property source called "configService:<URL of remote -repository>/<file name>" contains the property "foo" with value -"bar" and is highest priority).

[Note]Note

the URL in the property source name is the git repository not -the config server URL.

2. Spring Cloud Config Server

The Server provides an HTTP, resource-based API for external -configuration (name-value pairs, or equivalent YAML content). The -server is easily embeddable in a Spring Boot application using the -@EnableConfigServer annotation. So this app is a config server:

ConfigServer.java.  +}

A property source called ``configService:<URL of remote repository>/<file name> contains the foo property with a value of bar and is highest priority.

[Note]Note

The URL in the property source name is the git repository, not the config server URL.

2. Spring Cloud Config Server

Spring Cloud Config Server provides an HTTP resource-based API for external configuration (name-value pairs or equivalent YAML content). +The server is embeddable in a Spring Boot application, by using the @EnableConfigServer annotation. +Consequently, the following application is a config server:

ConfigServer.java. 

@SpringBootApplication
 @EnableConfigServer
 public class ConfigServer {
@@ -113,103 +94,61 @@ server is easily embeddable in a Spring Boot application using the
     SpringApplication.run(ConfigServer.class, args);
   }
 }

-

Like all Spring Boot apps it runs on port 8080 by default, but you -can switch it to the conventional port 8888 in various ways. The -easiest, which also sets a default configuration repository, -is by launching it with spring.config.name=configserver (there -is a configserver.yml in the Config Server jar). Another is -to use your own application.properties, e.g.

application.properties.  +

Like all Spring Boot applications, it runs on port 8080 by default, but you can switch it to the more conventional port 8888 in various ways. +The easiest, which also sets a default configuration repository, is by launching it with spring.config.name=configserver (there is a configserver.yml in the Config Server jar). +Another is to use your own application.properties, as shown in the following example:

application.properties. 

server.port: 8888
 spring.cloud.config.server.git.uri: file://${user.home}/config-repo

-

where ${user.home}/config-repo is a git repository containing -YAML and properties files.

[Note]Note

in Windows you need an extra "/" in the file URL if it is -absolute with a drive prefix, e.g. file:///${user.home}/config-repo.

[Tip]Tip

Here’s a recipe for creating the git repository in the example -above:

$ cd $HOME
+

where ${user.home}/config-repo is a git repository containing YAML and properties files.

[Note]Note

On Windows, you need an extra "/" in the file URL if it is absolute with a drive prefix (for example,file:///${user.home}/config-repo).

[Tip]Tip

The following listing shows a recipe for creating the git repository in the preceding example:

$ cd $HOME
 $ mkdir config-repo
 $ cd config-repo
 $ git init .
 $ echo info.foo: bar > application.properties
 $ git add -A .
-$ git commit -m "Add application.properties"
[Warning]Warning

using the local filesystem for your git repository is -intended for testing only. Use a server to host your -configuration repositories in production.

[Warning]Warning

the initial clone of your configuration repository will -be quick and efficient if you only keep text files in it. If you start -to store binary files, especially large ones, you may experience -delays on the first request for configuration and/or out of memory -errors in the server.

2.1 Environment Repository

Where do you want to store the configuration data for the Config -Server? The strategy that governs this behaviour is the -EnvironmentRepository, serving Environment objects. This -Environment is a shallow copy of the domain from the Spring -Environment (including propertySources as the main feature). The -Environment resources are parametrized by three variables:

  • {application} maps to "spring.application.name" on the client side;
  • {profile} maps to "spring.profiles.active" on the client (comma separated list); and
  • {label} which is a server side feature labelling a "versioned" set of config files.

Repository implementations generally behave just like a Spring Boot -application loading configuration files from a "spring.config.name" -equal to the {application} parameter, and "spring.profiles.active" -equal to the {profiles} parameter. Precedence rules for profiles are -also the same as in a regular Boot application: active profiles take -precedence over defaults, and if there are multiple profiles the last -one wins (like adding entries to a Map).

Example: a client application has this bootstrap configuration:

bootstrap.yml.  +$ git commit -m "Add application.properties"

[Warning]Warning

Using the local filesystem for your git repository is intended for testing only. +You should use a server to host your configuration repositories in production.

[Warning]Warning

The initial clone of your configuration repository can be quick and efficient if you keep only text files in it. +If you store binary files, especially large ones, you may experience delays on the first request for configuration or encounter out of memory errors in the server.

2.1 Environment Repository

Where should you store the configuration data for the Config Server? +The strategy that governs this behaviour is the EnvironmentRepository, serving Environment objects. +This Environment is a shallow copy of the domain from the Spring Environment (including propertySources as the main feature). +The Environment resources are parametrized by three variables:

  • {application}, which maps to spring.application.name on the client side.
  • {profile}, which maps to spring.profiles.active on the client (comma-separated list).
  • {label}, which is a server side feature labelling a "versioned" set of config files.

Repository implementations generally behave like a Spring Boot application, loading configuration files from a spring.config.name equal to the {application} parameter, and spring.profiles.active equal to the {profiles} parameter. +Precedence rules for profiles are also the same as in a regular Spring Boot application: Active profiles take precedence over defaults, and, if there are multiple profiles, the last one wins (similar to adding entries to a Map).

The following sample client application has this bootstrap configuration:

bootstrap.yml. 

spring:
   application:
     name: foo
   profiles:
     active: dev,mysql

-

(as usual with a Spring Boot application, these properties could also -be set as environment variables or command line arguments).

If the repository is file-based, the server will create an -Environment from application.yml (shared between all clients), and -foo.yml (with foo.yml taking precedence). If the YAML files have -documents inside them that point to Spring profiles, those are applied -with higher precedence (in order of the profiles listed), and if -there are profile-specific YAML (or properties) files these are also -applied with higher precedence than the defaults. Higher precedence -translates to a PropertySource listed earlier in the -Environment. (These are the same rules as apply in a standalone -Spring Boot application.)

2.1.1 Git Backend

The default implementation of EnvironmentRepository uses a Git -backend, which is very convenient for managing upgrades and physical -environments, and also for auditing changes. To change the location of -the repository you can set the "spring.cloud.config.server.git.uri" -configuration property in the Config Server (e.g. in -application.yml). If you set it with a file: prefix it should work -from a local repository so you can get started quickly and easily -without a server, but in that case the server operates directly on the -local repository without cloning it (it doesn’t matter if it’s not -bare because the Config Server never makes changes to the "remote" -repository). To scale the Config Server up and make it highly -available, you would need to have all instances of the server pointing -to the same repository, so only a shared file system would work. Even -in that case it is better to use the ssh: protocol for a shared -filesystem repository, so that the server can clone it and use a local -working copy as a cache.

This repository implementation maps the {label} parameter of the -HTTP resource to a git label (commit id, branch name or tag). If the -git branch or tag name contains a slash ("/") then the label in the -HTTP URL should be specified with the special string "(_)" instead (to -avoid ambiguity with other URL paths). For example, if the label is -foo/bar, replacing the slash would result in a label that looks like -foo(_)bar. The inclusion of the special string "(_)" can also be -applied to the {application} parameter. Be careful with the brackets -in the URL if you are using a command line client like curl (e.g. -escape them from the shell with quotes '').

Placeholders in Git URI

Spring Cloud Config Server supports a git repository URL with -placeholders for the {application} and {profile} (and {label} if -you need it, but remember that the label is applied as a git label -anyway). So you can easily support a "one repo per application" policy -using (for example):

spring:
+

(As usual with a Spring Boot application, these properties could also be set by environment variables or command line arguments).

If the repository is file-based, the server creates an +Environment from application.yml (shared between all clients) and +foo.yml (with foo.yml taking precedence). +If the YAML files have documents inside them that point to Spring profiles, those are applied with higher precedence (in order of the profiles listed). +If there are profile-specific YAML (or properties) files, these are also applied with higher precedence than the defaults. +Higher precedence translates to a PropertySource listed earlier in the Environment. +(These same rules apply in a standalone Spring Boot application.)

2.1.1 Git Backend

The default implementation of EnvironmentRepository uses a Git backend, which is very convenient for managing upgrades and physical +environments and for auditing changes. +To change the location of the repository, you can set the spring.cloud.config.server.git.uri configuration property in the Config Server (for example in application.yml). +If you set it with a file: prefix, it should work from a local repository so that you can get started quickly and easily without a server. However, in that case, the server operates directly on the local repository without cloning it (it does not matter if it is not bare because the Config Server never makes changes to the "remote" repository). +To scale the Config Server up and make it highly available, you need to have all instances of the server pointing to the same repository, so only a shared file system would work. +Even in that case, it is better to use the ssh: protocol for a shared filesystem repository, so that the server can clone it and use a local working copy as a cache.

This repository implementation maps the {label} parameter of the HTTP resource to a git label (commit id, branch name, or tag). +If the git branch or tag name contains a slash (/), then the label in the HTTP URL should instead be specified with the special string $$_$$ (to avoid ambiguity with other URL paths). +For example, if the label is foo/bar, replacing the slash would result in the following label: foo($$_$$)bar. +The inclusion of the special string ($$_$$) can also be applied to the {application} parameter. +If you use a command-line client such as curl, be careful with the brackets in the URL — you should +escape them from the shell with single quotes ('').

Placeholders in Git URI

Spring Cloud Config Server supports a git repository URL with placeholders for the {application} and {profile} (and {label} if you need it, but remember that the label is applied as a git label anyway). +So you can support a “one repository per application” policy by using a structure similar to the following:

spring:
   cloud:
     config:
       server:
         git:
-          uri: https://github.com/myorg/{application}

or a "one repo per profile" policy using a similar pattern but with -{profile}.

Additionally, using the special string "(_)" within your -{application} parameters can enable support for multiple -organizations (for example):

spring:
+          uri: https://github.com/myorg/{application}

You can also support a “one repository per profile” policy by using a similar pattern but with +{profile}.

Additionally, using the special string "($$_$$)" within your {application} parameters can enable support for multiple +organizations, as shown in the following example:

spring:
   cloud:
     config:
       server:
         git:
-          uri: https://github.com/{application}

where {application} is provided at request time in the format -"organization(_)application".

Pattern Matching and Multiple Repositories

There is also support for more complex requirements with pattern -matching on the application and profile name. The pattern format is a -comma-separated list of {application}/{profile} names with wildcards -(where a pattern beginning with a wildcard may need to be -quoted). Example:

spring:
+          uri: https://github.com/{application}

where {application} is provided at request time in the following format: organization($$_$$)application.

Pattern Matching and Multiple Repositories

Spring Cloud Config also includes support for more complex requirements with pattern +matching on the application and profile name. +The pattern format is a comma-separated list of {application}/{profile} names with wildcards (note that a pattern beginning with a wildcard may need to be quoted), as shown in the following example:

spring:
   cloud:
     config:
       server:
@@ -222,20 +161,10 @@ quoted). Example:

              uri: https://github.com/special/config-repo
             local:
               pattern: local*
-              uri: file:/home/configsvc/config-repo

If {application}/{profile} does not match any of the patterns, it -will use the default uri defined under -"spring.cloud.config.server.git.uri". In the above example, for the -"simple" repository, the pattern is simple/* (i.e. it only matches -one application named "simple" in all profiles). The "local" -repository matches all application names beginning with "local" in all -profiles (the /* suffix is added automatically to any pattern that -doesn’t have a profile matcher).

[Note]Note

the "one-liner" short cut used in the "simple" example above can -only be used if the only property to be set is the URI. If you need to -set anything else (credentials, pattern, etc.) you need to use the full -form.

The pattern property in the repo is actually an array, so you can -use a YAML array (or [0], [1], etc. suffixes in properties files) -to bind to multiple patterns. You may need to do this if you are going -to run apps with multiple profiles. Example:

spring:
+              uri: file:/home/configsvc/config-repo

If {application}/{profile} does not match any of the patterns, it uses the default URI defined under spring.cloud.config.server.git.uri. +In the above example, for the “simple” repository, the pattern is simple/* (it only matches one application named simple in all profiles). The “local” repository matches all application names beginning with local in all profiles (the /* suffix is added automatically to any pattern that does not have a profile matcher).

[Note]Note

The “one-liner” short cut used in the “simple” example can be used only if the only property to be set is the URI. +If you need to set anything else (credentials, pattern, and so on) you need to use the full form.

The pattern property in the repo is actually an array, so you can use a YAML array (or [0], [1], etc. suffixes in properties files) to bind to multiple patterns. +You may need to do so if you are going to run apps with multiple profiles, as shown in the following example:

spring:
   cloud:
     config:
       server:
@@ -251,24 +180,17 @@ to run apps with multiple profiles. Example:

              pattern:
                 - '*/qa'
                 - '*/production'
-              uri: https://github.com/staging/config-repo
[Note]Note

Spring Cloud will guess that a pattern containing a profile that -doesn’t end in * implies that you actually want to match a list of -profiles starting with this pattern (so */staging is a shortcut for -["*/staging", "*/staging,*"]). This is common where you need to run -apps in the "development" profile locally but also the "cloud" profile -remotely, for instance.

Every repository can also optionally store config files in -sub-directories, and patterns to search for those directories can be -specified as searchPaths. For example at the top level:

spring:
+              uri: https://github.com/staging/config-repo
[Note]Note

Spring Cloud guesses that a pattern containing a profile that does not end in * implies that you actually want to match a list of profiles starting with this pattern (so */staging is a shortcut for ["*/staging", "*/staging,*"], and so on). +This is common where, for instance, you need to run applications in the “development” profile locally but also the “cloud” profile remotely.

Every repository can also optionally store config files in sub-directories, and patterns to search for those directories can be specified as searchPaths. +The following example shows a config file at the top level:

spring:
   cloud:
     config:
       server:
         git:
           uri: https://github.com/spring-cloud-samples/config-repo
-          searchPaths: foo,bar*

In this example the server searches for config files in the top level -and in the "foo/" sub-directory and also any sub-directory whose name -begins with "bar".

By default the server clones remote repositories when configuration -is first requested. The server can be configured to clone the repositories -at startup. For example at the top level:

spring:
+          searchPaths: foo,bar*

In the preceding example, the server searches for config files in the top level and in the foo/ sub-directory and also any sub-directory whose name begins with bar.

By default, the server clones remote repositories when configuration +is first requested. +The server can be configured to clone the repositories at startup, as shown in the following top-level example:

spring:
   cloud:
     config:
       server:
@@ -285,48 +207,33 @@ at startup. For example at the top level:

                uri: http://git/team-b/config-repo.git
             team-c:
                 pattern: team-c-*
-                uri: http://git/team-a/config-repo.git

In this example the server clones team-a’s config-repo on startup before it -accepts any requests. All other repositories will not be cloned until -configuration from the repository is requested.

[Note]Note

Setting a repository to be cloned when the Config Server starts up can -help to identify a misconfigured configuration source (e.g., an invalid -repository URI) quickly, while the Config Server is starting up. With -cloneOnStart not enabled for a configuration source, the Config Server may -start successfully with a misconfigured or invalid configuration source and -not detect an error until an application requests configuration from that -configuration source.

Authentication

To use HTTP basic authentication on the remote repository add the -"username" and "password" properties separately (not in the URL), -e.g.

spring:
+                uri: http://git/team-a/config-repo.git

In the preceding example, the server clones team-a’s config-repo on startup, before it +accepts any requests. +All other repositories are not cloned until configuration from the repository is requested.

[Note]Note

Setting a repository to be cloned when the Config Server starts up can help to identify a misconfigured configuration source (such as an invalid repository URI) quickly, while the Config Server is starting up. +With cloneOnStart not enabled for a configuration source, the Config Server may start successfully with a misconfigured or invalid configuration source and not detect an error until an application requests configuration from that configuration source.

Authentication

To use HTTP basic authentication on the remote repository, add the username and password properties separately (not in the URL), as shown in the following example:

spring:
   cloud:
     config:
       server:
         git:
           uri: https://github.com/spring-cloud-samples/config-repo
           username: trolley
-          password: strongpassword

If you don’t use HTTPS and user credentials, SSH should also work out -of the box when you store keys in the default directories (~/.ssh) -and the uri points to an SSH location, -e.g. "git@github.com:configuration/cloud-configuration". It is important that an entry for the Git server be present in the ~/.ssh/known_hosts file and that it is in ssh-rsa format. Other formats (like ecdsa-sha2-nistp256) are not supported. To avoid surprises, you should ensure that only one entry is present in the known_hosts file for the Git server and that it is matching with the URL you provided to the config server. If you used a hostname in the URL, you want to have exactly that in the known_hosts file, not the IP. -The repository is accessed using JGit, so any documentation you find on -that should be applicable. HTTPS proxy settings can be set in -~/.git/config or in the same way as for any other JVM process via -system properties (-Dhttps.proxyHost and -Dhttps.proxyPort).

[Tip]Tip

If you don’t know where your ~/.git directory is use git config ---global to manipulate the settings (e.g. git config --global -http.sslVerify false).

Authentication with AWS CodeCommit

AWS CodeCommit authentication can also be -done. AWS CodeCommit uses an authentication helper when using Git from the command line. This helper is not -used with the JGit library, so a JGit CredentialProvider for AWS CodeCommit will be created if the Git -URI matches the AWS CodeCommit pattern. AWS CodeCommit URIs always look like -https://git-codecommit.${AWS_REGION}.amazonaws.com/${repopath}.

If you provide a username and password with an AWS CodeCommit URI, then these must be -the AWS accessKeyId and secretAccessKey -to be used to access the repository. If you do not specify a username and password, -then the accessKeyId and secretAccessKey will be retrieved using the -AWS Default Credential Provider Chain.

If your Git URI matches the CodeCommit URI pattern (above) then you must provide -valid AWS credentials in the username and password, or in one of the locations supported -by the default credential provider chain. AWS EC2 instances may use -IAM Roles for EC2 Instances.

Note: The aws-java-sdk-core jar is an optional dependency. If the aws-java-sdk-core jar is not on your -classpath, then the AWS Code Commit credential provider will not be created regardless of the git server URI.

Git SSH configuration using properties

By default, the JGit library used by Spring Cloud Config Server uses SSH configuration files such as ~/.ssh/known_hosts and /etc/ssh/ssh_config when connecting to Git repositories using an SSH URI. -In cloud environments such as Cloud Foundry, the local filesystem may be ephemeral or not easily accessible. For cases such as these, SSH configuration can be set using -Java properties. In order to activate property based SSH configuration, the property spring.cloud.config.server.git.ignoreLocalSshSettings must be set to true. -Example:

  spring:
+          password: strongpassword

If you do not use HTTPS and user credentials, SSH should also work out of the box when you store keys in the default directories (~/.ssh) and the URI points to an SSH location, such as git@github.com:configuration/cloud-configuration. +It is important that an entry for the Git server be present in the ~/.ssh/known_hosts file and that it is in ssh-rsa format. +Other formats (such as ecdsa-sha2-nistp256) are not supported. +To avoid surprises, you should ensure that only one entry is present in the known_hosts file for the Git server and that it matches the URL you provided to the config server. +If you use a hostname in the URL, you want to have exactly that (not the IP) in the known_hosts file. +The repository is accessed by using JGit, so any documentation you find on that should be applicable. +HTTPS proxy settings can be set in ~/.git/config or (in the same way as for any other JVM process) with +system properties (-Dhttps.proxyHost and -Dhttps.proxyPort).

[Tip]Tip

If you do not know where your ~/.git directory is, use git config --global to manipulate the settings (for example, git config --global http.sslVerify false).

Authentication with AWS CodeCommit

Spring Cloud Config Server also supports AWS CodeCommit authentication. +AWS CodeCommit uses an authentication helper when using Git from the command line. +This helper is not used with the JGit library, so a JGit CredentialProvider for AWS CodeCommit is created if the Git URI matches the AWS CodeCommit pattern. +AWS CodeCommit URIs follow this pattern://git-codecommit.${AWS_REGION}.amazonaws.com/${repopath}.

If you provide a username and password with an AWS CodeCommit URI, they must be the AWS accessKeyId and secretAccessKey that provide access to the repository. +If you do not specify a username and password, the accessKeyId and secretAccessKey are retrieved by using the AWS Default Credential Provider Chain.

If your Git URI matches the CodeCommit URI pattern (shown earlier), you must provide valid AWS credentials in the username and password or in one of the locations supported by the default credential provider chain. +AWS EC2 instances may use IAM Roles for EC2 Instances.

[Note]Note

The aws-java-sdk-core jar is an optional dependency. +If the aws-java-sdk-core jar is not on your classpath, the AWS Code Commit credential provider is not created, regardless of the git server URI.

Git SSH configuration using properties

By default, the JGit library used by Spring Cloud Config Server uses SSH configuration files such as ~/.ssh/known_hosts and /etc/ssh/ssh_config when connecting to Git repositories by using an SSH URI. +In cloud environments such as Cloud Foundry, the local filesystem may be ephemeral or not easily accessible. +For those cases, SSH configuration can be set by using Java properties. +In order to activate property-based SSH configuration, the spring.cloud.config.server.git.ignoreLocalSshSettings property must be set to true, as shown in the following example:

  spring:
     cloud:
       config:
         server:
@@ -362,30 +269,22 @@ Example:

69pcVH/4rmLbXdcmNYGm6iu+MlPQk4BUZknHSmVHIFdJ0EPupVaQ8RHT
-                         -----END RSA PRIVATE KEY-----

Table 2.1. SSH Configuration properties

Property NameRemarks

ignoreLocalSshSettings

If true, use property based SSH config instead of file based. Must be set at as spring.cloud.config.server.git.ignoreLocalSshSettings, not inside a repository definition.

privateKey

Valid SSH private key. Must be set if ignoreLocalSshSettings is true and Git URI is SSH format

hostKey

Valid SSH host key. Must be set if hostKeyAlgorithm is also set

hostKeyAlgorithm

One of ssh-dss, ssh-rsa, ecdsa-sha2-nistp256, ecdsa-sha2-nistp384 ,ecdsa-sha2-nistp521. Must be set if hostKey is also set

strictHostKeyChecking

true or false. If false, ignore errors with host key

knownHostsFile

Location of custom .known_hosts file

preferredAuthentications

Override server authentication method order. This should allow evade login prompts if server has keyboard-interactive authentication before publickey method.


Placeholders in Git Search Paths

Spring Cloud Config Server also supports a search path with -placeholders for the {application} and {profile} (and {label} if -you need it). Example:

spring:
+                         -----END RSA PRIVATE KEY-----

The following table describes the SSH configuration properties.

Table 2.1. SSH Configuration Properties

Property NameRemarks

ignoreLocalSshSettings

If true, use property-based instead of file-based SSH config. Must be set at as spring.cloud.config.server.git.ignoreLocalSshSettings, not inside a repository definition.

privateKey

Valid SSH private key. Must be set if ignoreLocalSshSettings is true and Git URI is SSH format.

hostKey

Valid SSH host key. Must be set if hostKeyAlgorithm is also set.

hostKeyAlgorithm

One of ssh-dss, ssh-rsa, ecdsa-sha2-nistp256, ecdsa-sha2-nistp384, or ecdsa-sha2-nistp521. Must be set if hostKey is also set.

strictHostKeyChecking

true or false. If false, ignore errors with host key.

knownHostsFile

Location of custom .known_hosts file.

preferredAuthentications

Override server authentication method order. This should allow for evading login prompts if server has keyboard-interactive authentication before the publickey method.


Placeholders in Git Search Paths

Spring Cloud Config Server also supports a search path with placeholders for the {application} and {profile} (and {label} if +you need it), as shown in the following example:

spring:
   cloud:
     config:
       server:
         git:
           uri: https://github.com/spring-cloud-samples/config-repo
-          searchPaths: '{application}'

searches the repository for files in the same name as the directory -(as well as the top level). Wildcards are also valid in a search -path with placeholders (any matching directory is included in the -search).

Force pull in Git Repositories

As mentioned before Spring Cloud Config Server makes a clone of the -remote git repository and if somehow the local copy gets dirty (e.g. -folder content changes by OS process) so Spring Cloud Config Server -cannot update the local copy from remote repository.

To solve this there is a force-pull property that will make Spring Cloud -Config Server force pull from remote repository if the local copy is dirty. -Example:

spring:
+          searchPaths: '{application}'

The preceding listing causes a search of the repository for files in the same name as the directory (as well as the top level). +Wildcards are also valid in a search path with placeholders (any matching directory is included in the search).

Force pull in Git Repositories

As mentioned earlier, Spring Cloud Config Server makes a clone of the remote git repository in case the local copy gets dirty (for example, +folder content changes by an OS process) such that Spring Cloud Config Server cannot update the local copy from remote repository.

To solve this issue, there is a force-pull property that makes Spring Cloud Config Server force pull from the remote repository if the local copy is dirty, as shown in the following example:

spring:
   cloud:
     config:
       server:
         git:
           uri: https://github.com/spring-cloud-samples/config-repo
-          force-pull: true

If you have a multiple repositories configuration you can configure the -force-pull property per repository. Example:

spring:
+          force-pull: true

If you have a multiple-repositories configuration, you can configure the force-pull property per repository, as shown in the following example:

spring:
   cloud:
     config:
       server:
@@ -416,49 +315,29 @@ Example:

      server:
         git:
           uri: https://github.com/spring-cloud-samples/config-repo
-          deleteUntrackedBranches: true
[Note]Note

The default value for deleteUntrackedBranches property is false.

2.1.2 Version Control Backend Filesystem Use

[Warning]Warning

With VCS based backends (git, svn) files are checked out or cloned to the local filesystem. By default they are put in the system temporary directory with a prefix of config-repo-. On linux, for example it could be /tmp/config-repo-<randomid>. Some operating systems routinely clean out temporary directories. This can lead to unexpected behaviour such as missing properties. To avoid this problem, change the directory Config Server uses, by setting spring.cloud.config.server.git.basedir or spring.cloud.config.server.svn.basedir to a directory that does not reside in the system temp structure.

2.1.3 File System Backend

There is also a "native" profile in the Config Server that doesn’t use -Git, but just loads the config files from the local classpath or file -system (any static URL you want to point to with -"spring.cloud.config.server.native.searchLocations"). To use the -native profile just launch the Config Server with -"spring.profiles.active=native".

[Note]Note

Remember to use the file: prefix for file resources (the -default without a prefix is usually the classpath). Just as with any -Spring Boot configuration you can embed ${}-style environment -placeholders, but remember that absolute paths in Windows require an -extra "/", e.g. file:///${user.home}/config-repo

[Warning]Warning

The default value of the searchLocations is identical to a -local Spring Boot application (so [classpath:/, classpath:/config, -file:./, file:./config]). This does not expose the -application.properties from the server to all clients because any -property sources present in the server are removed before being sent -to the client.

[Tip]Tip

A filesystem backend is great for getting started quickly and -for testing. To use it in production you need to be sure that the -file system is reliable, and shared across all instances of the -Config Server.

The search locations can contain placeholders for {application}, -{profile} and {label}. In this way you can segregate the -directories in the path, and choose a strategy that makes sense for -you (e.g. sub-directory per application, or sub-directory per -profile).

If you don’t use placeholders in the search locations, this repository -also appends the {label} parameter of the HTTP resource to a suffix -on the search path, so properties files are loaded from each search -location and a subdirectory with the same name as the label (the -labelled properties take precedence in the Spring Environment). Thus -the default behaviour with no placeholders is the same as adding a -search location ending with /{label}/. For example file:/tmp/config -is the same as file:/tmp/config,file:/tmp/config/{label}. This behavior can be -disabled by setting spring.cloud.config.server.native.addLabelLocations=false.

2.1.4 Vault Backend

Spring Cloud Config Server also supports Vault as a backend.

For more information on Vault see the Vault quickstart guide.

To enable the config server to use a Vault backend you can run your config server -with the vault profile. For example in your config server’s application.properties -you can add spring.profiles.active=vault.

By default the config server will assume your Vault server is running at -http://127.0.0.1:8200. It also will assume that the name of backend -is secret and the key is application. All of these defaults can be -configured in your config server’s application.properties. Below is a -table of configurable Vault properties. All properties are prefixed with -spring.cloud.config.server.vault.

NameDefault Value

host

127.0.0.1

port

8200

scheme

http

backend

secret

defaultKey

application

profileSeparator

,

All configurable properties can be found in -org.springframework.cloud.config.server.environment.VaultEnvironmentRepository.

With your config server running you can make HTTP requests to the server to retrieve -values from the Vault backend. To do this you will need a token for your Vault server.

First place some data in you Vault. For example

$ vault write secret/application foo=bar baz=bam
-$ vault write secret/myapp foo=myappsbar

Now make the HTTP request to your config server to retrieve the values.

$ curl -X "GET" "http://localhost:8888/myapp/default" -H "X-Config-Token: yourtoken"

You should see a response similar to this after making the above request.

{
+          deleteUntrackedBranches: true
[Note]Note

The default value for deleteUntrackedBranches property is false.

2.1.2 Version Control Backend Filesystem Use

[Warning]Warning

With VCS-based backends (git, svn), files are checked out or cloned to the local filesystem. +By default, they are put in the system temporary directory with a prefix of config-repo-. +On linux, for example, it could be /tmp/config-repo-<randomid>. +Some operating systems routinely clean out temporary directories. +This can lead to unexpected behavior, such as missing properties. +To avoid this problem, change the directory that Config Server uses by setting spring.cloud.config.server.git.basedir or spring.cloud.config.server.svn.basedir to a directory that does not reside in the system temp structure.

2.1.3 File System Backend

There is also a “native” profile in the Config Server that does not use Git but loads the config files from the local classpath or file system (any static URL you want to point to with spring.cloud.config.server.native.searchLocations). +To use the native profile, launch the Config Server with spring.profiles.active=native.

[Note]Note

Remember to use the file: prefix for file resources (the default without a prefix is usually the classpath). +As with any Spring Boot configuration, you can embed ${}-style environment placeholders, but remember that absolute paths in Windows require an extra / (for example, file:///${user.home}/config-repo).

[Warning]Warning

The default value of the searchLocations is identical to a local Spring Boot application (that is, [classpath:/, classpath:/config, +file:./, file:./config]). +This does not expose the application.properties from the server to all clients, because any property sources present in the server are removed before being sent to the client.

[Tip]Tip

A filesystem backend is great for getting started quickly and for testing. +To use it in production, you need to be sure that the file system is reliable and shared across all instances of the Config Server.

The search locations can contain placeholders for {application}, {profile}, and {label}. +In this way, you can segregate the directories in the path and choose a strategy that makes sense for you (such as subdirectory per application or subdirectory per profile).

If you do not use placeholders in the search locations, this repository also appends the {label} parameter of the HTTP resource to a suffix on the search path, so properties files are loaded from each search location and a subdirectory with the same name as the label (the labelled properties take precedence in the Spring Environment). +Thus, the default behaviour with no placeholders is the same as adding a search location ending with /{label}/. +For example, file:/tmp/config is the same as file:/tmp/config,file:/tmp/config/{label}. +This behavior can be disabled by setting spring.cloud.config.server.native.addLabelLocations=false.

2.1.4 Vault Backend

Spring Cloud Config Server also supports Vault as a backend.

For more information on Vault, see the Vault quick start guide.

To enable the config server to use a Vault backend, you can run your config server with the vault profile. +For example, in your config server’s application.properties, you can add spring.profiles.active=vault.

By default, the config server assumes that your Vault server runs at http://127.0.0.1:8200. +It also assumes that the name of backend is secret and the key is application. +All of these defaults can be configured in your config server’s application.properties. +The following table describes configurable Vault properties:

NameDefault Value

host

127.0.0.1

port

8200

scheme

http

backend

secret

defaultKey

application

profileSeparator

,

[Important]Important

All of the properties in the preceding table must be prefixed with spring.cloud.config.server.vault.

All configurable properties can be found in org.springframework.cloud.config.server.environment.VaultEnvironmentRepository.

With your config server running, you can make HTTP requests to the server to retrieve +values from the Vault backend. +To do so, you need a token for your Vault server.

First, place some data in you Vault, as shown in the following example:

$ vault write secret/application foo=bar baz=bam
+$ vault write secret/myapp foo=myappsbar

Second, make an HTTP request to your config server to retrieve the values, as shown in the following example:

$ curl -X "GET" "http://localhost:8888/myapp/default" -H "X-Config-Token: yourtoken"

You should see a response similar to the following:

{
    "name":"myapp",
    "profiles":[
       "default"
@@ -481,50 +360,23 @@ $ vault write secret/myapp foo=myappsbar

Now make the HTTP request to yo } } ] -}

Multiple Properties Sources

When using Vault you can provide your applications with multiple properties sources. -For example, assume you have written data to the following paths in Vault.

secret/myApp,dev
+}

Multiple Properties Sources

When using Vault, you can provide your applications with multiple properties sources. +For example, assume you have written data to the following paths in Vault:

secret/myApp,dev
 secret/myApp
 secret/application,dev
-secret/application

Properties written to secret/application are available to -all applications using the Config Server. An -application with the name myApp would have any properties -written to secret/myApp and secret/application available to it. -When myApp has the dev profile enabled then properties written to -all of the above paths would be available to it, with properties in -the first path in the list taking priority over the others.

2.1.5 Sharing Configuration With All Applications

File Based Repositories

With file-based (i.e. git, svn and native) repositories, resources -with file names in application* are shared between all client -applications (so application.properties, application.yml, -application-*.properties etc.). You can use resources with these -file names to configure global defaults and have them overridden by -application-specific files as necessary.

The #_property_overrides[property overrides] feature can also be used -for setting global defaults, and with placeholders applications are -allowed to override them locally.

[Tip]Tip

With the "native" profile (local file system backend) it is -recommended that you use an explicit search location that isn’t part -of the server’s own configuration. Otherwise the application* -resources in the default search locations are removed because they are -part of the server.

Vault Server

When using Vault as a backend you can share configuration with -all applications by placing configuration in -secret/application. For example, if you run this Vault command

$ vault write secret/application foo=bar baz=bam

All applications using the config server will have the properties -foo and baz available to them.

2.1.6 JDBC Backend

Spring Cloud Config Server supports JDBC (relation database) as a -backend for configuration properties. You can enable this feature by -adding spring-jdbc to the classpath, and using the "jdbc" profile, -or by adding a bean of type JdbcEnvironmentRepository. Spring Boot -will configure a data source if you include the right dependencies on -the classpath (see the user guide for more details on that).

The database needs to have a table called "PROPERTIES" with columns -"APPLICATION", "PROFILE", "LABEL" (with the usual Environment -meaning), plus "KEY" and "VALUE" for the key and value pairs in -Properties style. All fields are of type String in Java, so you can -make them VARCHAR of whatever length you need. Property values -behave in the same way as they would if they came from Spring Boot -properties files named {application}-{profile}.properties, including -all the encryption and decryption, which will be applied as -post-processing steps (i.e. not in the repository implementation -directly).

2.1.7 Composite Environment Repositories

In some scenarios you may wish to pull configuration data from multiple -environment repositories. To do this you can just enable -multiple profiles in your config server’s application properties or YAML file. -If, for example, you want to pull configuration data from a Git repository -as well as a SVN repository you would set the following properties for your -configuration server.

spring:
+secret/application

Properties written to secret/application are available to all applications using the Config Server. +An application with the name, myApp, would have any properties written to secret/myApp and secret/application available to it. +When myApp has the dev profile enabled, properties written to all of the above paths would be available to it, with properties in the first path in the list taking priority over the others.

2.1.5 Sharing Configuration With All Applications

Sharing configuration between all applications varies according to which approach you take, as described in the following topics:

File Based Repositories

With file-based (git, svn, and native) repositories, resources with file names in application* (application.properties, application.yml, application-*.properties, and so on) are shared between all client applications. +You can use resources with these file names to configure global defaults and have them be overridden by application-specific files as necessary.

The #_property_overrides[property overrides] feature can also be used for setting global defaults, with placeholders applications +allowed to override them locally.

[Tip]Tip

With the “native” profile (a local file system backend) , you should use an explicit search location that is not part of the server’s own configuration. +Otherwise, the application* resources in the default search locations get removed because they are part of the server.

Vault Server

When using Vault as a backend, you can share configuration with all applications by placing configuration in secret/application. +For example, if you run the following Vault command, all applications using the config server will have the properties foo and baz available to them:

$ vault write secret/application foo=bar baz=bam

2.1.6 JDBC Backend

Spring Cloud Config Server supports JDBC (relational database) as a backend for configuration properties. +You can enable this feature by adding spring-jdbc to the classpath and using the jdbc profile or by adding a bean of type JdbcEnvironmentRepository. +If you include the right dependencies on the classpath (see the user guide for more details on that), Spring Boot configures a data source.

The database needs to have a table called PROPERTIES with columns called APPLICATION, PROFILE, and LABEL (with the usual Environment meaning), plus KEY and VALUE for the key and value pairs in Properties style. +All fields are of type String in Java, so you can make them VARCHAR of whatever length you need. +Property values behave in the same way as they would if they came from Spring Boot properties files named {application}-{profile}.properties, including all the encryption and decryption, which will be applied as post-processing steps (that is, not in the repository implementation directly).

2.1.7 Composite Environment Repositories

In some scenarios, you may wish to pull configuration data from multiple environment repositories. +To do so, you can enable multiple profiles in your config server’s application properties or YAML file. +If, for example, you want to pull configuration data from a Git repository as well as an SVN repository, you can set the following properties for your configuration server:

spring:
   profiles:
     active: git, svn
   cloud:
@@ -535,48 +387,26 @@ configuration server.

          order: 2
         git:
           uri: file:///path/to/git/repo
-          order: 1

In addition to each repo specifying a URI, you can also specify an order property. -The order property allows you to specify the priority order for all your repositories. -The lower the numerical value of the order property the higher priority it will have. -The priority order of a repository will help resolve any potential conflicts between -repositories that contain values for the same properties.

[Note]Note

Any type of failure when retrieving values from an environment repositoy -will result in a failure for the entire composite environment.

[Note]Note

When using a composite environment it is important that all repos contain -the same label(s). If you have an environment similar to the one above and you request -configuration data with the label master but the SVN -repo does not contain a branch called master the entire request will fail.

Custom Composite Environment Repositories

It is also possible to provide your own EnvironmentRepository bean -to be included as part of a composite environment in addition to -using one of the environment repositories from Spring Cloud. To do this your bean -must implement the EnvironmentRepository interface. If you would like to control -the priority of you custom EnvironmentRepository within the composite -environment you should also implement the Ordered interface and override the -getOrdered method. If you do not implement the Ordered interface then your -EnvironmentRepository will be given the lowest priority.

2.1.8 Property Overrides

The Config Server has an "overrides" feature that allows the operator -to provide configuration properties to all applications that cannot be -accidentally changed by the application using the normal Spring Boot -hooks. To declare overrides just add a map of name-value pairs to -spring.cloud.config.server.overrides. For example

spring:
+          order: 1

In addition to each repository specifying a URI, you can also specify an order property. +The order property lets you specify the priority order for all your repositories. +The lower the numerical value of the order property, the higher priority it has. +The priority order of a repository helps resolve any potential conflicts between repositories that contain values for the same properties.

[Note]Note

Any type of failure when retrieving values from an environment repository results in a failure for the entire composite environment.

[Note]Note

When using a composite environment, it is important that all repositories contain the same labels. +If you have an environment similar to the one in the preceding example and you request configuration data with the master label but the SVN repository does not contain a branch called master, the entire request fails.

Custom Composite Environment Repositories

In addition to using one of the environment repositories from Spring Cloud, you can also provide your own EnvironmentRepository bean to be included as part of a composite environment. +To do so, your bean must implement the EnvironmentRepository interface. +If you want to control the priority of your custom EnvironmentRepository within the composite environment, you should also implement the Ordered interface and override the getOrdered method. +If you do not implement the Ordered interface, your EnvironmentRepository is given the lowest priority.

2.1.8 Property Overrides

The Config Server has an “overrides” feature that lets the operator provide configuration properties to all applications. +The overridden properties cannot be accidentally changed by the application with the normal Spring Boot hooks. +To declare overrides, add a map of name-value pairs to spring.cloud.config.server.overrides, as shown in the following example:

spring:
   cloud:
     config:
       server:
         overrides:
-          foo: bar

will cause all applications that are config clients to read foo=bar -independent of their own configuration. (Of course an application can -use the data in the Config Server in any way it likes, so overrides -are not enforceable, but they do provide useful default behaviour if -they are Spring Cloud Config clients.)

[Tip]Tip

Normal, Spring environment placeholders with "${}" can be escaped -(and resolved on the client) by using backslash ("\") to escape the -"$" or the "{", e.g. \${app.foo:bar} resolves to "bar" unless the -app provides its own "app.foo". Note that in YAML you don’t need to -escape the backslash itself, but in properties files you do, when you -configure the overrides on the server.

You can change the priority of all overrides in the client to be more -like default values, allowing applications to supply their own values -in environment variables or System properties, by setting the flag -spring.cloud.config.overrideNone=true (default is false) in the -remote repository.

2.2 Health Indicator

Config Server comes with a Health Indicator that checks if the configured -EnvironmentRepository is working. By default it asks the EnvironmentRepository -for an application named app, the default profile and the default -label provided by the EnvironmentRepository implementation.

You can configure the Health Indicator to check more applications -along with custom profiles and custom labels, e.g.

spring:
+          foo: bar

The preceding examples causes all applications that are config clients to read foo=bar, independent of their own configuration.

[Note]Note

A configuration system cannot force an application to use configuration data in any particular way. +Consequently, overrides are not enforceable. +However, they do provide useful default behavior for Spring Cloud Config clients.

[Tip]Tip

Normally, Spring environment placeholders with ${} can be escaped (and resolved on the client) by using backslash (\) to escape the $ or the {. +For example, \${app.foo:bar} resolves to bar, unless the app provides its own app.foo.

[Note]Note

In YAML, you do not need to escape the backslash itself. +However, in properties files, you do need to escape the backslash, when you configure the overrides on the server.

You can change the priority of all overrides in the client to be more like default values, letting applications supply their own values in environment variables or System properties, by setting the spring.cloud.config.overrideNone=true flag (the default is false) in the remote repository.

2.2 Health Indicator

Config Server comes with a Health Indicator that checks whether the configured EnvironmentRepository is working. +By default, it asks the EnvironmentRepository for an application named app, the default profile, and the default label provided by the EnvironmentRepository implementation.

You can configure the Health Indicator to check more applications along with custom profiles and custom labels, as shown in the following example:

spring:
   cloud:
     config:
       server:
@@ -586,155 +416,70 @@ along with custom profiles and custom labels, e.g.

              label: mylabel
             myservice-dev:
               name: myservice
-              profiles: development

You can disable the Health Indicator by setting spring.cloud.config.server.health.enabled=false.

2.3 Security

You are free to secure your Config Server in any way that makes sense -to you (from physical network security to OAuth2 bearer -tokens), and Spring Security and Spring Boot make it easy to do pretty -much anything.

To use the default Spring Boot configured HTTP Basic security, just -include Spring Security on the classpath (e.g. through -spring-boot-starter-security). The default is a username of "user" -and a randomly generated password, which isn’t going to be very useful -in practice, so we recommend you configure the password (via -spring.security.user.password) and encrypt it (see below for instructions -on how to do that).

2.4 Encryption and Decryption

[Important]Important

Prerequisites: to use the encryption and decryption features -you need the full-strength JCE installed in your JVM (it’s not there by default). -You can download the "Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files" -from Oracle, and follow instructions for installation (essentially replace the 2 policy files -in the JRE lib/security directory with the ones that you downloaded).

If the remote property sources contain encrypted content (values -starting with {cipher}) they will be decrypted before sending to -clients over HTTP. The main advantage of this set up is that the -property values don’t have to be in plain text when they are "at rest" -(e.g. in a git repository). If a value cannot be decrypted it is -removed from the property source and an additional property is added -with the same key, but prefixed with "invalid." and a value that means -"not applicable" (usually "<n/a>"). This is largely to prevent cipher -text being used as a password and accidentally leaking.

If you are setting up a remote config repository for config client -applications it might contain an application.yml like this, for -instance:

application.yml.  + profiles: development

You can disable the Health Indicator by setting spring.cloud.config.server.health.enabled=false.

2.3 Security

You can secure your Config Server in any way that makes sense to you (from physical network security to OAuth2 bearer tokens), because Spring Security and Spring Boot offer support for many security arrangements.

To use the default Spring Boot-configured HTTP Basic security, include Spring Security on the classpath (for example, through spring-boot-starter-security). +The default is a username of user and a randomly generated password. A random password is not useful in practice, so we recommend you configure the password (by setting spring.security.user.password) and encrypt it (see below for instructions on how to do that).

2.4 Encryption and Decryption

[Important]Important

To use the encryption and decryption features you need the full-strength JCE installed in your JVM (it is not included by default). +You can download the “Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files” from Oracle and follow the installation instructions (essentially, you need to replace the two policy files in the JRE lib/security directory with the ones that you downloaded).

If the remote property sources contain encrypted content (values starting with {cipher}), they are decrypted before sending to clients over HTTP. +The main advantage of this setup is that the property values need not be in plain text when they are “at rest” (for example, in a git repository). +If a value cannot be decrypted, it is removed from the property source and an additional property is added with the same key but prefixed with invalid and a value that means “not applicable” (usually <n/a>). +This is largely to prevent cipher text being used as a password and accidentally leaking.

If you set up a remote config repository for config client applications, it might contain an application.yml similar to the following:

application.yml. 

spring:
   datasource:
     username: dbuser
     password: '{cipher}FKSAJDFGYOS8F7GLHAKERGFHLSAJ'

-

Encrypted values in a .properties file must not be wrapped in quotes, otherwise the value will not be decrypted:

application.properties.  +

Encrypted values in a .properties file must not be wrapped in quotes. Otherwise, the value is not decrypted. The following example shows values that would work:

application.properties. 

spring.datasource.username: dbuser
 spring.datasource.password: {cipher}FKSAJDFGYOS8F7GLHAKERGFHLSAJ

-

You can safely push this plain text to a shared git repository and the -secret password is protected.

The server also exposes /encrypt and /decrypt endpoints (on the -assumption that these will be secured and only accessed by authorized -agents). If you are editing a remote config file you can use the Config Server -to encrypt values by POSTing to the /encrypt endpoint, e.g.

$ curl localhost:8888/encrypt -d mysecret
-682bc583f4641835fa2db009355293665d2647dade3375c0ee201de2a49f7bda
[Note]Note

If the value you are encrypting has characters in it that need to be URL encoded you should use -the --data-urlencode option to curl to make sure they are encoded properly.

[Tip]Tip

Be sure not to include any of the curl command statistics in the encrypted value. -Outputting the value to a file can help avoid this problem.

The inverse operation is also available via /decrypt (provided the server is -configured with a symmetric key or a full key pair):

$ curl localhost:8888/decrypt -d 682bc583f4641835fa2db009355293665d2647dade3375c0ee201de2a49f7bda
-mysecret
[Tip]Tip

If you are testing like this with curl, then use ---data-urlencode (instead of -d) or set an explicit Content-Type: -text/plain to make sure curl encodes the data correctly when there -are special characters ('+' is particularly tricky).

Take the encrypted value and add the {cipher} prefix before you put -it in the YAML or properties file, and before you commit and push it -to a remote, potentially insecure store.

The /encrypt and /decrypt endpoints also both accept paths of the -form /*/{name}/{profiles} which can be used to control cryptography -per application (name) and profile when clients call into the main -Environment resource.

[Note]Note

to control the cryptography in this granular way you must also -provide a @Bean of type TextEncryptorLocator that creates a -different encryptor per name and profiles. The one that is provided -by default does not do this (so all encryptions use the same key).

The spring command line client (with Spring Cloud CLI extensions -installed) can also be used to encrypt and decrypt, e.g.

$ spring encrypt mysecret --key foo
+

You can safely push this plain text to a shared git repository, and the secret password remains protected.

The server also exposes /encrypt and /decrypt endpoints (on the assumption that these are secured and only accessed by authorized agents). +If you edit a remote config file, you can use the Config Server to encrypt values by POSTing to the /encrypt endpoint, as shown in the following example:

$ curl localhost:8888/encrypt -d mysecret
+682bc583f4641835fa2db009355293665d2647dade3375c0ee201de2a49f7bda
[Note]Note

If the value you encrypt has characters in it that need to be URL encoded, you should use the --data-urlencode option to curl to make sure they are encoded properly.

[Tip]Tip

Be sure not to include any of the curl command statistics in the encrypted value. +Outputting the value to a file can help avoid this problem.

The inverse operation is also available through /decrypt (provided the server is +configured with a symmetric key or a full key pair), as shown in the following example:

$ curl localhost:8888/decrypt -d 682bc583f4641835fa2db009355293665d2647dade3375c0ee201de2a49f7bda
+mysecret
[Tip]Tip

If you testing with curl, then use --data-urlencode (instead of -d) or set an explicit Content-Type: text/plain to make sure curl encodes the data correctly when there are special characters ('+' is particularly tricky).

Take the encrypted value and add the {cipher} prefix before you put it in the YAML or properties file and before you commit and push it to a remote (potentially insecure) store.

The /encrypt and /decrypt endpoints also both accept paths in the form of /*/{name}/{profiles}, which can be used to control cryptography on a per-application (name) and per-profile basis when clients call into the main environment resource.

[Note]Note

To control the cryptography in this granular way, you must also provide a @Bean of type TextEncryptorLocator that creates a different encryptor per name and profiles. +The one that is provided by default does not do so (all encryptions use the same key).

The spring command line client (with Spring Cloud CLI extensions +installed) can also be used to encrypt and decrypt, as shown in the following example:

$ spring encrypt mysecret --key foo
 682bc583f4641835fa2db009355293665d2647dade3375c0ee201de2a49f7bda
 $ spring decrypt --key foo 682bc583f4641835fa2db009355293665d2647dade3375c0ee201de2a49f7bda
-mysecret

To use a key in a file (e.g. an RSA public key for encryption) prepend -the key value with "@" and provide the file path, e.g.

$ spring encrypt mysecret --key @${HOME}/.ssh/id_rsa.pub
-AQAjPgt3eFZQXwt8tsHAVv/QHiY5sI2dRcR+...

The key argument is mandatory (despite having a -- prefix).

2.5 Key Management

The Config Server can use a symmetric (shared) key or an asymmetric -one (RSA key pair). The asymmetric choice is superior in terms of -security, but it is often more convenient to use a symmetric key since -it is just a single property value to configure in the bootstrap.properties.

To configure a symmetric key you just need to set encrypt.key to a -secret String (or use an enviroment variable ENCRYPT_KEY to keep it -out of plain text configuration files).

To configure an asymmetric key you can either set the key as a -PEM-encoded text value (in encrypt.key), or via a keystore (e.g. as -created by the keytool utility that comes with the JDK). The -keystore properties are encrypt.keyStore.* with * equal to

  • location (a Resource location),
  • password (to unlock the keystore) and
  • alias (to identify which key in the store is to be -used).

The encryption is done with the public key, and a private key is -needed for decryption. Thus in principle you can configure only the -public key in the server if you only want to do encryption (and are -prepared to decrypt the values yourself locally with the private -key). In practice you might not want to do that because it spreads the -key management process around all the clients, instead of -concentrating it in the server. On the other hand it’s a useful option -if your config server really is relatively insecure and only a -handful of clients need the encrypted properties.

2.6 Creating a Key Store for Testing

To create a keystore for testing you can do something like this:

$ keytool -genkeypair -alias mytestkey -keyalg RSA \
+mysecret

To use a key in a file (such as an RSA public key for encryption), prepend +the key value with "@" and provide the file path, as shown in the following example:

$ spring encrypt mysecret --key @${HOME}/.ssh/id_rsa.pub
+AQAjPgt3eFZQXwt8tsHAVv/QHiY5sI2dRcR+...
[Note]Note

The --key argument is mandatory (despite having a -- prefix).

2.5 Key Management

The Config Server can use a symmetric (shared) key or an asymmetric one (RSA key pair). +The asymmetric choice is superior in terms of security, but it is often more convenient to use a symmetric key since it is a single property value to configure in the bootstrap.properties.

To configure a symmetric key, you need to set encrypt.key to a secret String (or use the ENCRYPT_KEY environment variable to keep it out of plain-text configuration files).

To configure an asymmetric key, you can either set the key as a PEM-encoded text value (in encrypt.key) or use a keystore (such as the keystore created by the keytool utility that comes with the JDK). +The following table describes the keystore properties:

PropertyDescription

encrypt.keyStore.location

Contains a Resource location

encrypt.keyStore.password

Holds the password that unlocks the keystore

encrypt.keyStore.alias

Identifies which key in the store to use

The encryption is done with the public key, and a private key is +needed for decryption. +Thus, in principle, you can configure only the public key in the server if you want to only encrypt (and are prepared to decrypt the values yourself locally with the private key). +In practice, you might not want to do decrypt locally, because it spreads the key management process around all the clients, instead of +concentrating it in the server. +On the other hand, it can be a useful option if your config server is relatively insecure and only a handful of clients need the encrypted properties.

2.6 Creating a Key Store for Testing

To create a keystore for testing, you can use a command resembling the following:

$ keytool -genkeypair -alias mytestkey -keyalg RSA \
   -dname "CN=Web Server,OU=Unit,O=Organization,L=City,S=State,C=US" \
-  -keypass changeme -keystore server.jks -storepass letmein

Put the server.jks file in the classpath (for instance) and then in -your bootstrap.yml for the Config Server:

encrypt:
+  -keypass changeme -keystore server.jks -storepass letmein

Put the server.jks file in the classpath (for instance) and then, in +your bootstrap.yml, for the Config Server, create the following settings:

encrypt:
   keyStore:
     location: classpath:/server.jks
     password: letmein
     alias: mytestkey
-    secret: changeme

2.7 Using Multiple Keys and Key Rotation

In addition to the {cipher} prefix in encrypted property values, the -Config Server looks for {name:value} prefixes (zero or many) before -the start of the (Base64 encoded) cipher text. The keys are passed to -a TextEncryptorLocator which can do whatever logic it needs to -locate a TextEncryptor for the cipher. If you have configured a -keystore (encrypt.keystore.location) the default locator will look -for keys in the store with aliases as supplied by the "key" prefix, -i.e. with a cipher text like this:

foo:
-  bar: `{cipher}{key:testkey}...`

the locator will look for a key named "testkey". A secret can also be -supplied via a {secret:…​} value in the prefix, but if it is not -the default is to use the keystore password (which is what you get -when you build a keytore and don’t specify a secret). If you do -supply a secret it is recommended that you also encrypt the secrets -using a custom SecretLocator.

Key rotation is hardly ever necessary on cryptographic grounds if the -keys are only being used to encrypt a few bytes of configuration data -(i.e. they are not being used elsewhere), but occasionally you might -need to change the keys if there is a security breach for instance. In -that case all the clients would need to change their source config -files (e.g. in git) and use a new {key:…​} prefix in all the -ciphers, checking beforehand of course that the key alias is available -in the Config Server keystore.

[Tip]Tip

the {name:value} prefixes can also be added to plaintext posted -to the /encrypt endpoint, if you want to let the Config Server -handle all encryption as well as decryption.

2.8 Serving Encrypted Properties

Sometimes you want the clients to decrypt the configuration locally, -instead of doing it in the server. In that case you can still have -/encrypt and /decrypt endpoints (if you provide the encrypt.* -configuration to locate a key), but you need to explicitly switch off -the decryption of outgoing properties using -spring.cloud.config.server.encrypt.enabled=false. If you don’t care -about the endpoints, then it should work if you configure neither the -key nor the enabled flag.

3. Serving Alternative Formats

The default JSON format from the environment endpoints is perfect for -consumption by Spring applications because it maps directly onto the -Environment abstraction. If you prefer you can consume the same data -as YAML or Java properties by adding a suffix to the resource path -(".yml", ".yaml" or ".properties"). This can be useful for consumption -by applications that do not care about the structure of the JSON -endpoints, or the extra metadata they provide, for example an -application that is not using Spring might benefit from the simplicity -of this approach.

The YAML and properties representations have an additional flag -(provided as a boolean query parameter resolvePlaceholders) to -signal that placeholders in the source documents, in the standard -Spring ${…​} form, should be resolved in the output where possible -before rendering. This is a useful feature for consumers that don’t -know about the Spring placeholder conventions.

[Note]Note

there are limitations in using the YAML or properties formats, -mainly in relation to the loss of metadata. The JSON is structured as -an ordered list of property sources, for example, with names that -correlate with the source. The YAML and properties forms are coalesced -into a single map, even if the origin of the values has multiple -sources, and the names of the original source files are lost. The YAML -representation is not necessarily a faithful representation of the -YAML source in a backing repository either: it is constructed from a -list of flat property sources, and assumptions have to be made about -the form of the keys.

4. Serving Plain Text

Instead of using the Environment abstraction (or one of the -alternative representations of it in YAML or properties format) your -applications might need generic plain text configuration files, -tailored to their environment. The Config Server provides these -through an additional endpoint at /{name}/{profile}/{label}/{path} -where "name", "profile" and "label" have the same meaning as the -regular environment endpoint, but "path" is a file name -(e.g. log.xml). The source files for this endpoint are located in -the same way as for the environment endpoints: the same search path is -used as for properties or YAML files, but instead of aggregating all -matching resources, only the first one to match is returned.

After a resource is located, placeholders in the normal format -(${…​}) are resolved using the effective Environment for the -application name, profile and label supplied. In this way the resource -endpoint is tightly integrated with the environment -endpoints. Example, if you have this layout for a GIT (or SVN) -repository:

application.yml
+    secret: changeme

2.7 Using Multiple Keys and Key Rotation

In addition to the {cipher} prefix in encrypted property values, the Config Server looks for zero or more {name:value} prefixes before the start of the (Base64 encoded) cipher text. +The keys are passed to a TextEncryptorLocator, which can do whatever logic it needs to locate a TextEncryptor for the cipher. +If you have configured a keystore (encrypt.keystore.location), the default locator looks for keys with aliases supplied by the key prefix, with a cipher text like resembling the following:

foo:
+  bar: `{cipher}{key:testkey}...`

The locator looks for a key named "testkey". +A secret can also be supplied by using a {secret:…​} value in the prefix. +However, if it is not supplied, the default is to use the keystore password (which is what you get when you build a keytore and do not specify a secret). +If you do supply a secret, you should also encrypt the secret using a custom SecretLocator.

When the keys are being used only to encrypt a few bytes of configuration data (that is, they are not being used elsewhere), key rotation is hardly ever necessary on cryptographic grounds. +However, you might occasionally need to change the keys (for example, in the event of a security breach). +In that case, all the clients would need to change their source config files (for example, in git) and use a new {key:…​} prefix in all the ciphers. +Note that the clients need to first check that the key alias is available in the Config Server keystore.

[Tip]Tip

If you want to let the Config Server handle all encryption as well as decryption, the {name:value} prefixes can also be added as plain text posted to the /encrypt endpoint, .

2.8 Serving Encrypted Properties

Sometimes you want the clients to decrypt the configuration locally, instead of doing it in the server. +In that case, if you provide the encrypt.* configuration to locate a key, you can still have /encrypt and /decrypt endpoints, but you need to explicitly switch off the decryption of outgoing properties by setting spring.cloud.config.server.encrypt.enabled=false. +If you do not care about the endpoints, it should work if you do not configure either the key or the enabled flag.

3. Serving Alternative Formats

The default JSON format from the environment endpoints is perfect for consumption by Spring applications, because it maps directly onto the Environment abstraction. +If you prefer, you can consume the same data as YAML or Java properties by adding a suffix (".yml", ".yaml" or ".properties") to the resource path. +This can be useful for consumption by applications that do not care about the structure of the JSON endpoints or the extra metadata they provide (for example, an application that is not using Spring might benefit from the simplicity of this approach).

The YAML and properties representations have an additional flag (provided as a boolean query parameter called resolvePlaceholders) to signal that placeholders in the source documents (in the standard Spring ${…​} form) should be resolved in the output before rendering, where possible. +This is a useful feature for consumers that do not know about the Spring placeholder conventions.

[Note]Note

There are limitations in using the YAML or properties formats, mainly in relation to the loss of metadata. +For example, the JSON is structured as an ordered list of property sources, with names that correlate with the source. +The YAML and properties forms are coalesced into a single map, even if the origin of the values has multiple sources, and the names of the original source files are lost. +Also, the YAML representation is not necessarily a faithful representation of the YAML source in a backing repository either. It is constructed from a list of flat property sources, and assumptions have to be made about the form of the keys.

4. Serving Plain Text

Instead of using the Environment abstraction (or one of the alternative representations of it in YAML or properties format), your applications might need generic plain-text configuration files that are tailored to their environment. +The Config Server provides these through an additional endpoint at /{name}/{profile}/{label}/{path}, where name, profile, and label have the same meaning as the regular environment endpoint, but path is a file name (such as log.xml). +The source files for this endpoint are located in the same way as for the environment endpoints. +The same search path is used for properties and YAML files. +However, instead of aggregating all matching resources, only the first one to match is returned.

After a resource is located, placeholders in the normal format (${…​}) are resolved by using the effective Environment for the supplied application name, profile, and label. +In this way, the resource endpoint is tightly integrated with the environment endpoints. +Consider the following example for a GIT or SVN repository:

application.yml
 nginx.conf

where nginx.conf looks like this:

server {
     listen              80;
     server_name         ${nginx.server.name};
@@ -746,94 +491,45 @@ nginx.conf

where nginx.conf looks like this profiles: development nginx: server: - name: develop.com

then the /foo/default/master/nginx.conf resource looks like this:

server {
+    name: develop.com

The /foo/default/master/nginx.conf resource might be as follows:

server {
     listen              80;
     server_name         example.com;
 }

and /foo/development/master/nginx.conf like this:

server {
     listen              80;
     server_name         develop.com;
-}
[Note]Note

Just like the source files for environment configuration, the -"profile" is used to resolve the file name, so if you want a -profile-specific file then /*/development/*/logback.xml will be -resolved by a file called logback-development.xml (in preference -to logback.xml).

[Note]Note

If you do not want to supply the label and let the server use the default label, you can supply a useDefaultLabel request parameter. So, the above example for the default profile could look like /foo/default/nginx.conf?useDefaultLabel.

5. Embedding the Config Server

The Config Server runs best as a standalone application, but if you -need to you can embed it in another application. Just use the -@EnableConfigServer annotation. An optional property that can be -useful in this case is spring.cloud.config.server.bootstrap which is -a flag to indicate that the server should configure itself from its -own remote repository. The flag is off by default because it can delay -startup, but when embedded in another application it makes sense to -initialize the same way as any other application.

[Note]Note

It should be obvious, but remember that if you use the bootstrap -flag the config server will need to have its name and repository URI -configured in bootstrap.yml.

To change the location of the server endpoints you can (optionally) -set spring.cloud.config.server.prefix, e.g. "/config", to serve the -resources under a prefix. The prefix should start but not end with a -"/". It is applied to the @RequestMappings in the Config Server -(i.e. underneath the Spring Boot prefixes server.servletPath and -server.contextPath).

If you want to read the configuration for an application directly from -the backend repository (instead of from the config server) that’s -basically an embedded config server with no endpoints. You can switch -off the endpoints entirely if you don’t use the @EnableConfigServer -annotation (just set spring.cloud.config.server.bootstrap=true).

6. Push Notifications and Spring Cloud Bus

Many source code repository providers (like Github, Gitlab, Gitee or Bitbucket -for instance) will notify you of changes in a repository through a -webhook. You can configure the webhook via the provider’s user -interface as a URL and a set of events in which you are -interested. For instance -Github -will POST to the webhook with a JSON body containing a list of -commits, and a header "X-Github-Event" equal to "push". If you add a -dependency on the spring-cloud-config-monitor library and activate -the Spring Cloud Bus in your Config Server, then a "/monitor" endpoint -is enabled.

When the webhook is activated the Config Server will send a -RefreshRemoteApplicationEvent targeted at the applications it thinks -might have changed. The change detection can be strategized, but by -default it just looks for changes in files that match the application -name (e.g. "foo.properties" is targeted at the "foo" application, and -"application.properties" is targeted at all applications). The strategy -if you want to override the behaviour is PropertyPathNotificationExtractor -which accepts the request headers and body as parameters and returns a list -of file paths that changed.

The default configuration works out of the box with Github, Gitlab, Gitee or -Bitbucket. In addition to the JSON notifications from Github, Gitlab, Gitee -or Bitbucket you can trigger a change notification by POSTing to -"/monitor" with a form-encoded body parameters path={name}. This will -broadcast to applications matching the "{name}" pattern (can contain -wildcards).

[Note]Note

the RefreshRemoteApplicationEvent will only be transmitted if -the spring-cloud-bus is activated in the Config Server and in the -client application.

[Note]Note

the default configuration also detects filesystem changes in -local git repositories (the webhook is not used in that case but as -soon as you edit a config file a refresh will be broadcast).

7. Spring Cloud Config Client

A Spring Boot application can take immediate advantage of the Spring -Config Server (or other external property sources provided by the -application developer), and it will also pick up some additional -useful features related to Environment change events.

7.1 Config First Bootstrap

This is the default behaviour for any application which has the Spring -Cloud Config Client on the classpath. When a config client starts up -it binds to the Config Server (via the bootstrap configuration -property spring.cloud.config.uri) and initializes Spring -Environment with remote property sources.

The net result of this is that all client apps that want to consume -the Config Server need a bootstrap.yml (or an environment variable) -with the server address in spring.cloud.config.uri (defaults to -"http://localhost:8888").

7.2 Discovery First Bootstrap

If you are using a `DiscoveryClient implementation, such as Spring Cloud Netflix -and Eureka Service Discovery or Spring Cloud Consul (Spring Cloud Zookeeper does -not support this yet), then you can have the Config Server register with the -Discovery Service if you want to, but in the default "Config First" mode, -clients won’t be able to take advantage of the registration.

If you prefer to use DiscoveryClient to locate the Config Server, you can do -that by setting spring.cloud.config.discovery.enabled=true (default -"false"). The net result of that is that client apps all need a -bootstrap.yml (or an environment variable) with the appropriate discovery -configuration. For example, with Spring Cloud Netflix, you need to define the -Eureka server address, e.g. in eureka.client.serviceUrl.defaultZone. The -price for using this option is an extra network round trip on start up to -locate the service registration. The benefit is that the Config Server -can change its co-ordinates, as long as the Discovery Service is a fixed point. The -default service id is "configserver" but you can change that on the -client with spring.cloud.config.discovery.serviceId (and on the server -in the usual way for a service, e.g. by setting spring.application.name).

The discovery client implementations all support some kind of metadata -map (e.g. for Eureka we have eureka.instance.metadataMap). Some -additional properties of the Config Server may need to be configured -in its service registration metadata so that clients can connect -correctly. If the Config Server is secured with HTTP Basic you can -configure the credentials as "username" and "password". And if the -Config Server has a context path you can set "configPath". Example, -for a Config Server that is a Eureka client:

bootstrap.yml.  +}

[Note]Note

As with the source files for environment configuration, the profile is used to resolve the file name. +So, if you want a profile-specific file, /*/development/*/logback.xml can be resolved by a file called logback-development.xml (in preference to logback.xml).

[Note]Note

If you do not want to supply the label and let the server use the default label, you can supply a useDefaultLabel request parameter. +So, the preceding example for the default profile could be /foo/default/nginx.conf?useDefaultLabel.

5. Embedding the Config Server

The Config Server runs best as a standalone application. +However, if need be, you can embed it in another application. +To do so, use the @EnableConfigServer annotation. +An optional property named spring.cloud.config.server.bootstrap can be useful in this case is. +It is a flag to indicate whether the server should configure itself from its own remote repository. +By default, the flag is off, because it can delay startup. +However, when embedded in another application, it makes sense to initialize the same way as any other application.

[Note]Note

If you use the bootstrap flag, the config server needs to have its name and repository URI configured in bootstrap.yml.

To change the location of the server endpoints, you can (optionally) set spring.cloud.config.server.prefix (for example, /config), to serve the resources under a prefix. +The prefix should start but not end with a /. +It is applied to the @RequestMappings in the Config Server (that is, underneath the Spring Boot server.servletPath and server.contextPath prefixes).

If you want to read the configuration for an application directly from the backend repository (instead of from the config server), you +basically wat an embedded config server with no endpoints. +You can switch off the endpoints entirely by not using the @EnableConfigServer annotation (set spring.cloud.config.server.bootstrap=true).

6. Push Notifications and Spring Cloud Bus

Many source code repository providers (such as Github, Gitlab, Gitee, or Bitbucket) notify you of changes in a repository through a webhook. +You can configure the webhook through the provider’s user interface as a URL and a set of events in which you are interested. +For instance, Github uses a POST to the webhook with a JSON body containing a list of commits and a header (X-Github-Event) set to push. +If you add a dependency on the spring-cloud-config-monitor library and activate the Spring Cloud Bus in your Config Server, then a /monitor endpoint is enabled.

When the webhook is activated, the Config Server sends a RefreshRemoteApplicationEvent targeted at the applications it thinks might have changed. +The change detection can be strategized. +However, by default, it looks for changes in files that match the application name (for example, foo.properties is targeted at the foo application, while application.properties is targeted at all applications). +The strategy to use when you want to override the behavior is PropertyPathNotificationExtractor, which accepts the request headers and body as parameters and returns a list of file paths that changed.

The default configuration works out of the box with Github, Gitlab, Gitee, or Bitbucket. +In addition to the JSON notifications from Github, Gitlab, Gitee, or Bitbucket, you can trigger a change notification by POSTing to /monitor with form-encoded body parameters in the pattern of path={name}. +Doing so broadcasts to applications matching the {name} pattern (which can contain wildcards).

[Note]Note

The RefreshRemoteApplicationEvent is transmitted only if the spring-cloud-bus is activated in both the Config Server and in the client application.

[Note]Note

The default configuration also detects filesystem changes in local git repositories. In that case, the webhook is not used. However, as soon as you edit a config file, a refresh is broadcast.

7. Spring Cloud Config Client

A Spring Boot application can take immediate advantage of the Spring Config Server (or other external property sources provided by the application developer). +It also picks up some additional useful features related to Environment change events.

7.1 Config First Bootstrap

The default behavior for any application that has the Spring Cloud Config Client on the classpath is as follows: +When a config client starts, it binds to the Config Server (through the spring.cloud.config.uri bootstrap configuration property) and initializes Spring Environment with remote property sources.

The net result of this behavior is that all client applciations that want to consume the Config Server need a bootstrap.yml (or an environment variable) with the server address set in spring.cloud.config.uri (it defaults to "http://localhost:8888").

7.2 Discovery First Bootstrap

If you use a `DiscoveryClient implementation, such as Spring Cloud Netflix and Eureka Service Discovery or Spring Cloud Consul, you can have the Config Server register with the Discovery Service. +However, in the default “Config First” mode, clients cannot take advantage of the registration.

If you prefer to use DiscoveryClient to locate the Config Server, you can do so by setting spring.cloud.config.discovery.enabled=true (the default is false). +The net result of doing so is that client applications all need a bootstrap.yml (or an environment variable) with the appropriate discovery configuration. +For example, with Spring Cloud Netflix, you need to define the Eureka server address (for example, in eureka.client.serviceUrl.defaultZone). +The price for using this option is an extra network round trip on startup, to locate the service registration. +The benefit is that, as long as the Discovery Service is a fixed point, the Config Server can change its coordinates. +The default service ID is configserver, but you can change that on the client by setting spring.cloud.config.discovery.serviceId (and on the server, in the usual way for a service, such as by setting spring.application.name).

The discovery client implementations all support some kind of metadata map (for example, we have eureka.instance.metadataMap for Eureka). +Some additional properties of the Config Server may need to be configured in its service registration metadata so that clients can connect correctly. +If the Config Server is secured with HTTP Basic, you can configure the credentials as username and password. +Also, if the Config Server has a context path, you can set configPath. +For example, the following YAML file is for a Config Server that is a Eureka client:

bootstrap.yml. 

eureka:
   instance:
     ...
@@ -841,57 +537,44 @@ for a Config Server that is a Eureka client:

bootstrap.yml.  user: osufhalskjrtl password: lviuhlszvaorhvlo5847 configPath: /config

-

7.3 Config Client Fail Fast

In some cases, it may be desirable to fail startup of a service if -it cannot connect to the Config Server. If this is the desired -behavior, set the bootstrap configuration property -spring.cloud.config.fail-fast=true and the client will halt with -an Exception.

7.4 Config Client Retry

If you expect that the config server may occasionally be unavailable when -your app starts, you can ask it to keep trying after a failure. First you need -to set spring.cloud.config.fail-fast=true, and then you need to add -spring-retry and spring-boot-starter-aop to your classpath. The default -behaviour is to retry 6 times with an initial backoff interval of 1000ms and an -exponential multiplier of 1.1 for subsequent backoffs. You can configure these -properties (and others) using spring.cloud.config.retry.* configuration properties.

[Tip]Tip

To take full control of the retry add a @Bean of type -RetryOperationsInterceptor with id "configServerRetryInterceptor". Spring -Retry has a RetryInterceptorBuilder that makes it easy to create one.

7.5 Locating Remote Configuration Resources

The Config Service serves property sources from /{name}/{profile}/{label}, where the default bindings in the client app are

  • "name" = ${spring.application.name}
  • "profile" = ${spring.profiles.active} (actually Environment.getActiveProfiles())
  • "label" = "master"

All of them can be overridden by setting spring.cloud.config.* -(where * is "name", "profile" or "label"). The "label" is useful for -rolling back to previous versions of configuration; with the default -Config Server implementation it can be a git label, branch name or -commit id. Label can also be provided as a comma-separated list, in -which case the items in the list are tried on-by-one until one succeeds. -This can be useful when working on a feature branch, for instance, -when you might want to align the config label with your branch, but -make it optional (e.g. spring.cloud.config.label=myfeature,develop).

7.6 Security

If you use HTTP Basic security on the server then clients just need to -know the password (and username if it isn’t the default). You can do -that via the config server URI, or via separate username and password -properties, e.g.

bootstrap.yml.  +

7.3 Config Client Fail Fast

In some cases, you may want to fail startup of a service if it cannot connect to the Config Server. +If this is the desired behavior, set the bootstrap configuration property spring.cloud.config.fail-fast=true to make the client halt with an Exception.

7.4 Config Client Retry

If you expect that the config server may occasionally be unavailable when your application starts, you can make it keep trying after a failure. +First, you need to set spring.cloud.config.fail-fast=true. +Then you need to add spring-retry and spring-boot-starter-aop to your classpath. +The default behavior is to retry six times with an initial backoff interval of 1000ms and an exponential multiplier of 1.1 for subsequent backoffs. +You can configure these properties (and others) by setting the spring.cloud.config.retry.* configuration properties.

[Tip]Tip

To take full control of the retry behavior, add a @Bean of type RetryOperationsInterceptor with an ID of configServerRetryInterceptor. +Spring Retry has a RetryInterceptorBuilder that supports creating one.

7.5 Locating Remote Configuration Resources

The Config Service serves property sources from /{name}/{profile}/{label}, where the default bindings in the client app are as follows:

  • "name" = ${spring.application.name}
  • "profile" = ${spring.profiles.active} (actually Environment.getActiveProfiles())
  • "label" = "master"

You can override all of them by setting spring.cloud.config.* (where * is name, profile or label). +The label is useful for rolling back to previous versions of configuration. +With the default Config Server implementation, it can be a git label, branch name, or commit ID. +Label can also be provided as a comma-separated list. +In that case, the items in the list are tried one by one until one succeeds. +This behavior can be useful when working on a feature branch. +For instance, you might want to align the config label with your branch but make it optional (in that case, use spring.cloud.config.label=myfeature,develop).

7.6 Security

If you use HTTP Basic security on the server, clients need to know the password (and username if it is not the default). +You can specify the username and password through the config server URI or via separate username and password properties, as shown in the following example:

bootstrap.yml. 

spring:
   cloud:
     config:
      uri: https://user:secret@myconfig.mycompany.com

-

or

bootstrap.yml.  +

The following example shows an alternate way to pass the same information:

bootstrap.yml. 

spring:
   cloud:
     config:
      uri: https://myconfig.mycompany.com
      username: user
      password: secret

-

The spring.cloud.config.password and spring.cloud.config.username -values override anything that is provided in the URI.

If you deploy your apps on Cloud Foundry then the best way to provide -the password is through service credentials, e.g. in the URI, since -then it doesn’t even need to be in a config file. An example which -works locally and for a user-provided service on Cloud Foundry named -"configserver":

bootstrap.yml.  +

The spring.cloud.config.password and spring.cloud.config.username values override anything that is provided in the URI.

If you deploy your apps on Cloud Foundry, the best way to provide the password is through service credentials (such as in the URI, since it does not need to be in a config file). +The following example works locally and for a user-provided service on Cloud Foundry named configserver:

bootstrap.yml. 

spring:
   cloud:
     config:
      uri: ${vcap.services.configserver.credentials.uri:http://user:password@localhost:8888}

-

If you use another form of security you might need to provide a -RestTemplate to the ConfigServicePropertySourceLocator (e.g. by -grabbing it in the bootstrap context and injecting one).

7.6.1 Health Indicator

The Config Client supplies a Spring Boot Health Indicator that attempts to load configuration from Config Server. The health indicator can be disabled by setting health.config.enabled=false. The response is also cached for performance reasons. The default cache time to live is 5 minutes. To change that value set the health.config.time-to-live property (in milliseconds).

7.6.2 Providing A Custom RestTemplate

In some cases you might need to customize the requests made to the config server from -the client. Typically this involves passing special Authorization headers to -authenticate requests to the server. To provide a custom RestTemplate follow the -steps below.

  1. Create a new configuration bean with an implementation of PropertySourceLocator.

CustomConfigServiceBootstrapConfiguration.java.  +

If you use another form of security, you might need to provide a RestTemplate to the ConfigServicePropertySourceLocator (for example, by grabbing it in the bootstrap context and injecting it).

7.6.1 Health Indicator

The Config Client supplies a Spring Boot Health Indicator that attempts to load configuration from the Config Server. +The health indicator can be disabled by setting health.config.enabled=false. +The response is also cached for performance reasons. +The default cache time to live is 5 minutes. +To change that value, set the health.config.time-to-live property (in milliseconds).

7.6.2 Providing A Custom RestTemplate

In some cases, you might need to customize the requests made to the config server from the client. +Typically, doing so involves passing special Authorization headers to authenticate requests to the server. +To provide a custom RestTemplate:

  1. Create a new configuration bean with an implementation of PropertySourceLocator, as shown in the following example:

CustomConfigServiceBootstrapConfiguration.java. 

@Configuration
 public class CustomConfigServiceBootstrapConfiguration {
     @Bean
@@ -902,17 +585,16 @@ steps below.

  1. return configServicePropertySourceLocator; } }

-

  1. In resources/META-INF create a file called -spring.factories and specify your custom configuration.

spring.factories.  +

  1. In resources/META-INF, create a file called +spring.factories and specify your custom configuration, as shown in the following example:

spring.factories. 

org.springframework.cloud.bootstrap.BootstrapConfiguration = com.my.config.client.CustomConfigServiceBootstrapConfiguration

-

7.6.3 Vault

When using Vault as a backend to your config server the client will need to -supply a token for the server to retrieve values from Vault. This token -can be provided within the client by setting spring.cloud.config.token -in bootstrap.yml.

bootstrap.yml.  +

7.6.3 Vault

When using Vault as a backend to your config server, the client needs to supply a token for the server to retrieve values from Vault. +This token can be provided within the client by setting spring.cloud.config.token +in bootstrap.yml, as shown in the following example:

bootstrap.yml. 

spring:
   cloud:
     config:
       token: YourVaultToken

-

7.7 Vault

7.7.1 Nested Keys In Vault

Vault supports the ability to nest keys in a value stored in Vault. For example

echo -n '{"appA": {"secret": "appAsecret"}, "bar": "baz"}' | vault write secret/myapp -

This command will write a JSON object to your Vault. To access these values in Spring -you would use the traditional dot(.) annotation. For example

@Value("${appA.secret}")
-String name = "World";

The above code would set the name variable to appAsecret.

\ No newline at end of file +

7.7 Nested Keys In Vault

Vault supports the ability to nest keys in a value stored in Vault, as shown in the following example:

echo -n '{"appA": {"secret": "appAsecret"}, "bar": "baz"}' | vault write secret/myapp -

This command writes a JSON object to your Vault. +To access these values in Spring, you would use the traditional dot(.) annotation, as shown in the following example

@Value("${appA.secret}")
+String name = "World";

The preceding code would sets the value of the name variable to appAsecret.

\ No newline at end of file diff --git a/spring-cloud-config.xml b/spring-cloud-config.xml index 09fe31e2..8b516f15 100644 --- a/spring-cloud-config.xml +++ b/spring-cloud-config.xml @@ -4,44 +4,40 @@ Spring Cloud Config -2018-03-21 +2018-03-22 2.0.0.BUILD-SNAPSHOT -Spring Cloud Config provides server and client-side support for externalized configuration in a distributed system. With the Config Server you have a central place to manage external properties for applications across all environments. The concepts on both client and server map identically to the Spring Environment and PropertySource abstractions, so they fit very well with Spring applications, but can be used with any application running in any language. As an application moves through the deployment pipeline from dev to test and into production you can manage the configuration between those environments and be certain that applications have everything they need to run when they migrate. The default implementation of the server storage backend uses git so it easily supports labelled versions of configuration environments, as well as being accessible to a wide range of tooling for managing the content. It is easy to add alternative implementations and plug them in with Spring configuration. +Spring Cloud Config provides server-side and client-side support for externalized configuration in a distributed system. With the Config Server, you have a central place to manage external properties for applications across all environments. +The concepts on both client and server map identically to the Spring Environment and PropertySource abstractions, so they fit very well with Spring applications but can be used with any application running in any language. +As an application moves through the deployment pipeline from dev to test and into production, you can manage the configuration between those environments and be certain that applications have everything they need to run when they migrate. +The default implementation of the server storage backend uses git, so it easily supports labelled versions of configuration environments as well as being accessible to a wide range of tooling for managing the content. +It is easy to add alternative implementations and plug them in with Spring configuration. Quick Start -Start the server: +This quick start walks through using both the server and the client of Spring Cloud Config Server. +First, start the server, as follows: $ cd spring-cloud-config-server $ ../mvnw spring-boot:run -The server is a Spring Boot application so you can run it from your -IDE instead if you prefer (the main class is -ConfigServerApplication). Then try out a client: +The server is a Spring Boot application, so you can run it from your IDE if you prefer to do so (the main class is ConfigServerApplication). +Next try out a client, as follows: $ curl localhost:8888/foo/development {"name":"foo","label":"master","propertySources":[ {"name":"https://github.com/scratches/config-repo/foo-development.properties","source":{"bar":"spam"}}, {"name":"https://github.com/scratches/config-repo/foo.properties","source":{"foo":"bar"}} ]} -The default strategy for locating property sources is to clone a git -repository (at spring.cloud.config.server.git.uri) and use it to -initialize a mini SpringApplication. The mini-application’s -Environment is used to enumerate property sources and publish them -via a JSON endpoint. -The HTTP service has resources in the form: +The default strategy for locating property sources is to clone a git repository (at spring.cloud.config.server.git.uri) and use it to initialize a mini SpringApplication. +The mini-application’s Environment is used to enumerate property sources and publish them at a JSON endpoint. +The HTTP service has resources in the following form: /{application}/{profile}[/{label}] /{application}-{profile}.yml /{label}/{application}-{profile}.yml /{application}-{profile}.properties /{label}/{application}-{profile}.properties -where the "application" is injected as the spring.config.name in the -SpringApplication (i.e. what is normally "application" in a regular -Spring Boot app), "profile" is an active profile (or comma-separated -list of properties), and "label" is an optional git label (defaults to -"master".) -Spring Cloud Config Server pulls configuration for remote clients -from a git repository (which must be provided): +where application is injected as the spring.config.name in the SpringApplication (what is normally application in a regular Spring Boot app), profile is an active profile (or comma-separated list of properties), and label is an optional git label (defaults to master.) +Spring Cloud Config Server pulls configuration for remote clients from a git repository (which must be provided), as shown in the following example: spring: cloud: config: @@ -50,14 +46,9 @@ from a git repository (which must be provided): uri: https://github.com/spring-cloud-samples/config-repo
Client Side Usage -To use these features in an application, just build it as a Spring -Boot application that depends on spring-cloud-config-client (e.g. see -the test cases for the config-client, or the sample app). The most -convenient way to add the dependency is via a Spring Boot starter -org.springframework.cloud:spring-cloud-starter-config. There is also a -parent pom and BOM (spring-cloud-starter-parent) for Maven users and a -Spring IO version management properties file for Gradle and Spring CLI -users. Example Maven configuration: +To use these features in an application, you can build it as a Spring Boot application that depends on spring-cloud-config-client (for an example, see the test cases for the config-client or the sample application). +The most convenient way to add the dependency is with a Spring Boot starter org.springframework.cloud:spring-cloud-starter-config. +There is also a parent pom and BOM (spring-cloud-starter-parent) for Maven users and a Spring IO version management properties file for Gradle and Spring CLI users. The following example shows a typical Maven configuration: pom.xml @@ -104,7 +95,7 @@ users. Example Maven configuration: <!-- repositories also needed for snapshots and milestones --> -Then you can create a standard Spring Boot application, like this simple HTTP server: +Now you can create a standard Spring Boot application, such as the following HTTP server: @SpringBootApplication @RestController public class Application { @@ -119,14 +110,10 @@ public class Application { } } -When it runs it will pick up the external configuration from the -default local config server on port 8888 if it is running. To modify -the startup behaviour you can change the location of the config server -using bootstrap.properties (like application.properties but for -the bootstrap phase of an application context), e.g. +When this HTTP server runs, it picks up the external configuration from the default local config server (if it is running) on port 8888. +To modify the startup behavior, you can change the location of the config server by using bootstrap.properties (similar to application.properties but for the bootstrap phase of an application context), as shown in the following example: spring.cloud.config.uri: http://myconfigserver.com -The bootstrap properties will show up in the /env endpoint as a -high-priority property source, e.g. +The bootstrap properties show up in the /env endpoint as a high-priority property source, as shown in the following example. $ curl localhost:8080/env { "profiles":[], @@ -135,21 +122,17 @@ high-priority property source, e.g. "systemProperties":{...}, ... } -(a property source called "configService:<URL of remote -repository>/<file name>" contains the property "foo" with value -"bar" and is highest priority). +A property source called ``configService:<URL of remote repository>/<file name> contains the foo property with a value of bar and is highest priority. -the URL in the property source name is the git repository not -the config server URL. +The URL in the property source name is the git repository, not the config server URL.
Spring Cloud Config Server -The Server provides an HTTP, resource-based API for external -configuration (name-value pairs, or equivalent YAML content). The -server is easily embeddable in a Spring Boot application using the -@EnableConfigServer annotation. So this app is a config server: +Spring Cloud Config Server provides an HTTP resource-based API for external configuration (name-value pairs or equivalent YAML content). +The server is embeddable in a Spring Boot application, by using the @EnableConfigServer annotation. +Consequently, the following application is a config server: ConfigServer.java @@ -162,12 +145,9 @@ public class ConfigServer { } -Like all Spring Boot apps it runs on port 8080 by default, but you -can switch it to the conventional port 8888 in various ways. The -easiest, which also sets a default configuration repository, -is by launching it with spring.config.name=configserver (there -is a configserver.yml in the Config Server jar). Another is -to use your own application.properties, e.g. +Like all Spring Boot applications, it runs on port 8080 by default, but you can switch it to the more conventional port 8888 in various ways. +The easiest, which also sets a default configuration repository, is by launching it with spring.config.name=configserver (there is a configserver.yml in the Config Server jar). +Another is to use your own application.properties, as shown in the following example: application.properties @@ -175,15 +155,12 @@ to use your own application.properties, e.g. spring.cloud.config.server.git.uri: file://${user.home}/config-repo -where ${user.home}/config-repo is a git repository containing -YAML and properties files. +where ${user.home}/config-repo is a git repository containing YAML and properties files. -in Windows you need an extra "/" in the file URL if it is -absolute with a drive prefix, e.g. file:///${user.home}/config-repo. +On Windows, you need an extra "/" in the file URL if it is absolute with a drive prefix (for example,file:///${user.home}/config-repo). -Here’s a recipe for creating the git repository in the example -above: +The following listing shows a recipe for creating the git repository in the preceding example: $ cd $HOME $ mkdir config-repo $ cd config-repo @@ -193,44 +170,33 @@ $ git add -A . $ git commit -m "Add application.properties" -using the local filesystem for your git repository is -intended for testing only. Use a server to host your -configuration repositories in production. +Using the local filesystem for your git repository is intended for testing only. +You should use a server to host your configuration repositories in production. -the initial clone of your configuration repository will -be quick and efficient if you only keep text files in it. If you start -to store binary files, especially large ones, you may experience -delays on the first request for configuration and/or out of memory -errors in the server. +The initial clone of your configuration repository can be quick and efficient if you keep only text files in it. +If you store binary files, especially large ones, you may experience delays on the first request for configuration or encounter out of memory errors in the server.
Environment Repository -Where do you want to store the configuration data for the Config -Server? The strategy that governs this behaviour is the -EnvironmentRepository, serving Environment objects. This -Environment is a shallow copy of the domain from the Spring -Environment (including propertySources as the main feature). The -Environment resources are parametrized by three variables: +Where should you store the configuration data for the Config Server? +The strategy that governs this behaviour is the EnvironmentRepository, serving Environment objects. +This Environment is a shallow copy of the domain from the Spring Environment (including propertySources as the main feature). +The Environment resources are parametrized by three variables: -{application} maps to "spring.application.name" on the client side; +{application}, which maps to spring.application.name on the client side. -{profile} maps to "spring.profiles.active" on the client (comma separated list); and +{profile}, which maps to spring.profiles.active on the client (comma-separated list). -{label} which is a server side feature labelling a "versioned" set of config files. +{label}, which is a server side feature labelling a "versioned" set of config files. -Repository implementations generally behave just like a Spring Boot -application loading configuration files from a "spring.config.name" -equal to the {application} parameter, and "spring.profiles.active" -equal to the {profiles} parameter. Precedence rules for profiles are -also the same as in a regular Boot application: active profiles take -precedence over defaults, and if there are multiple profiles the last -one wins (like adding entries to a Map). -Example: a client application has this bootstrap configuration: +Repository implementations generally behave like a Spring Boot application, loading configuration files from a spring.config.name equal to the {application} parameter, and spring.profiles.active equal to the {profiles} parameter. +Precedence rules for profiles are also the same as in a regular Spring Boot application: Active profiles take precedence over defaults, and, if there are multiple profiles, the last one wins (similar to adding entries to a Map). +The following sample client application has this bootstrap configuration: bootstrap.yml @@ -241,80 +207,55 @@ one wins (like adding entries to a Map). active: dev,mysql -(as usual with a Spring Boot application, these properties could also -be set as environment variables or command line arguments). -If the repository is file-based, the server will create an -Environment from application.yml (shared between all clients), and -foo.yml (with foo.yml taking precedence). If the YAML files have -documents inside them that point to Spring profiles, those are applied -with higher precedence (in order of the profiles listed), and if -there are profile-specific YAML (or properties) files these are also -applied with higher precedence than the defaults. Higher precedence -translates to a PropertySource listed earlier in the -Environment. (These are the same rules as apply in a standalone -Spring Boot application.) +(As usual with a Spring Boot application, these properties could also be set by environment variables or command line arguments). +If the repository is file-based, the server creates an +Environment from application.yml (shared between all clients) and +foo.yml (with foo.yml taking precedence). +If the YAML files have documents inside them that point to Spring profiles, those are applied with higher precedence (in order of the profiles listed). +If there are profile-specific YAML (or properties) files, these are also applied with higher precedence than the defaults. +Higher precedence translates to a PropertySource listed earlier in the Environment. +(These same rules apply in a standalone Spring Boot application.)
Git Backend -The default implementation of EnvironmentRepository uses a Git -backend, which is very convenient for managing upgrades and physical -environments, and also for auditing changes. To change the location of -the repository you can set the "spring.cloud.config.server.git.uri" -configuration property in the Config Server (e.g. in -application.yml). If you set it with a file: prefix it should work -from a local repository so you can get started quickly and easily -without a server, but in that case the server operates directly on the -local repository without cloning it (it doesn’t matter if it’s not -bare because the Config Server never makes changes to the "remote" -repository). To scale the Config Server up and make it highly -available, you would need to have all instances of the server pointing -to the same repository, so only a shared file system would work. Even -in that case it is better to use the ssh: protocol for a shared -filesystem repository, so that the server can clone it and use a local -working copy as a cache. -This repository implementation maps the {label} parameter of the -HTTP resource to a git label (commit id, branch name or tag). If the -git branch or tag name contains a slash ("/") then the label in the -HTTP URL should be specified with the special string "(_)" instead (to -avoid ambiguity with other URL paths). For example, if the label is -foo/bar, replacing the slash would result in a label that looks like -foo(_)bar. The inclusion of the special string "(_)" can also be -applied to the {application} parameter. Be careful with the brackets -in the URL if you are using a command line client like curl (e.g. -escape them from the shell with quotes ''). +The default implementation of EnvironmentRepository uses a Git backend, which is very convenient for managing upgrades and physical +environments and for auditing changes. +To change the location of the repository, you can set the spring.cloud.config.server.git.uri configuration property in the Config Server (for example in application.yml). +If you set it with a file: prefix, it should work from a local repository so that you can get started quickly and easily without a server. However, in that case, the server operates directly on the local repository without cloning it (it does not matter if it is not bare because the Config Server never makes changes to the "remote" repository). +To scale the Config Server up and make it highly available, you need to have all instances of the server pointing to the same repository, so only a shared file system would work. +Even in that case, it is better to use the ssh: protocol for a shared filesystem repository, so that the server can clone it and use a local working copy as a cache. +This repository implementation maps the {label} parameter of the HTTP resource to a git label (commit id, branch name, or tag). +If the git branch or tag name contains a slash (/), then the label in the HTTP URL should instead be specified with the special string $$_$$ (to avoid ambiguity with other URL paths). +For example, if the label is foo/bar, replacing the slash would result in the following label: foo($$_$$)bar. +The inclusion of the special string ($$_$$) can also be applied to the {application} parameter. +If you use a command-line client such as curl, be careful with the brackets in the URL — you should +escape them from the shell with single quotes ('').
Placeholders in Git URI -Spring Cloud Config Server supports a git repository URL with -placeholders for the {application} and {profile} (and {label} if -you need it, but remember that the label is applied as a git label -anyway). So you can easily support a "one repo per application" policy -using (for example): +Spring Cloud Config Server supports a git repository URL with placeholders for the {application} and {profile} (and {label} if you need it, but remember that the label is applied as a git label anyway). +So you can support a “one repository per application” policy by using a structure similar to the following: spring: cloud: config: server: git: uri: https://github.com/myorg/{application} -or a "one repo per profile" policy using a similar pattern but with +You can also support a “one repository per profile” policy by using a similar pattern but with {profile}. -Additionally, using the special string "(_)" within your -{application} parameters can enable support for multiple -organizations (for example): +Additionally, using the special string "($$_$$)" within your {application} parameters can enable support for multiple +organizations, as shown in the following example: spring: cloud: config: server: git: uri: https://github.com/{application} -where {application} is provided at request time in the format -"organization(_)application". +where {application} is provided at request time in the following format: organization($$_$$)application.
Pattern Matching and Multiple Repositories -There is also support for more complex requirements with pattern -matching on the application and profile name. The pattern format is a -comma-separated list of {application}/{profile} names with wildcards -(where a pattern beginning with a wildcard may need to be -quoted). Example: +Spring Cloud Config also includes support for more complex requirements with pattern +matching on the application and profile name. +The pattern format is a comma-separated list of {application}/{profile} names with wildcards (note that a pattern beginning with a wildcard may need to be quoted), as shown in the following example: spring: cloud: config: @@ -329,24 +270,14 @@ quoted). Example: local: pattern: local* uri: file:/home/configsvc/config-repo -If {application}/{profile} does not match any of the patterns, it -will use the default uri defined under -"spring.cloud.config.server.git.uri". In the above example, for the -"simple" repository, the pattern is simple/* (i.e. it only matches -one application named "simple" in all profiles). The "local" -repository matches all application names beginning with "local" in all -profiles (the /* suffix is added automatically to any pattern that -doesn’t have a profile matcher). +If {application}/{profile} does not match any of the patterns, it uses the default URI defined under spring.cloud.config.server.git.uri. +In the above example, for the “simple” repository, the pattern is simple/* (it only matches one application named simple in all profiles). The “local” repository matches all application names beginning with local in all profiles (the /* suffix is added automatically to any pattern that does not have a profile matcher). -the "one-liner" short cut used in the "simple" example above can -only be used if the only property to be set is the URI. If you need to -set anything else (credentials, pattern, etc.) you need to use the full -form. +The “one-liner” short cut used in the “simple” example can be used only if the only property to be set is the URI. +If you need to set anything else (credentials, pattern, and so on) you need to use the full form. -The pattern property in the repo is actually an array, so you can -use a YAML array (or [0], [1], etc. suffixes in properties files) -to bind to multiple patterns. You may need to do this if you are going -to run apps with multiple profiles. Example: +The pattern property in the repo is actually an array, so you can use a YAML array (or [0], [1], etc. suffixes in properties files) to bind to multiple patterns. +You may need to do so if you are going to run apps with multiple profiles, as shown in the following example: spring: cloud: config: @@ -365,16 +296,11 @@ to run apps with multiple profiles. Example: - '*/production' uri: https://github.com/staging/config-repo -Spring Cloud will guess that a pattern containing a profile that -doesn’t end in * implies that you actually want to match a list of -profiles starting with this pattern (so */staging is a shortcut for -["*/staging", "*/staging,*"]). This is common where you need to run -apps in the "development" profile locally but also the "cloud" profile -remotely, for instance. +Spring Cloud guesses that a pattern containing a profile that does not end in * implies that you actually want to match a list of profiles starting with this pattern (so */staging is a shortcut for ["*/staging", "*/staging,*"], and so on). +This is common where, for instance, you need to run applications in the “development” profile locally but also the “cloud” profile remotely. -Every repository can also optionally store config files in -sub-directories, and patterns to search for those directories can be -specified as searchPaths. For example at the top level: +Every repository can also optionally store config files in sub-directories, and patterns to search for those directories can be specified as searchPaths. +The following example shows a config file at the top level: spring: cloud: config: @@ -382,12 +308,10 @@ specified as searchPaths. For example at the top level: -In this example the server searches for config files in the top level -and in the "foo/" sub-directory and also any sub-directory whose name -begins with "bar". -By default the server clones remote repositories when configuration -is first requested. The server can be configured to clone the repositories -at startup. For example at the top level: +In the preceding example, the server searches for config files in the top level and in the foo/ sub-directory and also any sub-directory whose name begins with bar. +By default, the server clones remote repositories when configuration +is first requested. +The server can be configured to clone the repositories at startup, as shown in the following top-level example: spring: cloud: config: @@ -406,24 +330,17 @@ at startup. For example at the top level: team-c: pattern: team-c-* uri: http://git/team-a/config-repo.git -In this example the server clones team-a’s config-repo on startup before it -accepts any requests. All other repositories will not be cloned until -configuration from the repository is requested. +In the preceding example, the server clones team-a’s config-repo on startup, before it +accepts any requests. +All other repositories are not cloned until configuration from the repository is requested. -Setting a repository to be cloned when the Config Server starts up can -help to identify a misconfigured configuration source (e.g., an invalid -repository URI) quickly, while the Config Server is starting up. With -cloneOnStart not enabled for a configuration source, the Config Server may -start successfully with a misconfigured or invalid configuration source and -not detect an error until an application requests configuration from that -configuration source. +Setting a repository to be cloned when the Config Server starts up can help to identify a misconfigured configuration source (such as an invalid repository URI) quickly, while the Config Server is starting up. +With cloneOnStart not enabled for a configuration source, the Config Server may start successfully with a misconfigured or invalid configuration source and not detect an error until an application requests configuration from that configuration source.
Authentication -To use HTTP basic authentication on the remote repository add the -"username" and "password" properties separately (not in the URL), -e.g. +To use HTTP basic authentication on the remote repository, add the username and password properties separately (not in the URL), as shown in the following example: spring: cloud: config: @@ -432,45 +349,39 @@ e.g. uri: https://github.com/spring-cloud-samples/config-repo username: trolley password: strongpassword -If you don’t use HTTPS and user credentials, SSH should also work out -of the box when you store keys in the default directories (~/.ssh) -and the uri points to an SSH location, -e.g. "git@github.com:configuration/cloud-configuration". It is important that an entry for the Git server be present in the ~/.ssh/known_hosts file and that it is in ssh-rsa format. Other formats (like ecdsa-sha2-nistp256) are not supported. To avoid surprises, you should ensure that only one entry is present in the known_hosts file for the Git server and that it is matching with the URL you provided to the config server. If you used a hostname in the URL, you want to have exactly that in the known_hosts file, not the IP. -The repository is accessed using JGit, so any documentation you find on -that should be applicable. HTTPS proxy settings can be set in -~/.git/config or in the same way as for any other JVM process via +If you do not use HTTPS and user credentials, SSH should also work out of the box when you store keys in the default directories (~/.ssh) and the URI points to an SSH location, such as git@github.com:configuration/cloud-configuration. +It is important that an entry for the Git server be present in the ~/.ssh/known_hosts file and that it is in ssh-rsa format. +Other formats (such as ecdsa-sha2-nistp256) are not supported. +To avoid surprises, you should ensure that only one entry is present in the known_hosts file for the Git server and that it matches the URL you provided to the config server. +If you use a hostname in the URL, you want to have exactly that (not the IP) in the known_hosts file. +The repository is accessed by using JGit, so any documentation you find on that should be applicable. +HTTPS proxy settings can be set in ~/.git/config or (in the same way as for any other JVM process) with system properties (-Dhttps.proxyHost and -Dhttps.proxyPort). -If you don’t know where your ~/.git directory is use git config ---global to manipulate the settings (e.g. git config --global -http.sslVerify false). +If you do not know where your ~/.git directory is, use git config --global to manipulate the settings (for example, git config --global http.sslVerify false).
Authentication with AWS CodeCommit -AWS CodeCommit authentication can also be -done. AWS CodeCommit uses an authentication helper when using Git from the command line. This helper is not -used with the JGit library, so a JGit CredentialProvider for AWS CodeCommit will be created if the Git -URI matches the AWS CodeCommit pattern. AWS CodeCommit URIs always look like -https://git-codecommit.${AWS_REGION}.amazonaws.com/${repopath}. -If you provide a username and password with an AWS CodeCommit URI, then these must be -the AWS accessKeyId and secretAccessKey -to be used to access the repository. If you do not specify a username and password, -then the accessKeyId and secretAccessKey will be retrieved using the -AWS Default Credential Provider Chain. -If your Git URI matches the CodeCommit URI pattern (above) then you must provide -valid AWS credentials in the username and password, or in one of the locations supported -by the default credential provider chain. AWS EC2 instances may use -IAM Roles for EC2 Instances. -Note: The aws-java-sdk-core jar is an optional dependency. If the aws-java-sdk-core jar is not on your -classpath, then the AWS Code Commit credential provider will not be created regardless of the git server URI. +Spring Cloud Config Server also supports AWS CodeCommit authentication. +AWS CodeCommit uses an authentication helper when using Git from the command line. +This helper is not used with the JGit library, so a JGit CredentialProvider for AWS CodeCommit is created if the Git URI matches the AWS CodeCommit pattern. +AWS CodeCommit URIs follow this pattern://git-codecommit.${AWS_REGION}.amazonaws.com/${repopath}. +If you provide a username and password with an AWS CodeCommit URI, they must be the AWS accessKeyId and secretAccessKey that provide access to the repository. +If you do not specify a username and password, the accessKeyId and secretAccessKey are retrieved by using the AWS Default Credential Provider Chain. +If your Git URI matches the CodeCommit URI pattern (shown earlier), you must provide valid AWS credentials in the username and password or in one of the locations supported by the default credential provider chain. +AWS EC2 instances may use IAM Roles for EC2 Instances. + +The aws-java-sdk-core jar is an optional dependency. +If the aws-java-sdk-core jar is not on your classpath, the AWS Code Commit credential provider is not created, regardless of the git server URI. +
Git SSH configuration using properties -By default, the JGit library used by Spring Cloud Config Server uses SSH configuration files such as ~/.ssh/known_hosts and /etc/ssh/ssh_config when connecting to Git repositories using an SSH URI. -In cloud environments such as Cloud Foundry, the local filesystem may be ephemeral or not easily accessible. For cases such as these, SSH configuration can be set using -Java properties. In order to activate property based SSH configuration, the property spring.cloud.config.server.git.ignoreLocalSshSettings must be set to true. -Example: +By default, the JGit library used by Spring Cloud Config Server uses SSH configuration files such as ~/.ssh/known_hosts and /etc/ssh/ssh_config when connecting to Git repositories by using an SSH URI. +In cloud environments such as Cloud Foundry, the local filesystem may be ephemeral or not easily accessible. +For those cases, SSH configuration can be set by using Java properties. +In order to activate property-based SSH configuration, the spring.cloud.config.server.git.ignoreLocalSshSettings property must be set to true, as shown in the following example: spring: cloud: config: @@ -508,8 +419,9 @@ Example: q0TY3we+ERB40U8Z2BvU61QuwaunJ2+uGadHo58VSVdggqAo0BSkH58innKKt96J 69pcVH/4rmLbXdcmNYGm6iu+MlPQk4BUZknHSmVHIFdJ0EPupVaQ8RHT -----END RSA PRIVATE KEY----- +The following table describes the SSH configuration properties. -SSH Configuration properties +SSH Configuration Properties @@ -522,31 +434,31 @@ Example: ignoreLocalSshSettings -If true, use property based SSH config instead of file based. Must be set at as spring.cloud.config.server.git.ignoreLocalSshSettings, not inside a repository definition. +If true, use property-based instead of file-based SSH config. Must be set at as spring.cloud.config.server.git.ignoreLocalSshSettings, not inside a repository definition. privateKey -Valid SSH private key. Must be set if ignoreLocalSshSettings is true and Git URI is SSH format +Valid SSH private key. Must be set if ignoreLocalSshSettings is true and Git URI is SSH format. hostKey -Valid SSH host key. Must be set if hostKeyAlgorithm is also set +Valid SSH host key. Must be set if hostKeyAlgorithm is also set. hostKeyAlgorithm -One of ssh-dss, ssh-rsa, ecdsa-sha2-nistp256, ecdsa-sha2-nistp384 ,ecdsa-sha2-nistp521. Must be set if hostKey is also set +One of ssh-dss, ssh-rsa, ecdsa-sha2-nistp256, ecdsa-sha2-nistp384, or ecdsa-sha2-nistp521. Must be set if hostKey is also set. strictHostKeyChecking -true or false. If false, ignore errors with host key +true or false. If false, ignore errors with host key. knownHostsFile -Location of custom .known_hosts file +Location of custom .known_hosts file. preferredAuthentications -Override server authentication method order. This should allow evade login prompts if server has keyboard-interactive authentication before publickey method. +Override server authentication method order. This should allow for evading login prompts if server has keyboard-interactive authentication before the publickey method. @@ -554,9 +466,8 @@ Example:
Placeholders in Git Search Paths -Spring Cloud Config Server also supports a search path with -placeholders for the {application} and {profile} (and {label} if -you need it). Example: +Spring Cloud Config Server also supports a search path with placeholders for the {application} and {profile} (and {label} if +you need it), as shown in the following example: spring: cloud: config: @@ -564,20 +475,14 @@ you need it). Example: git: uri: https://github.com/spring-cloud-samples/config-repo searchPaths: '{application}' -searches the repository for files in the same name as the directory -(as well as the top level). Wildcards are also valid in a search -path with placeholders (any matching directory is included in the -search). +The preceding listing causes a search of the repository for files in the same name as the directory (as well as the top level). +Wildcards are also valid in a search path with placeholders (any matching directory is included in the search).
Force pull in Git Repositories -As mentioned before Spring Cloud Config Server makes a clone of the -remote git repository and if somehow the local copy gets dirty (e.g. -folder content changes by OS process) so Spring Cloud Config Server -cannot update the local copy from remote repository. -To solve this there is a force-pull property that will make Spring Cloud -Config Server force pull from remote repository if the local copy is dirty. -Example: +As mentioned earlier, Spring Cloud Config Server makes a clone of the remote git repository in case the local copy gets dirty (for example, +folder content changes by an OS process) such that Spring Cloud Config Server cannot update the local copy from remote repository. +To solve this issue, there is a force-pull property that makes Spring Cloud Config Server force pull from the remote repository if the local copy is dirty, as shown in the following example: spring: cloud: config: @@ -585,8 +490,7 @@ Example: git: uri: https://github.com/spring-cloud-samples/config-repo force-pull: true -If you have a multiple repositories configuration you can configure the -force-pull property per repository. Example: +If you have a multiple-repositories configuration, you can configure the force-pull property per repository, as shown in the following example: spring: cloud: config: @@ -636,72 +540,52 @@ Example:
Version Control Backend Filesystem Use -With VCS based backends (git, svn) files are checked out or cloned to the local filesystem. By default they are put in the system temporary directory with a prefix of config-repo-. On linux, for example it could be /tmp/config-repo-<randomid>. Some operating systems routinely clean out temporary directories. This can lead to unexpected behaviour such as missing properties. To avoid this problem, change the directory Config Server uses, by setting spring.cloud.config.server.git.basedir or spring.cloud.config.server.svn.basedir to a directory that does not reside in the system temp structure. +With VCS-based backends (git, svn), files are checked out or cloned to the local filesystem. +By default, they are put in the system temporary directory with a prefix of config-repo-. +On linux, for example, it could be /tmp/config-repo-<randomid>. +Some operating systems routinely clean out temporary directories. +This can lead to unexpected behavior, such as missing properties. +To avoid this problem, change the directory that Config Server uses by setting spring.cloud.config.server.git.basedir or spring.cloud.config.server.svn.basedir to a directory that does not reside in the system temp structure.
File System Backend -There is also a "native" profile in the Config Server that doesn’t use -Git, but just loads the config files from the local classpath or file -system (any static URL you want to point to with -"spring.cloud.config.server.native.searchLocations"). To use the -native profile just launch the Config Server with -"spring.profiles.active=native". +There is also a “native” profile in the Config Server that does not use Git but loads the config files from the local classpath or file system (any static URL you want to point to with spring.cloud.config.server.native.searchLocations). +To use the native profile, launch the Config Server with spring.profiles.active=native. -Remember to use the file: prefix for file resources (the -default without a prefix is usually the classpath). Just as with any -Spring Boot configuration you can embed ${}-style environment -placeholders, but remember that absolute paths in Windows require an -extra "/", e.g. file:///${user.home}/config-repo +Remember to use the file: prefix for file resources (the default without a prefix is usually the classpath). +As with any Spring Boot configuration, you can embed ${}-style environment placeholders, but remember that absolute paths in Windows require an extra / (for example, file:///${user.home}/config-repo). -The default value of the searchLocations is identical to a -local Spring Boot application (so [classpath:/, classpath:/config, -file:./, file:./config]). This does not expose the -application.properties from the server to all clients because any -property sources present in the server are removed before being sent -to the client. +The default value of the searchLocations is identical to a local Spring Boot application (that is, [classpath:/, classpath:/config, +file:./, file:./config]). +This does not expose the application.properties from the server to all clients, because any property sources present in the server are removed before being sent to the client. -A filesystem backend is great for getting started quickly and -for testing. To use it in production you need to be sure that the -file system is reliable, and shared across all instances of the -Config Server. +A filesystem backend is great for getting started quickly and for testing. +To use it in production, you need to be sure that the file system is reliable and shared across all instances of the Config Server. -The search locations can contain placeholders for {application}, -{profile} and {label}. In this way you can segregate the -directories in the path, and choose a strategy that makes sense for -you (e.g. sub-directory per application, or sub-directory per -profile). -If you don’t use placeholders in the search locations, this repository -also appends the {label} parameter of the HTTP resource to a suffix -on the search path, so properties files are loaded from each search -location and a subdirectory with the same name as the label (the -labelled properties take precedence in the Spring Environment). Thus -the default behaviour with no placeholders is the same as adding a -search location ending with /{label}/. For example file:/tmp/config -is the same as file:/tmp/config,file:/tmp/config/{label}. This behavior can be -disabled by setting spring.cloud.config.server.native.addLabelLocations=false. +The search locations can contain placeholders for {application}, {profile}, and {label}. +In this way, you can segregate the directories in the path and choose a strategy that makes sense for you (such as subdirectory per application or subdirectory per profile). +If you do not use placeholders in the search locations, this repository also appends the {label} parameter of the HTTP resource to a suffix on the search path, so properties files are loaded from each search location and a subdirectory with the same name as the label (the labelled properties take precedence in the Spring Environment). +Thus, the default behaviour with no placeholders is the same as adding a search location ending with /{label}/. +For example, file:/tmp/config is the same as file:/tmp/config,file:/tmp/config/{label}. +This behavior can be disabled by setting spring.cloud.config.server.native.addLabelLocations=false.
Vault Backend Spring Cloud Config Server also supports Vault as a backend. -Vault is a tool for securely accessing secrets. A secret is anything -that you want to tightly control access to, such as API keys, passwords, -certificates, and more. Vault provides a unified interface to any secret, -while providing tight access control and recording a detailed audit log. +Vault is a tool for securely accessing secrets. +A secret is anything that to which you want to tightly control access, such as API keys, passwords, certificates, and other sensitive information. Vault provides a unified interface to any secret while providing tight access control and recording a detailed audit log. -For more information on Vault see the Vault quickstart guide. -To enable the config server to use a Vault backend you can run your config server -with the vault profile. For example in your config server’s application.properties -you can add spring.profiles.active=vault. -By default the config server will assume your Vault server is running at -http://127.0.0.1:8200. It also will assume that the name of backend -is secret and the key is application. All of these defaults can be -configured in your config server’s application.properties. Below is a -table of configurable Vault properties. All properties are prefixed with -spring.cloud.config.server.vault. +For more information on Vault, see the Vault quick start guide. +To enable the config server to use a Vault backend, you can run your config server with the vault profile. +For example, in your config server’s application.properties, you can add spring.profiles.active=vault. +By default, the config server assumes that your Vault server runs at http://127.0.0.1:8200. +It also assumes that the name of backend is secret and the key is application. +All of these defaults can be configured in your config server’s application.properties. +The following table describes configurable Vault properties: @@ -740,16 +624,19 @@ table of configurable Vault properties. All properties are prefixed with -All configurable properties can be found in -org.springframework.cloud.config.server.environment.VaultEnvironmentRepository. -With your config server running you can make HTTP requests to the server to retrieve -values from the Vault backend. To do this you will need a token for your Vault server. -First place some data in you Vault. For example + +All of the properties in the preceding table must be prefixed with spring.cloud.config.server.vault. + +All configurable properties can be found in org.springframework.cloud.config.server.environment.VaultEnvironmentRepository. +With your config server running, you can make HTTP requests to the server to retrieve +values from the Vault backend. +To do so, you need a token for your Vault server. +First, place some data in you Vault, as shown in the following example: $ vault write secret/application foo=bar baz=bam $ vault write secret/myapp foo=myappsbar -Now make the HTTP request to your config server to retrieve the values. +Second, make an HTTP request to your config server to retrieve the values, as shown in the following example: $ curl -X "GET" "http://localhost:8888/myapp/default" -H "X-Config-Token: yourtoken" -You should see a response similar to this after making the above request. +You should see a response similar to the following: { "name":"myapp", "profiles":[ @@ -776,79 +663,60 @@ $ vault write secret/myapp foo=myappsbar }
Multiple Properties Sources -When using Vault you can provide your applications with multiple properties sources. -For example, assume you have written data to the following paths in Vault. +When using Vault, you can provide your applications with multiple properties sources. +For example, assume you have written data to the following paths in Vault: secret/myApp,dev secret/myApp secret/application,dev secret/application -Properties written to secret/application are available to -all applications using the Config Server. An -application with the name myApp would have any properties -written to secret/myApp and secret/application available to it. -When myApp has the dev profile enabled then properties written to -all of the above paths would be available to it, with properties in -the first path in the list taking priority over the others. +Properties written to secret/application are available to all applications using the Config Server. +An application with the name, myApp, would have any properties written to secret/myApp and secret/application available to it. +When myApp has the dev profile enabled, properties written to all of the above paths would be available to it, with properties in the first path in the list taking priority over the others.
Sharing Configuration With All Applications -
+Sharing configuration between all applications varies according to which approach you take, as described in the following topics: + + + + + + + + +
File Based Repositories -With file-based (i.e. git, svn and native) repositories, resources -with file names in application* are shared between all client -applications (so application.properties, application.yml, -application-*.properties etc.). You can use resources with these -file names to configure global defaults and have them overridden by -application-specific files as necessary. -The #_property_overrides[property overrides] feature can also be used -for setting global defaults, and with placeholders applications are +With file-based (git, svn, and native) repositories, resources with file names in application* (application.properties, application.yml, application-*.properties, and so on) are shared between all client applications. +You can use resources with these file names to configure global defaults and have them be overridden by application-specific files as necessary. +The #_property_overrides[property overrides] feature can also be used for setting global defaults, with placeholders applications allowed to override them locally. -With the "native" profile (local file system backend) it is -recommended that you use an explicit search location that isn’t part -of the server’s own configuration. Otherwise the application* -resources in the default search locations are removed because they are -part of the server. +With the “native” profile (a local file system backend) , you should use an explicit search location that is not part of the server’s own configuration. +Otherwise, the application* resources in the default search locations get removed because they are part of the server.
-
+
Vault Server -When using Vault as a backend you can share configuration with -all applications by placing configuration in -secret/application. For example, if you run this Vault command +When using Vault as a backend, you can share configuration with all applications by placing configuration in secret/application. +For example, if you run the following Vault command, all applications using the config server will have the properties foo and baz available to them: $ vault write secret/application foo=bar baz=bam -All applications using the config server will have the properties -foo and baz available to them.
JDBC Backend -Spring Cloud Config Server supports JDBC (relation database) as a -backend for configuration properties. You can enable this feature by -adding spring-jdbc to the classpath, and using the "jdbc" profile, -or by adding a bean of type JdbcEnvironmentRepository. Spring Boot -will configure a data source if you include the right dependencies on -the classpath (see the user guide for more details on that). -The database needs to have a table called "PROPERTIES" with columns -"APPLICATION", "PROFILE", "LABEL" (with the usual Environment -meaning), plus "KEY" and "VALUE" for the key and value pairs in -Properties style. All fields are of type String in Java, so you can -make them VARCHAR of whatever length you need. Property values -behave in the same way as they would if they came from Spring Boot -properties files named {application}-{profile}.properties, including -all the encryption and decryption, which will be applied as -post-processing steps (i.e. not in the repository implementation -directly). +Spring Cloud Config Server supports JDBC (relational database) as a backend for configuration properties. +You can enable this feature by adding spring-jdbc to the classpath and using the jdbc profile or by adding a bean of type JdbcEnvironmentRepository. +If you include the right dependencies on the classpath (see the user guide for more details on that), Spring Boot configures a data source. +The database needs to have a table called PROPERTIES with columns called APPLICATION, PROFILE, and LABEL (with the usual Environment meaning), plus KEY and VALUE for the key and value pairs in Properties style. +All fields are of type String in Java, so you can make them VARCHAR of whatever length you need. +Property values behave in the same way as they would if they came from Spring Boot properties files named {application}-{profile}.properties, including all the encryption and decryption, which will be applied as post-processing steps (that is, not in the repository implementation directly).
Composite Environment Repositories -In some scenarios you may wish to pull configuration data from multiple -environment repositories. To do this you can just enable -multiple profiles in your config server’s application properties or YAML file. -If, for example, you want to pull configuration data from a Git repository -as well as a SVN repository you would set the following properties for your -configuration server. +In some scenarios, you may wish to pull configuration data from multiple environment repositories. +To do so, you can enable multiple profiles in your config server’s application properties or YAML file. +If, for example, you want to pull configuration data from a Git repository as well as an SVN repository, you can set the following properties for your configuration server: spring: profiles: active: git, svn @@ -861,74 +729,58 @@ configuration server. git: uri: file:///path/to/git/repo order: 1 -In addition to each repo specifying a URI, you can also specify an order property. -The order property allows you to specify the priority order for all your repositories. -The lower the numerical value of the order property the higher priority it will have. -The priority order of a repository will help resolve any potential conflicts between -repositories that contain values for the same properties. +In addition to each repository specifying a URI, you can also specify an order property. +The order property lets you specify the priority order for all your repositories. +The lower the numerical value of the order property, the higher priority it has. +The priority order of a repository helps resolve any potential conflicts between repositories that contain values for the same properties. -Any type of failure when retrieving values from an environment repositoy -will result in a failure for the entire composite environment. +Any type of failure when retrieving values from an environment repository results in a failure for the entire composite environment. -When using a composite environment it is important that all repos contain -the same label(s). If you have an environment similar to the one above and you request -configuration data with the label master but the SVN -repo does not contain a branch called master the entire request will fail. +When using a composite environment, it is important that all repositories contain the same labels. +If you have an environment similar to the one in the preceding example and you request configuration data with the master label but the SVN repository does not contain a branch called master, the entire request fails.
Custom Composite Environment Repositories -It is also possible to provide your own EnvironmentRepository bean -to be included as part of a composite environment in addition to -using one of the environment repositories from Spring Cloud. To do this your bean -must implement the EnvironmentRepository interface. If you would like to control -the priority of you custom EnvironmentRepository within the composite -environment you should also implement the Ordered interface and override the -getOrdered method. If you do not implement the Ordered interface then your -EnvironmentRepository will be given the lowest priority. +In addition to using one of the environment repositories from Spring Cloud, you can also provide your own EnvironmentRepository bean to be included as part of a composite environment. +To do so, your bean must implement the EnvironmentRepository interface. +If you want to control the priority of your custom EnvironmentRepository within the composite environment, you should also implement the Ordered interface and override the getOrdered method. +If you do not implement the Ordered interface, your EnvironmentRepository is given the lowest priority.
Property Overrides -The Config Server has an "overrides" feature that allows the operator -to provide configuration properties to all applications that cannot be -accidentally changed by the application using the normal Spring Boot -hooks. To declare overrides just add a map of name-value pairs to -spring.cloud.config.server.overrides. For example +The Config Server has an “overrides” feature that lets the operator provide configuration properties to all applications. +The overridden properties cannot be accidentally changed by the application with the normal Spring Boot hooks. +To declare overrides, add a map of name-value pairs to spring.cloud.config.server.overrides, as shown in the following example: spring: cloud: config: server: overrides: foo: bar -will cause all applications that are config clients to read foo=bar -independent of their own configuration. (Of course an application can -use the data in the Config Server in any way it likes, so overrides -are not enforceable, but they do provide useful default behaviour if -they are Spring Cloud Config clients.) +The preceding examples causes all applications that are config clients to read foo=bar, independent of their own configuration. + +A configuration system cannot force an application to use configuration data in any particular way. +Consequently, overrides are not enforceable. +However, they do provide useful default behavior for Spring Cloud Config clients. + -Normal, Spring environment placeholders with "${}" can be escaped -(and resolved on the client) by using backslash ("\") to escape the -"$" or the "{", e.g. \${app.foo:bar} resolves to "bar" unless the -app provides its own "app.foo". Note that in YAML you don’t need to -escape the backslash itself, but in properties files you do, when you -configure the overrides on the server. +Normally, Spring environment placeholders with ${} can be escaped (and resolved on the client) by using backslash (\) to escape the $ or the {. +For example, \${app.foo:bar} resolves to bar, unless the app provides its own app.foo. -You can change the priority of all overrides in the client to be more -like default values, allowing applications to supply their own values -in environment variables or System properties, by setting the flag -spring.cloud.config.overrideNone=true (default is false) in the -remote repository. + +In YAML, you do not need to escape the backslash itself. +However, in properties files, you do need to escape the backslash, when you configure the overrides on the server. + +You can change the priority of all overrides in the client to be more like default values, letting applications supply their own values in environment variables or System properties, by setting the spring.cloud.config.overrideNone=true flag (the default is false) in the remote repository.
Health Indicator -Config Server comes with a Health Indicator that checks if the configured -EnvironmentRepository is working. By default it asks the EnvironmentRepository -for an application named app, the default profile and the default -label provided by the EnvironmentRepository implementation. -You can configure the Health Indicator to check more applications -along with custom profiles and custom labels, e.g. +Config Server comes with a Health Indicator that checks whether the configured EnvironmentRepository is working. +By default, it asks the EnvironmentRepository for an application named app, the default profile, and the default label provided by the EnvironmentRepository implementation. +You can configure the Health Indicator to check more applications along with custom profiles and custom labels, as shown in the following example: spring: cloud: config: @@ -944,39 +796,21 @@ along with custom profiles and custom labels, e.g.
Security -You are free to secure your Config Server in any way that makes sense -to you (from physical network security to OAuth2 bearer -tokens), and Spring Security and Spring Boot make it easy to do pretty -much anything. -To use the default Spring Boot configured HTTP Basic security, just -include Spring Security on the classpath (e.g. through -spring-boot-starter-security). The default is a username of "user" -and a randomly generated password, which isn’t going to be very useful -in practice, so we recommend you configure the password (via -spring.security.user.password) and encrypt it (see below for instructions -on how to do that). +You can secure your Config Server in any way that makes sense to you (from physical network security to OAuth2 bearer tokens), because Spring Security and Spring Boot offer support for many security arrangements. +To use the default Spring Boot-configured HTTP Basic security, include Spring Security on the classpath (for example, through spring-boot-starter-security). +The default is a username of user and a randomly generated password. A random password is not useful in practice, so we recommend you configure the password (by setting spring.security.user.password) and encrypt it (see below for instructions on how to do that).
Encryption and Decryption -Prerequisites: to use the encryption and decryption features -you need the full-strength JCE installed in your JVM (it’s not there by default). -You can download the "Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files" -from Oracle, and follow instructions for installation (essentially replace the 2 policy files -in the JRE lib/security directory with the ones that you downloaded). +To use the encryption and decryption features you need the full-strength JCE installed in your JVM (it is not included by default). +You can download the “Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files” from Oracle and follow the installation instructions (essentially, you need to replace the two policy files in the JRE lib/security directory with the ones that you downloaded). -If the remote property sources contain encrypted content (values -starting with {cipher}) they will be decrypted before sending to -clients over HTTP. The main advantage of this set up is that the -property values don’t have to be in plain text when they are "at rest" -(e.g. in a git repository). If a value cannot be decrypted it is -removed from the property source and an additional property is added -with the same key, but prefixed with "invalid." and a value that means -"not applicable" (usually "<n/a>"). This is largely to prevent cipher -text being used as a password and accidentally leaking. -If you are setting up a remote config repository for config client -applications it might contain an application.yml like this, for -instance: +If the remote property sources contain encrypted content (values starting with {cipher}), they are decrypted before sending to clients over HTTP. +The main advantage of this setup is that the property values need not be in plain text when they are “at rest” (for example, in a git repository). +If a value cannot be decrypted, it is removed from the property source and an additional property is added with the same key but prefixed with invalid and a value that means “not applicable” (usually <n/a>). +This is largely to prevent cipher text being used as a password and accidentally leaking. +If you set up a remote config repository for config client applications, it might contain an application.yml similar to the following: application.yml @@ -986,7 +820,7 @@ instance: password: '{cipher}FKSAJDFGYOS8F7GLHAKERGFHLSAJ' -Encrypted values in a .properties file must not be wrapped in quotes, otherwise the value will not be decrypted: +Encrypted values in a .properties file must not be wrapped in quotes. Otherwise, the value is not decrypted. The following example shows values that would work: application.properties @@ -994,100 +828,93 @@ instance: spring.datasource.password: {cipher}FKSAJDFGYOS8F7GLHAKERGFHLSAJ -You can safely push this plain text to a shared git repository and the -secret password is protected. -The server also exposes /encrypt and /decrypt endpoints (on the -assumption that these will be secured and only accessed by authorized -agents). If you are editing a remote config file you can use the Config Server -to encrypt values by POSTing to the /encrypt endpoint, e.g. +You can safely push this plain text to a shared git repository, and the secret password remains protected. +The server also exposes /encrypt and /decrypt endpoints (on the assumption that these are secured and only accessed by authorized agents). +If you edit a remote config file, you can use the Config Server to encrypt values by POSTing to the /encrypt endpoint, as shown in the following example: $ curl localhost:8888/encrypt -d mysecret 682bc583f4641835fa2db009355293665d2647dade3375c0ee201de2a49f7bda -If the value you are encrypting has characters in it that need to be URL encoded you should use -the --data-urlencode option to curl to make sure they are encoded properly. +If the value you encrypt has characters in it that need to be URL encoded, you should use the --data-urlencode option to curl to make sure they are encoded properly. Be sure not to include any of the curl command statistics in the encrypted value. Outputting the value to a file can help avoid this problem. -The inverse operation is also available via /decrypt (provided the server is -configured with a symmetric key or a full key pair): +The inverse operation is also available through /decrypt (provided the server is +configured with a symmetric key or a full key pair), as shown in the following example: $ curl localhost:8888/decrypt -d 682bc583f4641835fa2db009355293665d2647dade3375c0ee201de2a49f7bda mysecret -If you are testing like this with curl, then use ---data-urlencode (instead of -d) or set an explicit Content-Type: -text/plain to make sure curl encodes the data correctly when there -are special characters ('+' is particularly tricky). +If you testing with curl, then use --data-urlencode (instead of -d) or set an explicit Content-Type: text/plain to make sure curl encodes the data correctly when there are special characters ('+' is particularly tricky). -Take the encrypted value and add the {cipher} prefix before you put -it in the YAML or properties file, and before you commit and push it -to a remote, potentially insecure store. -The /encrypt and /decrypt endpoints also both accept paths of the -form /*/{name}/{profiles} which can be used to control cryptography -per application (name) and profile when clients call into the main -Environment resource. +Take the encrypted value and add the {cipher} prefix before you put it in the YAML or properties file and before you commit and push it to a remote (potentially insecure) store. +The /encrypt and /decrypt endpoints also both accept paths in the form of /*/{name}/{profiles}, which can be used to control cryptography on a per-application (name) and per-profile basis when clients call into the main environment resource. -to control the cryptography in this granular way you must also -provide a @Bean of type TextEncryptorLocator that creates a -different encryptor per name and profiles. The one that is provided -by default does not do this (so all encryptions use the same key). +To control the cryptography in this granular way, you must also provide a @Bean of type TextEncryptorLocator that creates a different encryptor per name and profiles. +The one that is provided by default does not do so (all encryptions use the same key). The spring command line client (with Spring Cloud CLI extensions -installed) can also be used to encrypt and decrypt, e.g. +installed) can also be used to encrypt and decrypt, as shown in the following example: $ spring encrypt mysecret --key foo 682bc583f4641835fa2db009355293665d2647dade3375c0ee201de2a49f7bda $ spring decrypt --key foo 682bc583f4641835fa2db009355293665d2647dade3375c0ee201de2a49f7bda mysecret -To use a key in a file (e.g. an RSA public key for encryption) prepend -the key value with "@" and provide the file path, e.g. +To use a key in a file (such as an RSA public key for encryption), prepend +the key value with "@" and provide the file path, as shown in the following example: $ spring encrypt mysecret --key @${HOME}/.ssh/id_rsa.pub AQAjPgt3eFZQXwt8tsHAVv/QHiY5sI2dRcR+... -The key argument is mandatory (despite having a -- prefix). + +The --key argument is mandatory (despite having a -- prefix). +
Key Management -The Config Server can use a symmetric (shared) key or an asymmetric -one (RSA key pair). The asymmetric choice is superior in terms of -security, but it is often more convenient to use a symmetric key since -it is just a single property value to configure in the bootstrap.properties. -To configure a symmetric key you just need to set encrypt.key to a -secret String (or use an enviroment variable ENCRYPT_KEY to keep it -out of plain text configuration files). -To configure an asymmetric key you can either set the key as a -PEM-encoded text value (in encrypt.key), or via a keystore (e.g. as -created by the keytool utility that comes with the JDK). The -keystore properties are encrypt.keyStore.* with * equal to - - -location (a Resource location), - - -password (to unlock the keystore) and - - -alias (to identify which key in the store is to be -used). - - +The Config Server can use a symmetric (shared) key or an asymmetric one (RSA key pair). +The asymmetric choice is superior in terms of security, but it is often more convenient to use a symmetric key since it is a single property value to configure in the bootstrap.properties. +To configure a symmetric key, you need to set encrypt.key to a secret String (or use the ENCRYPT_KEY environment variable to keep it out of plain-text configuration files). +To configure an asymmetric key, you can either set the key as a PEM-encoded text value (in encrypt.key) or use a keystore (such as the keystore created by the keytool utility that comes with the JDK). +The following table describes the keystore properties: + + + + +
+ +Property +Description + + + + +encrypt.keyStore.location +Contains a Resource location + + +encrypt.keyStore.password +Holds the password that unlocks the keystore + + +encrypt.keyStore.alias +Identifies which key in the store to use + + + +The encryption is done with the public key, and a private key is -needed for decryption. Thus in principle you can configure only the -public key in the server if you only want to do encryption (and are -prepared to decrypt the values yourself locally with the private -key). In practice you might not want to do that because it spreads the -key management process around all the clients, instead of -concentrating it in the server. On the other hand it’s a useful option -if your config server really is relatively insecure and only a -handful of clients need the encrypted properties. +needed for decryption. +Thus, in principle, you can configure only the public key in the server if you want to only encrypt (and are prepared to decrypt the values yourself locally with the private key). +In practice, you might not want to do decrypt locally, because it spreads the key management process around all the clients, instead of +concentrating it in the server. +On the other hand, it can be a useful option if your config server is relatively insecure and only a handful of clients need the encrypted properties.
Creating a Key Store for Testing -To create a keystore for testing you can do something like this: +To create a keystore for testing, you can use a command resembling the following: $ keytool -genkeypair -alias mytestkey -keyalg RSA \ -dname "CN=Web Server,OU=Unit,O=Organization,L=City,S=State,C=US" \ -keypass changeme -keystore server.jks -storepass letmein -Put the server.jks file in the classpath (for instance) and then in -your bootstrap.yml for the Config Server: +Put the server.jks file in the classpath (for instance) and then, in +your bootstrap.yml, for the Config Server, create the following settings: encrypt: keyStore: location: classpath:/server.jks @@ -1097,97 +924,54 @@ your bootstrap.yml for the Config Server:
Using Multiple Keys and Key Rotation -In addition to the {cipher} prefix in encrypted property values, the -Config Server looks for {name:value} prefixes (zero or many) before -the start of the (Base64 encoded) cipher text. The keys are passed to -a TextEncryptorLocator which can do whatever logic it needs to -locate a TextEncryptor for the cipher. If you have configured a -keystore (encrypt.keystore.location) the default locator will look -for keys in the store with aliases as supplied by the "key" prefix, -i.e. with a cipher text like this: +In addition to the {cipher} prefix in encrypted property values, the Config Server looks for zero or more {name:value} prefixes before the start of the (Base64 encoded) cipher text. +The keys are passed to a TextEncryptorLocator, which can do whatever logic it needs to locate a TextEncryptor for the cipher. +If you have configured a keystore (encrypt.keystore.location), the default locator looks for keys with aliases supplied by the key prefix, with a cipher text like resembling the following: foo: bar: `{cipher}{key:testkey}...` -the locator will look for a key named "testkey". A secret can also be -supplied via a {secret:…​} value in the prefix, but if it is not -the default is to use the keystore password (which is what you get -when you build a keytore and don’t specify a secret). If you do -supply a secret it is recommended that you also encrypt the secrets -using a custom SecretLocator. -Key rotation is hardly ever necessary on cryptographic grounds if the -keys are only being used to encrypt a few bytes of configuration data -(i.e. they are not being used elsewhere), but occasionally you might -need to change the keys if there is a security breach for instance. In -that case all the clients would need to change their source config -files (e.g. in git) and use a new {key:…​} prefix in all the -ciphers, checking beforehand of course that the key alias is available -in the Config Server keystore. +The locator looks for a key named "testkey". +A secret can also be supplied by using a {secret:…​} value in the prefix. +However, if it is not supplied, the default is to use the keystore password (which is what you get when you build a keytore and do not specify a secret). +If you do supply a secret, you should also encrypt the secret using a custom SecretLocator. +When the keys are being used only to encrypt a few bytes of configuration data (that is, they are not being used elsewhere), key rotation is hardly ever necessary on cryptographic grounds. +However, you might occasionally need to change the keys (for example, in the event of a security breach). +In that case, all the clients would need to change their source config files (for example, in git) and use a new {key:…​} prefix in all the ciphers. +Note that the clients need to first check that the key alias is available in the Config Server keystore. -the {name:value} prefixes can also be added to plaintext posted -to the /encrypt endpoint, if you want to let the Config Server -handle all encryption as well as decryption. +If you want to let the Config Server handle all encryption as well as decryption, the {name:value} prefixes can also be added as plain text posted to the /encrypt endpoint, .
Serving Encrypted Properties -Sometimes you want the clients to decrypt the configuration locally, -instead of doing it in the server. In that case you can still have -/encrypt and /decrypt endpoints (if you provide the encrypt.* -configuration to locate a key), but you need to explicitly switch off -the decryption of outgoing properties using -spring.cloud.config.server.encrypt.enabled=false. If you don’t care -about the endpoints, then it should work if you configure neither the -key nor the enabled flag. +Sometimes you want the clients to decrypt the configuration locally, instead of doing it in the server. +In that case, if you provide the encrypt.* configuration to locate a key, you can still have /encrypt and /decrypt endpoints, but you need to explicitly switch off the decryption of outgoing properties by setting spring.cloud.config.server.encrypt.enabled=false. +If you do not care about the endpoints, it should work if you do not configure either the key or the enabled flag.
Serving Alternative Formats -The default JSON format from the environment endpoints is perfect for -consumption by Spring applications because it maps directly onto the -Environment abstraction. If you prefer you can consume the same data -as YAML or Java properties by adding a suffix to the resource path -(".yml", ".yaml" or ".properties"). This can be useful for consumption -by applications that do not care about the structure of the JSON -endpoints, or the extra metadata they provide, for example an -application that is not using Spring might benefit from the simplicity -of this approach. -The YAML and properties representations have an additional flag -(provided as a boolean query parameter resolvePlaceholders) to -signal that placeholders in the source documents, in the standard -Spring ${…​} form, should be resolved in the output where possible -before rendering. This is a useful feature for consumers that don’t -know about the Spring placeholder conventions. +The default JSON format from the environment endpoints is perfect for consumption by Spring applications, because it maps directly onto the Environment abstraction. +If you prefer, you can consume the same data as YAML or Java properties by adding a suffix (".yml", ".yaml" or ".properties") to the resource path. +This can be useful for consumption by applications that do not care about the structure of the JSON endpoints or the extra metadata they provide (for example, an application that is not using Spring might benefit from the simplicity of this approach). +The YAML and properties representations have an additional flag (provided as a boolean query parameter called resolvePlaceholders) to signal that placeholders in the source documents (in the standard Spring ${…​} form) should be resolved in the output before rendering, where possible. +This is a useful feature for consumers that do not know about the Spring placeholder conventions. -there are limitations in using the YAML or properties formats, -mainly in relation to the loss of metadata. The JSON is structured as -an ordered list of property sources, for example, with names that -correlate with the source. The YAML and properties forms are coalesced -into a single map, even if the origin of the values has multiple -sources, and the names of the original source files are lost. The YAML -representation is not necessarily a faithful representation of the -YAML source in a backing repository either: it is constructed from a -list of flat property sources, and assumptions have to be made about -the form of the keys. +There are limitations in using the YAML or properties formats, mainly in relation to the loss of metadata. +For example, the JSON is structured as an ordered list of property sources, with names that correlate with the source. +The YAML and properties forms are coalesced into a single map, even if the origin of the values has multiple sources, and the names of the original source files are lost. +Also, the YAML representation is not necessarily a faithful representation of the YAML source in a backing repository either. It is constructed from a list of flat property sources, and assumptions have to be made about the form of the keys. Serving Plain Text -Instead of using the Environment abstraction (or one of the -alternative representations of it in YAML or properties format) your -applications might need generic plain text configuration files, -tailored to their environment. The Config Server provides these -through an additional endpoint at /{name}/{profile}/{label}/{path} -where "name", "profile" and "label" have the same meaning as the -regular environment endpoint, but "path" is a file name -(e.g. log.xml). The source files for this endpoint are located in -the same way as for the environment endpoints: the same search path is -used as for properties or YAML files, but instead of aggregating all -matching resources, only the first one to match is returned. -After a resource is located, placeholders in the normal format -(${…​}) are resolved using the effective Environment for the -application name, profile and label supplied. In this way the resource -endpoint is tightly integrated with the environment -endpoints. Example, if you have this layout for a GIT (or SVN) -repository: +Instead of using the Environment abstraction (or one of the alternative representations of it in YAML or properties format), your applications might need generic plain-text configuration files that are tailored to their environment. +The Config Server provides these through an additional endpoint at /{name}/{profile}/{label}/{path}, where name, profile, and label have the same meaning as the regular environment endpoint, but path is a file name (such as log.xml). +The source files for this endpoint are located in the same way as for the environment endpoints. +The same search path is used for properties and YAML files. +However, instead of aggregating all matching resources, only the first one to match is returned. +After a resource is located, placeholders in the normal format (${…​}) are resolved by using the effective Environment for the supplied application name, profile, and label. +In this way, the resource endpoint is tightly integrated with the environment endpoints. +Consider the following example for a GIT or SVN repository: application.yml nginx.conf where nginx.conf looks like this: @@ -1205,7 +989,7 @@ spring: nginx: server: name: develop.com -then the /foo/default/master/nginx.conf resource looks like this: +The /foo/default/master/nginx.conf resource might be as follows: server { listen 80; server_name example.com; @@ -1216,127 +1000,78 @@ nginx: server_name develop.com; } -Just like the source files for environment configuration, the -"profile" is used to resolve the file name, so if you want a -profile-specific file then /*/development/*/logback.xml will be -resolved by a file called logback-development.xml (in preference -to logback.xml). +As with the source files for environment configuration, the profile is used to resolve the file name. +So, if you want a profile-specific file, /*/development/*/logback.xml can be resolved by a file called logback-development.xml (in preference to logback.xml). -If you do not want to supply the label and let the server use the default label, you can supply a useDefaultLabel request parameter. So, the above example for the default profile could look like /foo/default/nginx.conf?useDefaultLabel. +If you do not want to supply the label and let the server use the default label, you can supply a useDefaultLabel request parameter. +So, the preceding example for the default profile could be /foo/default/nginx.conf?useDefaultLabel. Embedding the Config Server -The Config Server runs best as a standalone application, but if you -need to you can embed it in another application. Just use the -@EnableConfigServer annotation. An optional property that can be -useful in this case is spring.cloud.config.server.bootstrap which is -a flag to indicate that the server should configure itself from its -own remote repository. The flag is off by default because it can delay -startup, but when embedded in another application it makes sense to -initialize the same way as any other application. +The Config Server runs best as a standalone application. +However, if need be, you can embed it in another application. +To do so, use the @EnableConfigServer annotation. +An optional property named spring.cloud.config.server.bootstrap can be useful in this case is. +It is a flag to indicate whether the server should configure itself from its own remote repository. +By default, the flag is off, because it can delay startup. +However, when embedded in another application, it makes sense to initialize the same way as any other application. -It should be obvious, but remember that if you use the bootstrap -flag the config server will need to have its name and repository URI -configured in bootstrap.yml. +If you use the bootstrap flag, the config server needs to have its name and repository URI configured in bootstrap.yml. -To change the location of the server endpoints you can (optionally) -set spring.cloud.config.server.prefix, e.g. "/config", to serve the -resources under a prefix. The prefix should start but not end with a -"/". It is applied to the @RequestMappings in the Config Server -(i.e. underneath the Spring Boot prefixes server.servletPath and -server.contextPath). -If you want to read the configuration for an application directly from -the backend repository (instead of from the config server) that’s -basically an embedded config server with no endpoints. You can switch -off the endpoints entirely if you don’t use the @EnableConfigServer -annotation (just set spring.cloud.config.server.bootstrap=true). +To change the location of the server endpoints, you can (optionally) set spring.cloud.config.server.prefix (for example, /config), to serve the resources under a prefix. +The prefix should start but not end with a /. +It is applied to the @RequestMappings in the Config Server (that is, underneath the Spring Boot server.servletPath and server.contextPath prefixes). +If you want to read the configuration for an application directly from the backend repository (instead of from the config server), you +basically wat an embedded config server with no endpoints. +You can switch off the endpoints entirely by not using the @EnableConfigServer annotation (set spring.cloud.config.server.bootstrap=true). Push Notifications and Spring Cloud Bus -Many source code repository providers (like Github, Gitlab, Gitee or Bitbucket -for instance) will notify you of changes in a repository through a -webhook. You can configure the webhook via the provider’s user -interface as a URL and a set of events in which you are -interested. For instance -Github -will POST to the webhook with a JSON body containing a list of -commits, and a header "X-Github-Event" equal to "push". If you add a -dependency on the spring-cloud-config-monitor library and activate -the Spring Cloud Bus in your Config Server, then a "/monitor" endpoint -is enabled. -When the webhook is activated the Config Server will send a -RefreshRemoteApplicationEvent targeted at the applications it thinks -might have changed. The change detection can be strategized, but by -default it just looks for changes in files that match the application -name (e.g. "foo.properties" is targeted at the "foo" application, and -"application.properties" is targeted at all applications). The strategy -if you want to override the behaviour is PropertyPathNotificationExtractor -which accepts the request headers and body as parameters and returns a list -of file paths that changed. -The default configuration works out of the box with Github, Gitlab, Gitee or -Bitbucket. In addition to the JSON notifications from Github, Gitlab, Gitee -or Bitbucket you can trigger a change notification by POSTing to -"/monitor" with a form-encoded body parameters path={name}. This will -broadcast to applications matching the "{name}" pattern (can contain -wildcards). +Many source code repository providers (such as Github, Gitlab, Gitee, or Bitbucket) notify you of changes in a repository through a webhook. +You can configure the webhook through the provider’s user interface as a URL and a set of events in which you are interested. +For instance, Github uses a POST to the webhook with a JSON body containing a list of commits and a header (X-Github-Event) set to push. +If you add a dependency on the spring-cloud-config-monitor library and activate the Spring Cloud Bus in your Config Server, then a /monitor endpoint is enabled. +When the webhook is activated, the Config Server sends a RefreshRemoteApplicationEvent targeted at the applications it thinks might have changed. +The change detection can be strategized. +However, by default, it looks for changes in files that match the application name (for example, foo.properties is targeted at the foo application, while application.properties is targeted at all applications). +The strategy to use when you want to override the behavior is PropertyPathNotificationExtractor, which accepts the request headers and body as parameters and returns a list of file paths that changed. +The default configuration works out of the box with Github, Gitlab, Gitee, or Bitbucket. +In addition to the JSON notifications from Github, Gitlab, Gitee, or Bitbucket, you can trigger a change notification by POSTing to /monitor with form-encoded body parameters in the pattern of path={name}. +Doing so broadcasts to applications matching the {name} pattern (which can contain wildcards). -the RefreshRemoteApplicationEvent will only be transmitted if -the spring-cloud-bus is activated in the Config Server and in the -client application. +The RefreshRemoteApplicationEvent is transmitted only if the spring-cloud-bus is activated in both the Config Server and in the client application. -the default configuration also detects filesystem changes in -local git repositories (the webhook is not used in that case but as -soon as you edit a config file a refresh will be broadcast). +The default configuration also detects filesystem changes in local git repositories. In that case, the webhook is not used. However, as soon as you edit a config file, a refresh is broadcast. Spring Cloud Config Client -A Spring Boot application can take immediate advantage of the Spring -Config Server (or other external property sources provided by the -application developer), and it will also pick up some additional -useful features related to Environment change events. +A Spring Boot application can take immediate advantage of the Spring Config Server (or other external property sources provided by the application developer). +It also picks up some additional useful features related to Environment change events.
Config First Bootstrap -This is the default behaviour for any application which has the Spring -Cloud Config Client on the classpath. When a config client starts up -it binds to the Config Server (via the bootstrap configuration -property spring.cloud.config.uri) and initializes Spring -Environment with remote property sources. -The net result of this is that all client apps that want to consume -the Config Server need a bootstrap.yml (or an environment variable) -with the server address in spring.cloud.config.uri (defaults to -"http://localhost:8888"). +The default behavior for any application that has the Spring Cloud Config Client on the classpath is as follows: +When a config client starts, it binds to the Config Server (through the spring.cloud.config.uri bootstrap configuration property) and initializes Spring Environment with remote property sources. +The net result of this behavior is that all client applciations that want to consume the Config Server need a bootstrap.yml (or an environment variable) with the server address set in spring.cloud.config.uri (it defaults to "http://localhost:8888").
Discovery First Bootstrap -If you are using a `DiscoveryClient implementation, such as Spring Cloud Netflix -and Eureka Service Discovery or Spring Cloud Consul (Spring Cloud Zookeeper does -not support this yet), then you can have the Config Server register with the -Discovery Service if you want to, but in the default "Config First" mode, -clients won’t be able to take advantage of the registration. -If you prefer to use DiscoveryClient to locate the Config Server, you can do -that by setting spring.cloud.config.discovery.enabled=true (default -"false"). The net result of that is that client apps all need a -bootstrap.yml (or an environment variable) with the appropriate discovery -configuration. For example, with Spring Cloud Netflix, you need to define the -Eureka server address, e.g. in eureka.client.serviceUrl.defaultZone. The -price for using this option is an extra network round trip on start up to -locate the service registration. The benefit is that the Config Server -can change its co-ordinates, as long as the Discovery Service is a fixed point. The -default service id is "configserver" but you can change that on the -client with spring.cloud.config.discovery.serviceId (and on the server -in the usual way for a service, e.g. by setting spring.application.name). -The discovery client implementations all support some kind of metadata -map (e.g. for Eureka we have eureka.instance.metadataMap). Some -additional properties of the Config Server may need to be configured -in its service registration metadata so that clients can connect -correctly. If the Config Server is secured with HTTP Basic you can -configure the credentials as "username" and "password". And if the -Config Server has a context path you can set "configPath". Example, -for a Config Server that is a Eureka client: +If you use a `DiscoveryClient implementation, such as Spring Cloud Netflix and Eureka Service Discovery or Spring Cloud Consul, you can have the Config Server register with the Discovery Service. +However, in the default “Config First” mode, clients cannot take advantage of the registration. +If you prefer to use DiscoveryClient to locate the Config Server, you can do so by setting spring.cloud.config.discovery.enabled=true (the default is false). +The net result of doing so is that client applications all need a bootstrap.yml (or an environment variable) with the appropriate discovery configuration. +For example, with Spring Cloud Netflix, you need to define the Eureka server address (for example, in eureka.client.serviceUrl.defaultZone). +The price for using this option is an extra network round trip on startup, to locate the service registration. +The benefit is that, as long as the Discovery Service is a fixed point, the Config Server can change its coordinates. +The default service ID is configserver, but you can change that on the client by setting spring.cloud.config.discovery.serviceId (and on the server, in the usual way for a service, such as by setting spring.application.name). +The discovery client implementations all support some kind of metadata map (for example, we have eureka.instance.metadataMap for Eureka). +Some additional properties of the Config Server may need to be configured in its service registration metadata so that clients can connect correctly. +If the Config Server is secured with HTTP Basic, you can configure the credentials as username and password. +Also, if the Config Server has a context path, you can set configPath. +For example, the following YAML file is for a Config Server that is a Eureka client: bootstrap.yml @@ -1352,30 +1087,24 @@ for a Config Server that is a Eureka client:
Config Client Fail Fast -In some cases, it may be desirable to fail startup of a service if -it cannot connect to the Config Server. If this is the desired -behavior, set the bootstrap configuration property -spring.cloud.config.fail-fast=true and the client will halt with -an Exception. +In some cases, you may want to fail startup of a service if it cannot connect to the Config Server. +If this is the desired behavior, set the bootstrap configuration property spring.cloud.config.fail-fast=true to make the client halt with an Exception.
Config Client Retry -If you expect that the config server may occasionally be unavailable when -your app starts, you can ask it to keep trying after a failure. First you need -to set spring.cloud.config.fail-fast=true, and then you need to add -spring-retry and spring-boot-starter-aop to your classpath. The default -behaviour is to retry 6 times with an initial backoff interval of 1000ms and an -exponential multiplier of 1.1 for subsequent backoffs. You can configure these -properties (and others) using spring.cloud.config.retry.* configuration properties. +If you expect that the config server may occasionally be unavailable when your application starts, you can make it keep trying after a failure. +First, you need to set spring.cloud.config.fail-fast=true. +Then you need to add spring-retry and spring-boot-starter-aop to your classpath. +The default behavior is to retry six times with an initial backoff interval of 1000ms and an exponential multiplier of 1.1 for subsequent backoffs. +You can configure these properties (and others) by setting the spring.cloud.config.retry.* configuration properties. -To take full control of the retry add a @Bean of type -RetryOperationsInterceptor with id "configServerRetryInterceptor". Spring -Retry has a RetryInterceptorBuilder that makes it easy to create one. +To take full control of the retry behavior, add a @Bean of type RetryOperationsInterceptor with an ID of configServerRetryInterceptor. +Spring Retry has a RetryInterceptorBuilder that supports creating one.
Locating Remote Configuration Resources -The Config Service serves property sources from /{name}/{profile}/{label}, where the default bindings in the client app are +The Config Service serves property sources from /{name}/{profile}/{label}, where the default bindings in the client app are as follows: "name" = ${spring.application.name} @@ -1387,22 +1116,18 @@ Retry has a RetryInterceptorBuilder that makes it easy to cre "label" = "master" -All of them can be overridden by setting spring.cloud.config.* -(where * is "name", "profile" or "label"). The "label" is useful for -rolling back to previous versions of configuration; with the default -Config Server implementation it can be a git label, branch name or -commit id. Label can also be provided as a comma-separated list, in -which case the items in the list are tried on-by-one until one succeeds. -This can be useful when working on a feature branch, for instance, -when you might want to align the config label with your branch, but -make it optional (e.g. spring.cloud.config.label=myfeature,develop). +You can override all of them by setting spring.cloud.config.* (where * is name, profile or label). +The label is useful for rolling back to previous versions of configuration. +With the default Config Server implementation, it can be a git label, branch name, or commit ID. +Label can also be provided as a comma-separated list. +In that case, the items in the list are tried one by one until one succeeds. +This behavior can be useful when working on a feature branch. +For instance, you might want to align the config label with your branch but make it optional (in that case, use spring.cloud.config.label=myfeature,develop).
Security -If you use HTTP Basic security on the server then clients just need to -know the password (and username if it isn’t the default). You can do -that via the config server URI, or via separate username and password -properties, e.g. +If you use HTTP Basic security on the server, clients need to know the password (and username if it is not the default). +You can specify the username and password through the config server URI or via separate username and password properties, as shown in the following example: bootstrap.yml @@ -1412,7 +1137,7 @@ properties, e.g. uri: https://user:secret@myconfig.mycompany.com -or +The following example shows an alternate way to pass the same information: bootstrap.yml @@ -1424,13 +1149,9 @@ properties, e.g. password: secret -The spring.cloud.config.password and spring.cloud.config.username -values override anything that is provided in the URI. -If you deploy your apps on Cloud Foundry then the best way to provide -the password is through service credentials, e.g. in the URI, since -then it doesn’t even need to be in a config file. An example which -works locally and for a user-provided service on Cloud Foundry named -"configserver": +The spring.cloud.config.password and spring.cloud.config.username values override anything that is provided in the URI. +If you deploy your apps on Cloud Foundry, the best way to provide the password is through service credentials (such as in the URI, since it does not need to be in a config file). +The following example works locally and for a user-provided service on Cloud Foundry named configserver: bootstrap.yml @@ -1440,22 +1161,23 @@ works locally and for a user-provided service on Cloud Foundry named uri: ${vcap.services.configserver.credentials.uri:http://user:password@localhost:8888} -If you use another form of security you might need to provide a -RestTemplate to the ConfigServicePropertySourceLocator (e.g. by -grabbing it in the bootstrap context and injecting one). +If you use another form of security, you might need to provide a RestTemplate to the ConfigServicePropertySourceLocator (for example, by grabbing it in the bootstrap context and injecting it).
Health Indicator -The Config Client supplies a Spring Boot Health Indicator that attempts to load configuration from Config Server. The health indicator can be disabled by setting health.config.enabled=false. The response is also cached for performance reasons. The default cache time to live is 5 minutes. To change that value set the health.config.time-to-live property (in milliseconds). +The Config Client supplies a Spring Boot Health Indicator that attempts to load configuration from the Config Server. +The health indicator can be disabled by setting health.config.enabled=false. +The response is also cached for performance reasons. +The default cache time to live is 5 minutes. +To change that value, set the health.config.time-to-live property (in milliseconds).
Providing A Custom RestTemplate -In some cases you might need to customize the requests made to the config server from -the client. Typically this involves passing special Authorization headers to -authenticate requests to the server. To provide a custom RestTemplate follow the -steps below. +In some cases, you might need to customize the requests made to the config server from the client. +Typically, doing so involves passing special Authorization headers to authenticate requests to the server. +To provide a custom RestTemplate: -Create a new configuration bean with an implementation of PropertySourceLocator. +Create a new configuration bean with an implementation of PropertySourceLocator, as shown in the following example: @@ -1475,8 +1197,8 @@ public class CustomConfigServiceBootstrapConfiguration { -In resources/META-INF create a file called -spring.factories and specify your custom configuration. +In resources/META-INF, create a file called +spring.factories and specify your custom configuration, as shown in the following example: @@ -1488,10 +1210,9 @@ public class CustomConfigServiceBootstrapConfiguration {
Vault -When using Vault as a backend to your config server the client will need to -supply a token for the server to retrieve values from Vault. This token -can be provided within the client by setting spring.cloud.config.token -in bootstrap.yml. +When using Vault as a backend to your config server, the client needs to supply a token for the server to retrieve values from Vault. +This token can be provided within the client by setting spring.cloud.config.token +in bootstrap.yml, as shown in the following example: bootstrap.yml @@ -1503,18 +1224,15 @@ in bootstrap.yml.
-
-Vault
Nested Keys In Vault -Vault supports the ability to nest keys in a value stored in Vault. For example +Vault supports the ability to nest keys in a value stored in Vault, as shown in the following example: echo -n '{"appA": {"secret": "appAsecret"}, "bar": "baz"}' | vault write secret/myapp - -This command will write a JSON object to your Vault. To access these values in Spring -you would use the traditional dot(.) annotation. For example +This command writes a JSON object to your Vault. +To access these values in Spring, you would use the traditional dot(.) annotation, as shown in the following example @Value("${appA.secret}") String name = "World"; -The above code would set the name variable to appAsecret. -
+The preceding code would sets the value of the name variable to appAsecret.
\ No newline at end of file