使用 lambda 函数停止多个 AWS RDS 实例

Stopping multiple AWS RDS instances using lambda function

我想使用 lambda 函数停止多个 RDS 实例。我使用的代码是:

import sys
import botocore
import boto3
from botocore.exceptions import ClientError
def lambda_handler(event, context):
   rds = boto3.client('rds')
   lambdaFunc = boto3.client('lambda')
   print('Trying to get Environment variable')
   try:
       funcResponse = lambdaFunc.get_function_configuration(
           FunctionName='lambdaStopRDS'
       )
       DBinstance = funcResponse['Environment']['Variables']['DBInstanceName']
       print('Stopping RDS service for DBInstance : ' + DBinstance)
   except ClientError as e:
       print(e)
   try:
       response = rds.stop_db_instance(
           DBInstanceIdentifier=DBinstance
       )
       print('Success :: ')
       return response
   except ClientError as e:
       print(e)
   return
   {
       'message' : "Script execution completed. See Cloudwatch logs for complete output"
   }

我正在添加以下环境变量:

Key: DBInstanceName Value: database-1, database-2

并出现以下错误:

Trying to get Environment variable
Stopping RDS service for DBInstance : database-1, database-2
An error occurred (InvalidParameterValue) when calling the StopDBInstance operation: Invalid database identifier:  database-1, database-2

在这里,Keys必须是唯一的,所以我不能添加另一个同名的key并添加另一个RDS。 有什么方法可以在没有标签的情况下停止同一 VPC/region 中的多个 RDS 实例?

stop_db_instance 只有一个 db id,而不是多个。但是,您正试图通过其中两个 database-1, database-2。所以你必须在循环中做。例如:

   try:

       db_ids = [v.strip() for v in DBinstance.split(',')] 

       for db_id in db_ids:
           response = rds.stop_db_instance(
               DBInstanceIdentifier=db_id
           )
           print('Success :: ')

       return response
   except ClientError as e:
       print(e)