View a markdown version of this page

Amazon MWAA 環境上的 Aurora PostgreSQL 資料庫清除 - Amazon Managed Workflows for Apache Airflow

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

Amazon MWAA 環境上的 Aurora PostgreSQL 資料庫清除

Amazon Managed Workflows for Apache Airflow 使用 Aurora PostgreSQL 資料庫做為 Apache Airflow 中繼資料資料庫,其中存放 DAG 執行和任務執行個體。下列範例程式碼會定期從 Amazon MWAA 環境的專用 Aurora PostgreSQL 資料庫清除項目。

重要

Apache Airflow v3 會限制任務程式碼的直接中繼資料資料庫存取。工作者不再連線到中繼資料資料庫,而且 DAG 或任務程式碼無法直接匯入或使用 Apache Airflow 資料庫工作階段或模型。此變更可改善安全性和可擴展性。不過,適用於 Apache Airflow v2 的 DAG 資料庫清除方法無法在 Apache Airflow v3 環境中運作。

反之,透過 airflow db clean Amazon MWAA CLI 端點使用 CLI 命令來執行中繼資料資料庫清除。

注意

隨著時間的推移,中繼資料資料庫會累積舊記錄、XCom 資料和過時的任務資料。此成長使用資料庫連線、減緩您的環境,以及延遲任務。執行定期中繼資料清除,以防止這些問題。

版本

此頁面上的程式碼範例專屬於 Amazon MWAA 上支援的 Apache Airflow v2 和 v3。請參閱支援的 Apache Airflow 版本

先決條件

若要使用此頁面上的範例程式碼,您需要下列項目:

相依性

若要搭配 Apache Airflow v2 使用此程式碼範例,不需要額外的相依性。使用 aws-mwaa-docker-images 來安裝 Apache Airflow。

範例程式碼

下列範例示範如何清除 Amazon MWAA 環境上的中繼資料資料庫。

Apache Airflow v3.0.6 to 3.2.1
重要考量
  • 您必須指定 --clean-before-timestamp來控制清除的進度。使用 ISO 8601 格式的時間戳記 (例如 2025-01-01T00:00:00+00:00)。

  • 建議您指定 --tables,將清除限制為特定資料表。如果省略,命令會清除所有支援的資料表。

  • 從較小的範圍開始 — 首先使用較舊--clean-before-timestamp的值 (更接近您的環境建立日期) 和單一資料表。這會將清除限制為僅最舊的記錄。由於 命令會在指定的時間戳記之前刪除所有項目,因此使用較新的時間戳記會導致較大的刪除範圍。隨著您對程序的信心逐漸向前移動時間戳記。

  • 大規模清除可能會影響資料庫效能。刪除大量記錄會對 Aurora PostgreSQL 資料庫造成壓力,並可能影響環境的回應能力。使用 --batch-size 參數控制交易大小,並考慮在低流量期間執行清除。在生產環境中執行時請小心。

相依資料表行為

當您使用 指定資料表時--tables,命令會自動包含與指定資料表具有外部索引鍵關係的任何相依 (子) 資料表。首先刪除子資料表記錄,然後刪除父資料表記錄,以滿足外部金鑰限制。例如,指定 --tables dag_run也會清除 task_instancetask_instance_historytask_state_store、 和 xcomdeadline因為這些資料表dag_run會參考外部索引鍵。

下表摘要說明相依性鏈。

指定的資料表 清理其他資料表 (依存項目)
dag_run task_instance, task_instance_history, xcom, task_state_store, deadline
dag dag_version, deadline
task_instance task_instance_history, xcom
trigger task_instance, task_instance_history, xcom
dag_version task_instance, task_instance_history, xcom, dag_run

沒有相依性的資料表 (例如 logjobimport_errorsla_miss) 會在指定時單獨清理。

使用 --dry-run 來確切查看哪些資料表和有多少資料列會受到影響,然後再進行清除。

的可用參數 airflow db clean

下表說明 的可用參數airflow db clean

