

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

# 使用 IAM 身分驗證和 連線至資料庫叢集 適用於 Python (Boto3) 的 AWS SDK
<a name="UsingWithRDS.IAMDBAuth.Connecting.Python"></a>

您可以使用 連線到 Aurora MySQL 或 Aurora PostgreSQL 資料庫叢集 適用於 Python (Boto3) 的 AWS SDK ，如下所述。

**先決條件**  
以下是使用 IAM 身分驗證連線至資料庫叢集的先決條件：
+ [啟用和停用 IAM 資料庫身分驗證](UsingWithRDS.IAMDBAuth.Enabling.md)
+ [建立並使用 IAM 政策進行 IAM 資料庫存取](UsingWithRDS.IAMDBAuth.IAMPolicy.md)
+ [使用 IAM 身分驗證建立資料庫帳戶](UsingWithRDS.IAMDBAuth.DBAccounts.md)

此外，請確定範例程式碼中匯入的程式庫存在於您的系統上。

**範例**  
程式碼範例使用設定檔進行共用登入資料。如需指定登入資料的資訊，請參閱 適用於 Python (Boto3) 的 AWS SDK 文件中的[登入](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html)資料。

以下程式碼範例顯示如何產生身分驗證字符，然後用來連線至資料庫叢集。

若要執行此程式碼範例，您需要在 AWS 網站上[適用於 Python (Boto3) 的 AWS SDK](https://aws.amazon.com/sdk-for-python/)找到的 。

視需要修改下列變數的值：
+ `ENDPOINT` – 您想要存取之資料庫叢集的端點
+ `PORT` – 用於連線資料庫叢集的連接埠號碼
+ `USER` – 您想要存取的資料庫帳戶
+ `REGION` – 資料庫叢集執行所在的 AWS 區域
+ `DBNAME` – 您想要存取的資料庫
+ `SSLCERTIFICATE` – Amazon Aurora 之 SSL 憑證的完整路徑

  對於 `ssl_ca`，指定 SSL 憑證。若要下載 SSL 憑證，請參閱[使用 SSL/TLS 加密與資料庫叢集的連線](UsingWithRDS.SSL.md)。

**注意**  
您無法使用自訂 Route 53 DNS 記錄，替代資料庫叢集端點來產生身分驗證字符。

此程式碼連接到一個 Aurora MySQL 資料庫叢集。

在執行此程式碼之前，請遵循 [Python 套件索引](https://pypi.org/project/PyMySQL/)中的指示，來安裝 PyMySQL 驅動程式。

```
import pymysql
import sys
import boto3
import os

ENDPOINT="mysqlcluster.cluster-123456789012.us-east-1.rds.amazonaws.com"
PORT="3306"
USER="jane_doe"
REGION="us-east-1"
DBNAME="mydb"
os.environ['LIBMYSQL_ENABLE_CLEARTEXT_PLUGIN'] = '1'

#gets the credentials from .aws/credentials
session = boto3.Session(profile_name='default')
client = session.client('rds')

token = client.generate_db_auth_token(DBHostname=ENDPOINT, Port=PORT, DBUsername=USER, Region=REGION)

try:
    conn =  pymysql.connect(auth_plugin_map={'mysql_clear_password':None},host=ENDPOINT, user=USER, password=token, port=PORT, database=DBNAME, ssl_ca='SSLCERTIFICATE', ssl_verify_identity=True, ssl_verify_cert=True)
    cur = conn.cursor()
    cur.execute("""SELECT now()""")
    query_results = cur.fetchall()
    print(query_results)
except Exception as e:
    print("Database connection failed due to {}".format(e))
```

此程式碼連接到一個 Aurora PostgreSQL 資料庫叢集。

在執行此程式碼之前，請按照 [Psycopg 文件](https://pypi.org/project/psycopg2/)中的指示來安裝 `psycopg2`。

```
import psycopg2
import sys
import boto3
import os

ENDPOINT="postgresmycluster.cluster-123456789012.us-east-1.rds.amazonaws.com"
PORT="5432"
USER="jane_doe"
REGION="us-east-1"
DBNAME="mydb"

#gets the credentials from .aws/credentials
session = boto3.Session(profile_name='RDSCreds')
client = session.client('rds')

token = client.generate_db_auth_token(DBHostname=ENDPOINT, Port=PORT, DBUsername=USER, Region=REGION)

try:
    conn = psycopg2.connect(host=ENDPOINT, port=PORT, database=DBNAME, user=USER, password=token, sslrootcert="SSLCERTIFICATE")
    cur = conn.cursor()
    cur.execute("""SELECT now()""")
    query_results = cur.fetchall()
    print(query_results)
except Exception as e:
    print("Database connection failed due to {}".format(e))
```

如果要透過 Proxy 連線到資料庫叢集，請參閱 [使用 IAM 身分驗證連線至資料庫](rds-proxy-connecting.md#rds-proxy-connecting-iam)。