我在一个小脚本中使用
boto3
来更改 RDS 集群的主凭据。
问题是来自
describe_db_clusters
的 RDS 集群状态不是可靠的最新状态。在我发出 modify_db_cluster
(具体来说,我正在更新主密码)之后,describe_db_clusters
很有可能显示集群在进入“修改”状态之前仍然“可用”。
事件发生顺序:
问题是我无法可靠地区分状态 3 和 5。
备注:
ApplyImmediately=True
进行主密码更新PendingModifiedValues
文档确实提到了这一点
describe_db_instances
:
主用户密码(字符串)-- 主用户的新密码。密码可以包含除“/”、“””或“@”之外的任何可打印 ASCII 字符。 更改此参数不会导致中断,并且会尽快异步应用更改。 在请求时间和请求完成之间,MasterUserPassword 元素存在于操作响应的 PendingModifiedValues 元素中。
但是,
describe_db_clusters
不存在该脚注。
我怎样才能可靠地知道我的修改操作何时完成?
显然,只有当有待处理的更改时,
PendingModifiedValues
才会出现在describe_db_clusters
响应中:
#!/usr/bin/python3
import boto3
import time
import datetime
client = boto3.client('rds',region_name='ap-southeast-2')
while True:
response = client.describe_db_clusters(
Filters=[
{
'Name': 'db-cluster-id',
'Values': [
'database-1',
]
}
]
)
for cluster in response['DBClusters']:
print(cluster['DBClusterIdentifier'],cluster['Status'])
if "PendingModifiedValues" in cluster:
print(cluster['PendingModifiedValues'])
else:
print('No PendingModifiedValues in response')
now = datetime.datetime.now()
print(now.strftime("%Y-%m-%d %H:%M:%S"))
time.sleep(1)
输出:
$ ./check_rds_cluster.py
database-1 available
No PendingModifiedValues in response
2021-03-28 13:19:45
database-1 available
No PendingModifiedValues in response
2021-03-28 13:19:46
database-1 available
No PendingModifiedValues in response
2021-03-28 13:19:48
database-1 available
{'MasterUserPassword': '****'}
2021-03-28 13:19:49
...
database-1 available
{'MasterUserPassword': '****'}
2021-03-28 13:19:53
database-1 available
{'MasterUserPassword': '****'}
2021-03-28 13:19:55
database-1 resetting-master-credentials
{'MasterUserPassword': '****'}
2021-03-28 13:19:56
database-1 resetting-master-credentials
{'MasterUserPassword': '****'}
...
2021-03-28 13:21:17
database-1 available
No PendingModifiedValues in response
2021-03-28 13:21:18
database-1 available
No PendingModifiedValues in response
2021-03-28 13:21:19
它记录在https://docs.aws.amazon.com/AmazonRDS/latest/APIReference/API_DBCluster.html:
待修改值
指定对数据库进行更改的值 集群正在等待处理。仅当发生更改时才包含此元素 待办的。具体更改由子元素标识。
在这种情况下,您可以在代码中创建一个 waiter 函数。 boto3 RDS 已经提供了几个“waiters”,但没有一个适用于集群。最接近的是 DBInstanceAvailable。 基本上,服务员是一个函数,它
以 15 秒的延迟迭代拉动 AWS API,以检查给定资源是否处于所需状态,例如RDS实例已创建并可供使用。因此,您可以创建自己的服务员
,它将每隔 10 或 15 秒拉动describe_db_clusters
,直到 PendingModifiedValues
不再响应或出现其他感兴趣的状态。也许检查
DBClusters
的
Status
就足够了。我就是这样做的。
while self.get_db_cluster_status() == "available":
time.sleep(5)
logging.getLogger().info(
f"waiting for cluster change to begin '{self.cluster_name}'"
)
waiter = self.rds.get_waiter("db_cluster_available")
waiter.wait(DBClusterIdentifier=self.cluster_name)