Skill/spring

java aws secretManager사용법

진열사랑 2024. 10. 22. 12:28

masterClass=net.sf.log4jdbc.sql.jdbcapi.DriverSpy
masterSecName=arn:aws:secretsmanager:ap-northeast-2:095592723414:secret:....
masterRegName=ap-northeast-...

getPassword(masterClass, masterSecName, masterRegName);

public String getValue(AWSSecretsManager secretsClient, String secretName) {
String secret, decodedBinarySecret;
GetSecretValueRequest getSecretValueRequest = new GetSecretValueRequest()
.withSecretId(secretName);
GetSecretValueResult getSecretValueResult = null;

try {
getSecretValueResult = secretsClient.getSecretValue(getSecretValueRequest);
secret = getSecretValueResult.getSecretString();
} catch (Exception e) {
logger.error("Exception = " + e.getMessage());
}

if (getSecretValueResult.getSecretString() != null) {
secret = getSecretValueResult.getSecretString();
return secret;
}
else {
decodedBinarySecret = new String(Base64.getDecoder().decode(getSecretValueResult.getSecretBinary()).array());
return decodedBinarySecret;
}
}

DataSource getPassword(String className, String secName, String regName) {
AWSSecretsManager client = AWSSecretsManagerClientBuilder.standard()
.withRegion(regName)
.build();
String jsonStr = getValue(client, secName);
try {
JSONParser parser = new JSONParser();
Object obj = parser.parse(jsonStr);
JSONObject jsonObj = (JSONObject) obj;
//String password = (String) jsonObj.get("password");
jdbcUrl = "jdbc:log4jdbc:postgresql://" + (String) jsonObj.get("host") + ":" + (String) jsonObj.get("port") + "/" + (String) jsonObj.get("dbname");
username = (String) jsonObj.get("username");
password = (String) jsonObj.get("password");
return DataSourceBuilder
.create()
.username((String) jsonObj.get("username"))
.password((String) jsonObj.get("password"))
.url("jdbc:log4jdbc:postgresql://" + (String) jsonObj.get("host") + ":" + (String) jsonObj.get("port") + "/" + (String) jsonObj.get("dbname"))
.driverClassName(className)
.build();
} catch (ParseException e) {
// TODO Auto-generated catch block
}
return null;
}