Last active
August 14, 2018 09:58
-
-
Save davidrosenstark/fa8680aa1e1f9d7e48b46269c55f6f29 to your computer and use it in GitHub Desktop.
PropertyPlaceholderConfigurer for reading from AWS Parameter Store
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.amazonaws.auth.AWSCredentialsProvider; | |
import org.springframework.beans.BeansException; | |
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; | |
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer; | |
import java.util.Map; | |
import java.util.Properties; | |
/** | |
* Class for reading properties from AWS Parameter Store and allowing spring to inject them in the | |
* environment. Requires two environment variables or to provide the variables in constructor: | |
* env -- which is used as the path in parameters store - e.g. - ci | |
* env.region -- which region the paramters are in (due to bug we have seen where region not taken from profile | |
*/ | |
public class SSMEncryptedPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer { | |
private String environment; | |
private String environmentRegion; | |
public SSMEncryptedPropertyPlaceholderConfigurer(String environment, String region) { | |
this.environment = environment; | |
this.environmentRegion = region; | |
} | |
public SSMEncryptedPropertyPlaceholderConfigurer() { | |
environment = System.getProperty("env"); | |
environmentRegion = System.getProperty("env.region"); | |
} | |
@Override | |
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { | |
if (environment == null || environmentRegion == null) { | |
throw new RuntimeException("no env or region property provided"); | |
} | |
AWSCredentialsProvider awsCredentialsProvider = beanFactory.getBean(AWSCredentialsProvider.class); | |
//at the point this function is created, the beans have been created but we have no Autowiring and | |
//also propeties have not been injected (obviously since we are doing that). So, here we manually | |
///create SSM Client and inject dependencies manually and call the PostConstruct function as well | |
SSMClient ssmClient = new SSMClient(awsCredentialsProvider, environmentRegion); | |
ssmClient.init(); | |
Map<String, String> parametersByPrefix = ssmClient.getParametersByPath("/" + environment, true); | |
Properties props = new Properties(); | |
props.putAll(parametersByPrefix); | |
setProperties(props); | |
super.postProcessBeanFactory(beanFactory); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment