跳至內容

如何停止 Aurora 叢集超過七天?

3 分的閱讀內容
0

我想知道如何停止 Amazon Aurora 叢集超過七天。

解決方法

設定 IAM 權限

建立下列 AWS 身分與 Access Management (IAM) 政策,以允許 AWS Lambda 從叢集啟動、停止和擷取資訊:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "VisualEditor0",
      "Effect": "Allow",
      "Action": [
        "rds:StartDBCluster",
        "rds:StopDBCluster",
        "rds:ListTagsForResource",
        "rds:DescribeDBInstances",
        "rds:StopDBInstance",
        "rds:DescribeDBClusters",
        "rds:StartDBInstance"
      ],
      "Resource": "*"
    }
  ]
}

注意: 對所有資源使用萬用字元 (**\ ***),或指定叢集的 Amazon Resource Name (ARN)。

建立 IAM 角色並附加必要的 IAM 政策

使用 IAM 主控台來建立 IAM 角色並附加必要的政策。在 Service or use case (服務或使用案例) 中,選擇 Lambda。權限政策請選取 AWSLambdaBasicExecutionRole 政策,然後選取您建立的政策。

將標籤新增至資料庫叢集

使用 Amazon Relational Databases (Amazon RDS) 主控台將兩個標籤新增至您的資料庫叢集。在 Key (金鑰) 中輸入 autostart,然後在 Value (值) 中輸入 yes。選擇 Add another Tag (新增另一個標籤),然後在 Key (金鑰) 中輸入 autostop,在 Value (值) 中輸入 yes

建立 Lambda 函式以啟動和停止資料庫叢集

若要建立 Lambda 函式以啟動叢集,請完成下列步驟:

  1. 開啟 Lambda 主控台
  2. 在導覽窗格中,選擇 Functions (函式)。
  3. 選擇 Create function (建立函式)。
  4. 選擇 Author from scratch (從頭開始撰寫)。
  5. Function name (函式名稱) 中,輸入函式名稱。
  6. Runtime (執行時期) 請選擇 Python 3.13
  7. 針對 Architecture (架構),請保留預設選取的 x86_64
  8. 展開 Change default execution role (變更預設執行角色)。
  9. Execution role (執行角色) 請選擇 Use an existing role (使用現有角色)。
  10. Existing role (現有角色) 請選取您的 IAM 角色。
  11. 選擇 Create function (建立函式)。
  12. 選擇 Code (程式碼) 索引標籤。
  13. Code source (程式碼來源) 編輯器中,刪除範例並輸入下列程式碼:
import boto3
rds = boto3.client('rds')

def lambda_handler(event, context):
    #Start DB clusters
    dbs = rds.describe_db_clusters()
    for db in dbs['DBClusters']:
        #Check if DB cluster stopped. Start it if eligible.
        if (db['Status'] == 'stopped'):
            try:
                GetTags = rds.list_tags_for_resource(ResourceName=db['DBClusterArn'])['TagList']
                for tags in GetTags:
                    #if tag "autostart=yes" is set for cluster, start it
                    if(tags['Key'] == 'autostart' and tags['Value'] == 'yes'):
                        result = rds.start_db_cluster(DBClusterIdentifier=db['DBClusterIdentifier'])
                        print("Starting cluster: {0}.".format(db['DBClusterIdentifier']))
            except Exception as e:
                print("Cannot start cluster {0}.".format(db['DBClusterIdentifier']))
                print(e)

if __name__ == "__main__":
    lambda_handler(None, None)
  1. 選擇 Deploy (部署)。
  2. 選擇 Configuration (組態) 索引標籤,然後選擇 Edit (編輯)。
  3. 針對 Timeout (逾時),min (分鐘) 請選擇 0sec (秒) 請選擇 10
  4. 選擇 Save (儲存)。

若要建立 Lambda 函式來停止叢集,請重複上述步驟。在 Code source (程式碼來源) 編輯器中輸入下列程式碼:

import boto3
rds = boto3.client('rds')

def lambda_handler(event, context):
    #Stop DB clusters
    dbs = rds.describe_db_clusters()
    for db in dbs['DBClusters']:
        #Check if DB cluster started. Stop it if eligible.
        if (db['Status'] == 'available'):
            try:
                GetTags = rds.list_tags_for_resource(ResourceName=db['DBClusterArn'])['TagList']
                for tags in GetTags:
                #if tag "autostop=yes" is set for cluster, stop it
                    if(tags['Key'] == 'autostop' and tags['Value'] == 'yes'):
                        result = rds.stop_db_cluster(DBClusterIdentifier=db['DBClusterIdentifier'])
                        print ("Stopping cluster: {0}.".format(db['DBClusterIdentifier']))
            except Exception as e:
                print ("Cannot stop cluster {0}.".format(db['DBClusterIdentifier']))
                print(e)


if __name__ == "__main__":
    lambda_handler(None, None)

測試您的函式

在測試您的函式之前,請先停止您的資料庫叢集。然後,使用 Lambda 主控台調用您的函式。針對 Edit saved event (編輯已儲存的事件),選取您的事件。

建立自動啟動和停止資料庫叢集的排程

您可以使用 Amazon EventBridge 排程器建立排程,在維護時段前後的指定時間啟動和停止您的叢集。針對 Schedule type (排程類型),請選擇 Cron-based schedule (以 Cron 為基礎的排程),然後輸入 Cron 表達式。

相關資訊

如何使用 Lambda 函式停止 Amazon RDS 執行個體超過七天?

AWS 官方已更新 10 個月前