參數 描述 預設
--clean-before-timestamp (必要) 清除資料之前的日期或時間戳記。如果未提供時區,則會假設 Apache Airflow 預設時區。範例:2025-01-01T00:00:00+00:00
--tables-t 要在 上執行維護的資料表名稱 (逗號分隔)。選項包括:dag_runtask_instancetask_instance_historylogjobxcomimport_errortask_rescheduletriggerdag、、dag_version、、sla_misscallback_requestcelery_taskmetacelery_tasksetmetaasset_event、、deadline、、 revoked_token task_state_store connection_test_request _xcom_archive
--batch-size 在單一交易中刪除或封存的資料列數目上限。較低的值可減少長時間執行的鎖定,但會增加批次數。
--dry-run 執行試轉而不實際刪除資料。建議用於初始測試。 False
--skip-archive 請勿在封存資料表中保留清除的記錄。根據預設, 會將清除的記錄db clean移至封存資料表 (以_<table>_archive慣例命名,例如 _dag_run_archive),而不是永久刪除它們。這可提供安全網路 — 您可以檢查封存的資料、使用 匯出資料airflow db export-archived,或稍後使用 將其捨棄airflow db drop-archived。設定 --skip-archive 時,記錄會在沒有此中繼步驟的情況下永久刪除。 False
--dag-ids 僅清除與指定 DAG IDs 相關的資料。
--exclude-dag-ids 避免清除與指定 DAG IDs 相關的資料。
-y, --yes 略過確認提示。透過 Amazon MWAA 執行非互動式 CLI 時需要。 False
-v, --verbose 讓記錄輸出更為詳細。 False

如需可用參數的詳細資訊,請參閱 Apache Airflow 網站上的 CLI 和 env 變數參考

程式碼範例

下列範例示範如何airflow db clean透過 Amazon MWAA CLI 端點叫用 。如需建立 CLI 字符的詳細資訊,請參閱 建立 Apache Airflow CLI 字符

使用 Python 指令碼:

import boto3 import base64 import requests # Replace with your environment name and AWS Region mwaa_env_name = "YOUR_ENVIRONMENT_NAME" region = "YOUR_REGION" # Configure cleanup scope clean_before_timestamp = "2025-06-01T00:00:00+00:00" tables = "dag_run,task_instance,log,job,xcom" # Build the Airflow CLI command # -y flag is required to skip interactive confirmation prompt airflow_cmd = f"db clean --clean-before-timestamp {clean_before_timestamp} --tables {tables} -y" # Create a CLI token client = boto3.client("mwaa", region_name=region) cli_token_response = client.create_cli_token(Name=mwaa_env_name) cli_token = cli_token_response["CliToken"] web_server_hostname = cli_token_response["WebServerHostname"] # Invoke the Airflow CLI through the MWAA endpoint url = f"https://{web_server_hostname}/aws_mwaa/cli" response = requests.post( url, headers={ "Authorization": f"Bearer {cli_token}", "Content-Type": "text/plain", }, data=airflow_cmd, ) # Parse and display the results stdout_message = base64.b64decode(response.json()["stdout"]).decode("utf-8") stderr_message = base64.b64decode(response.json()["stderr"]).decode("utf-8") print(f"Status code: {response.status_code}") print(f"stdout:\n{stdout_message}") print(f"stderr:\n{stderr_message}")
乾執行範例 (建議的第一個步驟)

在執行實際清除之前,請使用 執行 --dry-run 以查看要刪除的內容:

AIRFLOW_CMD="db clean --clean-before-timestamp 2025-06-01T00:00:00+00:00 --tables dag_run,task_instance --dry-run -y"
Apache Airflow v2.7.2 to 2.11.2
from airflow import DAG from airflow.models.param import Param from airflow.operators.bash_operator import BashOperator from airflow.utils.dates import days_ago from datetime import datetime, timedelta # Note: Database commands might time out if running longer than 5 minutes. If this occurs, please increase the MAX_AGE_IN_DAYS (or change # timestamp parameter to an earlier date) for initial runs, then reduce on subsequent runs until the desired retention is met. MAX_AGE_IN_DAYS = 30 # To clean specific tables, please provide a comma-separated list per # https://airflow.apache.org/docs/apache-airflow/stable/cli-and-env-variables-ref.html#clean # A value of None will clean all tables TABLES_TO_CLEAN = None with DAG( dag_id="clean_db_dag", schedule_interval=None, catchup=False, start_date=days_ago(1), params={ "timestamp": Param( default=(datetime.now()-timedelta(days=MAX_AGE_IN_DAYS)).strftime("%Y-%m-%d %H:%M:%S"), type="string", minLength=1, maxLength=255, ), } ) as dag: if TABLES_TO_CLEAN: bash_command="airflow db clean --clean-before-timestamp '{{ params.timestamp }}' --tables '"+TABLES_TO_CLEAN+"' --skip-archive --yes" else: bash_command="airflow db clean --clean-before-timestamp '{{ params.timestamp }}' --skip-archive --yes" cli_command = BashOperator( task_id="bash_command", bash_command=bash_command )