개발 이야기/개발 및 서비스
CDK / Secret Manager를 활용한 RDS 인증 저장/사용 방법
가온아
2022. 7. 18. 17:35
CDK로 RDS 생성 시 관리자 인증을 Secret Manager를 아래와 같이 설정하고 RDS 생성시 credential을 등록할 수 있습니다.
import * as rds from 'aws-cdk-lib/aws-rds';
import { Credentials, DatabaseInstance, DatabaseInstanceEngine, DatabaseSecret, MysqlEngineVersion } from 'aws-cdk-lib/aws-rds'
const vpc = new ec2.Vpc(this, _id);
const instanceIdentifier = 'mysql'
const credsSecretName = 'rds-pw'
# rds를 위한 credential을 생성
const creds = new rds.DatabaseSecret(this, 'rds-credentials', {
secretName: credsSecretName,
username: 'admin'
});
const cluster = new rds.ServerlessCluster(this, 'mysql-cluster', {
engine: rds.DatabaseClusterEngine.AURORA_MYSQL,
credentials: Credentials.fromSecret(creds), # 생성된 credential을 생성하는 rds에 적용
vpc
});
등록된 credential을 이용해 아래와 같이 rds로 접근할 수 있습니다.
import boto3
import json
import pymysql
import pymysqlpool
# pymysql에 전달할 rds config
rds_config = {
'host':YOUR_RDS_ENDPOINT,
'port':3306,
'user':'admin',
'password':'', # 이곳에 secret manager에서 가져온 pw값을 저장합니다.
'database':'mysql',
'autocommit':True,
'cursorclass':pymysql.cursors.DictCursor}
ssmClient = boto3.client('secretsmanager',
aws_access_key_id=YOUR_AWS_ACCESS_KEY_ID,
aws_secret_access_key=YOUR_AWS_SECRET_ACCESS_KEY,
region_name=YOUR_REGION)
# 저장된 비밀번호 값을 secret manager에서 읽어오기
try:
# secret manager on aws web console에서 'your_secret_id' 확인 가능
get_secret_value_response = ssmClient.get_secret_value(SecretId='your_secret_id')
if 'SecretString' in get_secret_value_response:
secret = get_secret_value_response['SecretString']
j = json.loads(secret)
rds_config['password'] = j['password']
print("password string:" + j['password'])
else:
decoded_binary_secret = base64.b64decode(get_secret_value_response['SecretBinary'])
print("password binary:" + decoded_binary_secret)
rds_config['password'] = decoded_binary_secret.password
except ClientError as e:
print(e)
rds_pool = pymysqlpool.ConnectionPool(size=2, maxsize=20, pre_create_num=2, **rds_config)
이상 secret manager를 활용하는 방법을 알아보았습니다. secret manager를 이용하면 rds 이외에도 다양한 서비스의 중요 데이터를 관리하는데 도움이 되므로 잘 활용하시기 바랍니다.
반응형