I have created an API in AWS Gateway which uses AWS Lambda. The Lambda uses a python script. I can use the API gateway to invoke the Lambda which can power on or off RDS clusters. In my AWS account I have 4 RDS clusters. If all 4 are powered off I can use the API to power them all on at once If all 4 are powered on I can use the API to power them all off at once
However the issue Im having is that if one of the clusters is powered on but the other 3 arent, my script wont power the other 3 on as it tells me that one cluster is not in the correct state (its already powered on)
The same if one cluster is already powered off and I want to power off everything else, my script again fails as one of the clusters is already powered off
I get this error
[ERROR] InvalidDBClusterStateFault: An error occurred (InvalidDBClusterStateFault) when calling the StartDBCluster operation: DbCluster cluster name is not in stopped
Here is my script that can power off or on if everything is either off or on. Can anyone tell me what I should add that could resolve my issue? Basically I’m trying to add to my script that if the status is available the script will shutdown the cluster and if stopped it starts it. ‘Method’ is the parameter I use for my api. Basically the api has an invoke URL which I can edit to have Method=StopAll or Method=StartAll
def handler(event, context): response = rds_client.describe_db_clusters( MaxRecords=100 ) allClusters = [] allClusters.append(response['DBClusters']) while 'Marker' in response: old_marker = response['Marker'] response = rds_client.describe_db_clusters( MaxRecords=100, Marker = old_marker ) allClusters.append(response['DBClusters']) if event['Method'] == "StopAll": for cluster in allClusters: for key in cluster: rds_client.stop_db_cluster( DBClusterIdentifier=key['DBClusterIdentifier'] ) if event['Method'] == "StartAll": for cluster in allClusters: for key in cluster: rds_client.start_db_cluster( DBClusterIdentifier=key['DBClusterIdentifier'] )```
Advertisement
Answer
Whenever you call start_db_cluster
or stop_db_cluster
you can wrap in a try/except so that, even if one call fails, it will still attempt to make the rest:
try: rds_client.start_db_cluster(DBClusterIdentifier=cluster_id) except rds_client.exceptions.InvalidDBClusterStateFault: print(f"Cluster {cluster_id} in invalid state") except Exception as e: print(f"Error updating cluster {cluster_id}: {repr(e)}")