Sam Template
CopyDatabaseFunction:
Type: AWS::Serverless::Function
Properties:
PackageType: Image
Timeout: 120
Environment:
Variables:
FromDbSecretId: !Ref UserDbSecretArn
ToDbSecretId: !Ref InitTargetDbSecretArn
VpcConfig:
SecurityGroupIds:
- !Ref SecurityGroupId
SubnetIds: !Ref SubnetIds
Policies:
- AWSSecretsManagerGetSecretValuePolicy:
SecretArn: !Ref UserDbSecretArn
- AWSSecretsManagerGetSecretValuePolicy:
SecretArn: !Ref InitTargetDbSecretArn
Metadata:
Dockerfile: Dockerfile
DockerContext: ./container/copy_data
DockerTag: v1
Dockerfile
FROM public.ecr.aws/lambda/python:3.8
RUN yum install -y https://dev.mysql.com/get/mysql57-community-release-el7-11.noarch.rpm \
&& yum install -y mysql-community-client
RUN mkdir /work
COPY ./index.py ./index.py
CMD ["index.handler"]
Code
import os
import subprocess
import boto3
def get_secret(client, secret_id):
import ast
rds_response = client.get_secret_value(SecretId=secret_id)
return ast.literal_eval(rds_response['SecretString'])
def run(from_db_secret_id: str, to_db_secret_id: str):
print('start program')
client = boto3.client('secretsmanager')
from_db_setting = get_secret(client, from_db_secret_id)
to_db_setting = get_secret(client, to_db_secret_id)
dump_response = subprocess.Popen([
'mysqldump', 'fromdb',
'-u', from_db_setting['username'],
f"-p{from_db_setting['password']}",
'-h', from_db_setting['host'],
'-t'
], stdout=subprocess.PIPE)
subprocess.run([
'mysql', 'todb',
'-u', to_db_setting['username'],
f"-p{to_db_setting['password']}",
'-h', to_db_setting['host'],
], stdin=dump_response.stdout)
print('end program')
def handler(event, context):
run(os.environ['FromDbSecretId'], os.environ['ToDbSecretId'])