This is an issue regardless of the IDE used. When you set the privateKey as an environment variable which is what will typically be done in a production environment, the key validation fails and you get the error .. is not a valid private key.
I got around this in the following manner.
- Just pass in the main content of the key in the environment variable. So for example, if the private key is :
-----BEGIN RSA PRIVATE KEY-----
{keyContent}
-----END RSA PRIVATE KEY-----
and the environment variable is githubKey
, the value of githubKey
is keyContent
.
2. Add a EnvironmentPostProcessor implementation in your code to transform the content inside githubKey
to the properly formatted private key and store this formatted value in a new property formattedGithubKey
@Component
public class GithubKeyProcessor implements EnvironmentPostProcessor {
private static final String START_PK = "-----BEGIN RSA PRIVATE KEY-----";
private static final String END_PK = "-----END RSA PRIVATE KEY-----";
private static final String LINE_BREAK = "\n";
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment,
SpringApplication application) {
String githubKey = environment.getProperty("githubKey");
Map<String, Object> formattedGithubKeyProperties = new HashMap<>();
formattedGithubKeyProperties.put("formattedGithubKey", formatKey(githubKey));
environment.getPropertySources()
.addLast(new MapPropertySource("formattedGithubKeyProperties", formattedGithubKeyProperties));
System.out.println("Done transforming githubKey to the correct format");
}
private String formatKey(String theSshKey) {
if (theSshKey.indexOf(LINE_BREAK) < 0) {
String tmpKey = theSshKey.replace(START_PK, "").replace(END_PK, "").trim();
return START_PK + LINE_BREAK + tmpKey.replaceAll(" ", LINE_BREAK) + LINE_BREAK + END_PK;
} else {
return theSshKey;
}
}
}
Note that this environment processor has to be registered inside the src/main/resources/META-INF/spring.factories file whose content looks like this:
org.springframework.boot.env.EnvironmentPostProcessor={package}.GithubKeyProcessor
- In the application yml file, use this new property for the private key.
spring:
cloud:
config:
server:
git:
private-key: ${formattedGithubKey}
This should do the trick.