

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

# 使用 AWS Secrets Manager 秘密設定 Apache Airflow 連線
<a name="connections-secrets-manager"></a>

AWS Secrets Manager 是 Amazon Managed Workflows for Apache Airflow 環境上支援的替代 Apache Airflow 後端。本主題說明如何使用 在 Amazon Managed Workflows for Apache Airflow 上 AWS Secrets Manager 安全地存放 Apache Airflow 變數和 Apache Airflow 連線的秘密。

**注意**  
您需要為您建立的秘密付費。如需 Secrets Manager 定價的詳細資訊，請參閱 [AWS 定價](https://aws.amazon.com/secrets-manager/pricing/)。
[AWS Systems Manager 參數存放區](https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-parameter-store)也支援做為 Amazon MWAA 中的秘密後端。如需詳細資訊，請參閱 [Amazon Provider Package 文件](https://airflow.apache.org/docs/apache-airflow-providers-amazon/stable/secrets-backends/aws-ssm-parameter-store.html)。

**Contents**
+ [步驟一：提供 Amazon MWAA 存取 Secrets Manager 私密金鑰的許可](#connections-sm-policy)
+ [步驟二：建立 Secrets Manager 後端做為 Apache Airflow 組態選項](#connections-sm-aa-configuration)
+ [步驟三：產生 Apache Airflow AWS 連線 URI 字串](#connections-sm-aa-uri)
+ [步驟四：在 Secrets Manager 中新增變數](#connections-sm-createsecret-variables)
+ [步驟五：在 Secrets Manager 中新增連線](#connections-sm-createsecret-connection)
+ [範本程式碼](#connections-sm-samples)
+ [Resources](#connections-sm-blogs)
+ [後續步驟？](#connections-sm-next-up)

## 步驟一：提供 Amazon MWAA 存取 Secrets Manager 私密金鑰的許可
<a name="connections-sm-policy"></a>

Amazon MWAA 環境的[執行角色](mwaa-create-role.md)需要秘密金鑰的讀取存取權 AWS Secrets Manager。下列 IAM 政策允許使用 AWS受管 [SecretsManagerReadWrite](https://console.aws.amazon.com/iam/home?#/policies/arn:aws:iam::aws:policy/SecretsManagerReadWrite$jsonEditor) 政策進行讀寫存取。

**將政策連接至您的執行角色**

1. 在 Amazon MWAA 主控台上開啟[環境](https://console.aws.amazon.com/mwaa/home#/environments)頁面。

1. 選擇環境。

1. 在**許可**窗格中選擇您的執行角色。

1. 選擇**連接政策**。

1. `SecretsManagerReadWrite` 在**篩選政策**文字欄位中輸入 。

1. 選擇**連接政策**。

如果您不想使用 AWS受管許可政策，您可以直接更新環境的執行角色，以允許任何層級的 Secrets Manager 資源存取權。例如，下列政策陳述式會授予您在 Secrets Manager 中特定 AWS 區域 中建立的所有秘密的讀取存取權。

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "secretsmanager:GetResourcePolicy",
                "secretsmanager:GetSecretValue",
                "secretsmanager:DescribeSecret",
                "secretsmanager:ListSecretVersionIds"
            ],
            "Resource": "arn:aws:secretsmanager:us-east-1:111122223333:secret:*"
        },
        {
            "Effect": "Allow",
            "Action": "secretsmanager:ListSecrets",
            "Resource": "*"
        }
    ]
}
```

------

## 步驟二：建立 Secrets Manager 後端做為 Apache Airflow 組態選項
<a name="connections-sm-aa-configuration"></a>

下一節說明如何在 AWS Secrets Manager 後端的 Amazon MWAA 主控台上建立 Apache Airflow 組態選項。如果您在 中使用相同名稱的組態設定`airflow.cfg`，則在下列步驟中建立的組態會優先並覆寫組態設定。

1. 在 Amazon MWAA 主控台上開啟[環境](https://console.aws.amazon.com/mwaa/home#/environments)頁面。

1. 選擇環境。

1. 選擇**編輯**。

1. 選擇**下一步**。

1. 在 Airflow **組態選項窗格中選擇新增自訂**組態。 ****新增下列鍵/值對：

   1. **`secrets.backend`**: **`airflow.providers.amazon.aws.secrets.secrets_manager.SecretsManagerBackend`**

   1. **`secrets.backend_kwargs`**：**`{"connections_prefix" : "airflow/connections", "variables_prefix" : "airflow/variables"}`**這會設定 Apache Airflow 在 和 `airflow/variables/*` 路徑搜尋連線字串`airflow/connections/*`和變數。

      您可以使用[查詢模式](https://airflow.apache.org/docs/apache-airflow-providers-amazon/stable/secrets-backends/aws-secrets-manager.html#optional-lookup)來減少 Amazon MWAA 代表您對 Secrets Manager 進行的 API 呼叫次數。如果您未指定查詢模式，Apache Airflow 會搜尋所設定後端中的所有連線和變數。透過指定模式，您可以縮小 Apache Airflow 搜尋的可能路徑。這可降低將 Secrets Manager 與 Amazon MWAA 搭配使用時的成本。

      若要指定查詢模式，請指定 `connections_lookup_pattern`和 `variables_lookup_pattern` 參數。這些參數接受 RegEx 字串做為輸入。例如，若要搜尋開頭為 的秘密`test`，請在 中輸入下列內容`secrets.backend_kwargs`：

      ```
      {
        "connections_prefix": "airflow/connections",
        "connections_lookup_pattern": "^test",
        "variables_prefix" : "airflow/variables",
        "variables_lookup_pattern": "^test"
      }
      ```
**注意**  
若要使用 `connections_lookup_pattern`和 `variables_lookup_pattern`，您必須安裝 7`apache-airflow-providers-amazon`.3.0 版或更新版本。如需將 的 provder pacakge 更新至較新版本的詳細資訊，請參閱 [限制條件檔案](connections-packages.md#connections-packages-constraints)。

1. 選擇**儲存**。

## 步驟三：產生 Apache Airflow AWS 連線 URI 字串
<a name="connections-sm-aa-uri"></a>

若要建立連線字串，請使用鍵盤上的「tab」鍵來縮排[連線](https://airflow.apache.org/docs/stable/howto/connection/index.html)物件中的鍵值對。我們也建議您在 shell 工作階段中為`extra`物件建立變數。下一節會逐步解說使用 [Apache Airflow 或 Python 指令碼為 Amazon MWAA 環境產生 Apache Airflow 連線 URI](https://airflow.apache.org/docs/apache-airflow/stable/howto/connection.html#generating-a-connection-uri) 字串的步驟。

------
#### [ Apache Airflow CLI ]

下列 shell 工作階段使用本機 Airflow CLI 來產生連線字串。如果您沒有安裝 CLI，建議您使用 Python 指令碼。

1. 開啟 Python shell 工作階段：

   ```
   python3
   ```

1. 輸入以下命令：

   ```
   >>> import json
   ```

1. 輸入以下命令：

   ```
   >>> from airflow.models.connection import Connection
   ```

1. 在`extra`物件的 shell 工作階段中建立變數。將 *YOUR\$1EXECUTION\$1ROLE\$1ARN* 中的範例值替換為執行角色 ARN，以及 *us-east-1* 中的區域 （例如 `us-east-1`)。

   ```
   >>> extra=json.dumps({'role_arn': 'YOUR_EXECUTION_ROLE_ARN', 'region_name': 'us-east-1'})
   ```

1. 建立連線物件。以 Apache Airflow 連線`myconn`的名稱取代 中的範例值。

   ```
   >>> myconn = Connection(
   ```

1. 使用鍵盤上的「tab」鍵來縮排連線物件中的下列每個鍵值對。以*紅色*取代範例值。

   1. 指定 AWS 連線類型：

      ```
      ... conn_id='aws',
      ```

   1. 指定 Apache Airflow 資料庫選項：

      ```
      ... conn_type='mysql',
      ```

   1. 在 Amazon MWAA 上指定 Apache Airflow UI URL：

      ```
      ... host='288888a0-50a0-888-9a88-1a111aaa0000.a1.us-east-1.airflow.amazonaws.com/home',
      ```

   1. 指定要登入 Amazon MWAA 的 AWS 存取金鑰 ID （使用者名稱）：

      ```
      ... login='YOUR_AWS_ACCESS_KEY_ID',
      ```

   1. 指定要登入 Amazon MWAA 的 AWS 私密存取金鑰 （密碼）：

      ```
      ... password='YOUR_AWS_SECRET_ACCESS_KEY',
      ```

   1. 指定 `extra` shell 工作階段變數：

      ```
      ... extra=extra
      ```

   1. 關閉連線物件。

      ```
      ... )
      ```

1. 列印連線 URI 字串：

   ```
   >>> myconn.get_uri()
   ```

   請參閱回應中的連線 URI 字串：

   ```
   'mysql://288888a0-50a0-888-9a88-1a111aaa0000.a1.us-east-1.airflow.amazonaws.com%2Fhome?role_arn=arn%3Aaws%3Aiam%3A%3A001122332255%3Arole%2Fservice-role%2FAmazonMWAA-MyAirflowEnvironment-iAaaaA&region_name=us-east-1'
   ```

------
#### [ Python script ]

下列 Python 指令碼不需要 Apache Airflow CLI。

1. 複製下列程式碼範例的內容，並在本機儲存為 `mwaa_connection.py`。

   ```
   import urllib.parse
   								
   								conn_type = 'YOUR_DB_OPTION'
   								host = 'YOUR_MWAA_AIRFLOW_UI_URL'
   								port = 'YOUR_PORT'
   								login = 'YOUR_AWS_ACCESS_KEY_ID'
   								password = 'YOUR_AWS_SECRET_ACCESS_KEY'
   								role_arn = urllib.parse.quote_plus('YOUR_EXECUTION_ROLE_ARN')
   								region_name = 'us-east-1'
   								
   								conn_string = '{0}://{1}:{2}@{3}:{4}?role_arn={5}&region_name={6}'.format(conn_type, login, password, host, port, role_arn, region_name)
   								print(conn_string)
   ```

1. 以*紅色*取代預留位置。

1. 執行下列指令碼來產生連線字串。

   ```
   python3 mwaa_connection.py
   ```

------

## 步驟四：在 Secrets Manager 中新增變數
<a name="connections-sm-createsecret-variables"></a>

下一節說明如何在 Secrets Manager 中建立變數的秘密。

**建立秘密**

1. 開啟 [AWS Secrets Manager 主控台](https://console.aws.amazon.com/secretsmanager/home#/environments)。

1. 選擇**儲存新機密**。

1. 選擇**其他類型的秘密**。

1. 在**指定要存放在此秘密窗格中的金鑰/值對上**，選擇**純文字**。

1. 以下列格式將變數值新增為**純文字**。

   ```
   "YOUR_VARIABLE_VALUE"
   ```

   例如，若要指定整數：

   ```
   14
   ```

   例如，若要指定字串：

   ```
   "mystring"
   ```

1. 對於**加密金鑰**，從下拉式清單中選擇 AWS KMS 金鑰選項。

1. 在**秘密**名稱的文字欄位中輸入名稱，格式如下。

   ```
   airflow/variables/YOUR_VARIABLE_NAME
   ```

   例如：

   ```
   airflow/variables/test-variable
   ```

1. 選擇**下一步**。

1. 在**設定秘密**頁面上的**秘密名稱和描述**窗格中，執行下列動作。

   1. 針對**秘密名稱**，請提供秘密的名稱。

   1. （選用） 針對**描述**，提供秘密的描述。

   選擇**下一步**。

1. 在**設定輪換 - 選用**中保留預設選項，然後選擇**下一步**。

1. 針對您要新增的任何其他變數，在 Secrets Manager 中重複這些步驟。

1. 在**檢閱**頁面上，檢閱您的秘密，然後選擇**儲存**。

## 步驟五：在 Secrets Manager 中新增連線
<a name="connections-sm-createsecret-connection"></a>

下一節說明如何在 Secrets Manager 中建立連線字串 URI 的秘密。

**建立秘密**

1. 開啟 [AWS Secrets Manager 主控台](https://console.aws.amazon.com/secretsmanager/home#/environments)。

1. 選擇**儲存新機密**。

1. 選擇**其他類型的秘密**。

1. 在**指定要存放在此秘密窗格中的金鑰/值對上**，選擇**純文字**。

1. 以下列格式將連線 URI 字串新增為**純文字**。

   ```
   YOUR_CONNECTION_URI_STRING
   ```

   例如：

   ```
   mysql://288888a0-50a0-888-9a88-1a111aaa0000.a1.us-east-1.airflow.amazonaws.com%2Fhome?role_arn=arn%3Aaws%3Aiam%3A%3A001122332255%3Arole%2Fservice-role%2FAmazonMWAA-MyAirflowEnvironment-iAaaaA&region_name=us-east-1
   ```
**警告**  
Apache Airflow 會剖析連線字串中的每個值。**您不得**使用單引號或雙引號，或將連線剖析為單一字串。

1. 對於**加密金鑰**，請從下拉式清單中選擇 AWS KMS 金鑰選項。

1. 在**秘密**名稱的文字欄位中輸入名稱，格式如下。

   ```
   airflow/connections/YOUR_CONNECTION_NAME
   ```

   例如：

   ```
   airflow/connections/myconn
   ```

1. 選擇**下一步**。

1. 在**設定秘密**頁面上的**秘密名稱和描述**窗格中，執行下列動作。

   1. 針對**秘密名稱**，請提供秘密的名稱。

   1. （選用） 針對**描述**，提供秘密的描述。

   選擇**下一步**。

1. 在**設定輪換 - 選用**保留預設選項，然後選擇**下一步**。

1. 針對您要新增的任何其他變數，在 Secrets Manager 中重複這些步驟。

1. 在**檢閱**頁面上，檢閱您的秘密，然後選擇**儲存**。

## 範本程式碼
<a name="connections-sm-samples"></a>
+ 了解如何使用位於 的範例程式碼，在此頁面上使用 Apache Airflow 連線 (`myconn`) 的私密金鑰[在 中使用私密金鑰 AWS Secrets Manager 進行 Apache Airflow 連線](samples-secrets-manager.md)。
+ 了解如何使用位於 的範例程式碼，在此頁面上使用 Apache Airflow 變數 (`test-variable`) 的私密金鑰[針對 AWS Secrets Manager Apache Airflow 變數在 中使用私密金鑰](samples-secrets-manager-var.md)。

## Resources
<a name="connections-sm-blogs"></a>
+ 如需使用主控台和 設定 Secrets Manager 秘密的詳細資訊 AWS CLI，請參閱*AWS Secrets Manager 《 使用者指南*》中的[建立秘密](https://docs.aws.amazon.com/secretsmanager/latest/userguide/create_secret.html)。
+ 使用 Python 指令碼將大量 Apache Airflow 變數和連線遷移至 Secrets Manager，並將[您的 Apache Airflow 連線和變數移至其中 AWS Secrets Manager](https://aws.amazon.com/blogs/opensource/move-apache-airflow-connections-variables-aws-secrets-manager/)。

## 後續步驟？
<a name="connections-sm-next-up"></a>
+ 了解如何在 中產生權杖以存取 Apache Airflow UI[存取 Apache Airflow](access-airflow-ui.md)。