由于越来越多的客户对应数据安全的重视,目前阿里云RDS提供了备份策略,但是备份策略周期为每天的某一个时间,在日常云运维工作中,有客户提出需要每天在不同的时间节点多备份几次,此时web界面就不能满足此类在一天内多次备份的需求,但是想到了在阿里云web控制台通过手动点击创建备份,是可以在点击后触发创建备份的任务,想到可以利用api来实现,同时提交工单咨询了下,果然此类需求是需要api来做,故写了个调用python实例配合linux系统的crond服务来完成。
#!/bin/env python
# -*- coding:utf-8 -*-
# _author:kaliarch
from aliyunsdkcore import client
from aliyunsdkrds.request.v20140815 import CreateBackupRequest
import time
import os
import logging
class rdsOper():
def __init__(self,logger):
self.clentoper = client.AcsClient(‘LTAIhfXlcjyln****‘,‘Gwf****4K2ELmt76184o****gRfAso‘,‘cn-shanghai‘)
self.logger = logger
self.logger.info("------------------------start exec rds backup API log-------------")
def backup_instance(self):
# 设置参数
request = CreateBackupRequest.CreateBackupRequest()
request.set_accept_format(‘json‘)
request.add_query_param(‘DBInstanceId‘, ‘rm-uf6xv3**1x842y61y‘)
#如果为单库备份,可以添加DBName
# request.add_query_param(‘DBName‘, ‘mydb‘)
#BackupMethod为备份方式:Logical:逻辑备份,Physical:物理备份
request.add_query_param(‘BackupMethod‘, ‘Physical‘)
#BackupType为备份类型: Auto:自动计算是全量备份还是增量备份;FullBackup:全量备份。默认值为Auto。
request.add_query_param(‘BackupType‘, ‘Auto‘)
response = self.clentoper.do_action_with_exception(request)
self.logger.info("rdsbackup mission submission successful!")
self.logger.info(response)
print(response)
class Rds_Log:
def __init__(self,filename):
self.filename = filename
def createDir(self):
_LOGDIR = os.path.join(os.path.dirname(__file__), ‘rdsbackuplog‘)
print(_LOGDIR)
_TIME = time.strftime(‘%Y-%m-%d‘, time.gmtime()) + ‘-‘
_LOGNAME = _TIME + self.filename
print(_LOGNAME)
LOGFILENAME = os.path.join(_LOGDIR, _LOGNAME)
print(LOGFILENAME)
if not os.path.exists(_LOGDIR):
os.mkdir(_LOGDIR)
return LOGFILENAME
def createlogger(self,logfilename):
logger= logging.getLogger()
logger.setLevel(logging.INFO)
handler = logging.FileHandler(logfilename)
handler.setLevel(logging.INFO)
formater = logging.Formatter(‘%(asctime)s - %(name)s - %(levelname)s - %(message)s‘)
handler.setFormatter(formater)
logger.addHandler(handler)
return logger
if __name__ == "__main__":
glploger = Rds_Log(‘rdsbackup.log‘)
logfilename = glploger.createDir()
logger = glploger.createlogger(logfilename)
app = rdsOper(logger)
app.backup_instance()
在随便服务器上传代码安装好相关python的sdk后
制作定时任务
查看日志
查看后天有备份任务已经提交完成
举一反三,类似的可以参考阿里云rds的API完成其他需求,如何客户对应rds的备份频率很高的话,可以开通灾备实例,来完成异地的实时备份,如果横向扩展读写操作,可以开通多个只读实例来分摊数据库压力。
https://help.aliyun.com/document_detail/26272.html?spm=5176.doc26228.6.821.Ux0gk1
原文地址:http://blog.51cto.com/kaliarch/2124609