

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

# Amazon ElastiCache 的資料安全性
<a name="encryption"></a>

為了協助保護您的資料安全，Amazon ElastiCache 和 Amazon EC2 提供保護您伺服器上的資料不受未授權存取的機制。

Amazon ElastiCache for Memcached 為執行 Memcached 1.6.12 版或更新版本的快取上的資料提供加密功能。

Amazon ElastiCache 搭配 Valkey 和 Redis OSS 為執行 Valkey 7.2 或更新版本的快取以及 Redis OSS 3.2.6 版 （針對 EOL 排程，請參閱 [Redis OSS 版本生命週期結束排程](engine-versions.md#deprecated-engine-versions))、4.0.10 或更新版本上的資料提供加密功能。Amazon ElastiCache 也支援使用 IAM 或 Valkey 和 Redis OSS AUTH 驗證使用者，以及使用角色型存取控制 (RBAC) 授權使用者操作。
+ 傳輸中加密會在您的資料從某一處移到另一處時進行加密，例如在您叢集內的節點之間移動，或是在您的快取與應用程式之間移動。
+ 待用加密可在同步和備份操作期間加密您磁碟上的資料。

ElastiCache 支援使用 IAM 和 Valkey 和 Redis OSS AUTH 命令驗證使用者，以及使用角色型存取控制 (RBAC) 授權使用者操作。

![\[影像：ElastiCache for Valkey 和 Redis OSS 安全圖表\]](http://docs.aws.amazon.com/zh_tw/AmazonElastiCache/latest/dg/images/ElastiCache-Redis-Secure-Compliant.png)


*ElastiCache for Valkey 和 Redis OSS 安全性圖表*

**Topics**
+ [ElastiCache 傳輸中加密 (TLS)](in-transit-encryption.md)
+ [ElastiCache 中的靜態加密](at-rest-encryption.md)
+ [身分驗證和授權](auth-redis.md)

# ElastiCache 傳輸中加密 (TLS)
<a name="in-transit-encryption"></a>

為了協助保護您的資料安全，Amazon ElastiCache 和 Amazon EC2 提供保護您伺服器上的資料不受未授權存取的機制。ElastiCache 透過提供傳輸中加密功能，在您的資料於不同地點間移動時，讓您有工具可以協助保護資料。

所有 Valkey 或 Redis OSS 無伺服器快取都已啟用傳輸中加密。對於節點型叢集，您可以在建立複寫群組時將 參數設定為 `TransitEncryptionEnabled``true`(CLI：`--transit-encryption-enabled`)，以在複寫群組上啟用傳輸中加密。無論您是使用AWS 管理主控台AWS CLI、 或 ElastiCache API 建立複寫群組，都可以執行此操作。

所有無伺服器快取都會啟用傳輸中加密。對於節點型叢集，您可以在使用 `TransitEncryptionEnabled``true`(CLI：`--transit-encryption-enabled`) 操作建立叢集時，將 參數設定為 `CreateCacheCluster`(CLI：`create-cache-cluster`)，在叢集上啟用傳輸中加密。

**Topics**
+ [傳輸中加密概觀](#in-transit-encryption-overview)
+ [傳輸中加密條件 (Valkey 和 Redis OSS)](#in-transit-encryption-constraints)
+ [傳輸中加密條件 (Memcached)](#in-transit-encryption-constraints)
+ [傳輸中加密最佳實務](#in-transit-encryption-best-practices)
+ [進一步的 Valkey 和 Redis OSS 選項](#in-transit-encryption-see-also)
+ [啟用 Memcached 的傳輸中加密](#in-transit-encryption-enable-existing-mc)
+ [啟用傳輸中加密](in-transit-encryption-enable.md)
+ [使用 valkey-cli 透過傳輸中加密連線至 ElastiCache (Valkey) 或 Amazon ElastiCache for Redis OSS](connect-tls.md)
+ [使用 Python 在以節點為基礎的 Redis OSS 叢集上啟用傳輸中加密](in-transit-encryption-enable-python.md)
+ [啟用傳輸中加密時的最佳實務](enable-python-best-practices.md)
+ [使用 Openssl (Memcached) 連線至已啟用傳輸中加密的節點](#in-transit-encryption-connect-mc)
+ [使用 Java 建立 TLS Memcached 用戶端](#in-transit-encryption-connect-java)
+ [使用 PHP 建立 TLS Memcached 用戶端](#in-transit-encryption-connect-php-mc)

## 傳輸中加密概觀
<a name="in-transit-encryption-overview"></a>

Amazon ElastiCache 傳輸中加密功能可讓您在資料於兩地之間傳輸時，在資料最易遭受攻擊的點提高資料的安全性。因為要加密和解密端點的資料需要一些處理，啟用傳輸中加密可能會有一些效能影響。您應該對您具有和不具有傳輸中加密的資料進行基準分析，以判斷對您的使用案例的影響。

ElastiCache 傳輸中加密會實作下列功能：
+ **加密的用戶端連線**：用戶端與快取節點的連線會經過 TLS 加密。
+ **加密的伺服器連線**：在叢集中的節點之間移動的資料會經過加密。
+ **伺服器身分驗證** - 用戶端可以驗證是否已連線至正確的伺服器。
+ **用戶端身分驗證** - 使用 Valkey 和 Redis OSS AUTH 功能，伺服器可以驗證用戶端。

## 傳輸中加密條件 (Valkey 和 Redis OSS)
<a name="in-transit-encryption-constraints"></a>

當您規劃節點型叢集實作時，應謹記 Amazon ElastiCache 傳輸中加密的下列限制：
+ 執行 Valkey 7.2 和更新版本以及 Redis OSS 3.2.6、4.0.10 和更新版本的複寫群組支援傳輸中加密。
+ 執行 Valkey 7.2 和更新版本以及 Redis OSS 第 7 版和更新版本的複寫群組支援修改現有叢集的傳輸中加密設定。
+ 只有在 Amazon VPC 中執行的複寫群組支援傳輸中加密。
+ 執行下列節點類型的複寫群組不支援傳輸中加密：M1, M2。

  如需詳細資訊，請參閱[支援的節點類型](CacheNodes.SupportedTypes.md)。
+ 透過將參數 `TransitEncryptionEnabled` 明確設定為 `true`，可啟用傳輸中加密。
+ 請確定您的快取用戶端支援 TLS 連線，而且您已在用戶端組態中啟用它。
+ 自 2026 年 1 月 26 日起，AWS將在 ElastiCache for Valkey 7.2 版及更新版本，以及 ElastiCache for Redis OSS 第 6 版及更新版本上，將支援的 TLS 最低版本更新為 1.2。客戶必須在該日期之前更新其用戶端軟體。此更新可協助您滿足安全、合規和法規需求。

## 傳輸中加密條件 (Memcached)
<a name="in-transit-encryption-constraints"></a>

當您規劃節點型叢集實作時，應謹記 Amazon ElastiCache 傳輸中加密的下列限制：
+ 執行 Memcached 1.6.12 和更新版本的叢集上支援傳輸中加密。
+ 傳輸中加密支援 Transport Layer Security (TLS) 1.2 和 1.3 版。
+ 只有在 Amazon VPC 中執行的叢集支援傳輸中加密。
+ 執行下列節點類型的複寫群組不支援傳輸中加密：M1, M2, M3, R3, T2。

  如需詳細資訊，請參閱[支援的節點類型](CacheNodes.SupportedTypes.md)。
+ 透過將參數 `TransitEncryptionEnabled` 明確設定為 `true`，可啟用傳輸中加密。
+ 您只能在建立叢集時，在叢集上啟用傳輸中加密。您無法透過修改叢集來開啟和關閉傳輸中加密。
+ 請確定您的快取用戶端支援 TLS 連線，而且您已在用戶端組態中啟用它。

## 傳輸中加密最佳實務
<a name="in-transit-encryption-best-practices"></a>
+ 因為要加密和解密端點的資料需要一些處理，實作傳輸中加密可能會降低效能。對您自己的資料進行傳輸中加密與無加密基準分析的比較，來判斷對您實作的影響。
+ 因為建立新連線可能所費不貲，您可以透過持續保存您的 TLS 連線來減少傳輸中加密的效能影響。

## 進一步的 Valkey 和 Redis OSS 選項
<a name="in-transit-encryption-see-also"></a>

如需 Valkey 和 Redis OSS 可用選項的詳細資訊，請參閱下列連結。
+ [ElastiCache 中的靜態加密](at-rest-encryption.md)
+ [使用 Valkey 和 Redis OSS AUTH 命令進行驗證](auth.md)
+ [角色型存取控制 (RBAC) 規則數量](Clusters.RBAC.md)
+ [Amazon VPC 和 ElastiCache 安全性](VPCs.md)
+ [Amazon ElastiCache 中的 Identity and Access Management](IAM.md)

## 啟用 Memcached 的傳輸中加密
<a name="in-transit-encryption-enable-existing-mc"></a>

若要在使用AWS管理主控台建立 Memcached 叢集時，啟用傳輸中加密，請選取以下項目：
+ 選擇 Memcached 當作您的引擎。
+ 選擇引擎 1.6.12 或更新版本。
+ 在 **Encryption in transit** (傳輸中加密) 中，選擇 **Enable** (啟用)。

 如需step-by-step程序，請參閱 [為 Valkey 或 Redis OSS 建立叢集](Clusters.Create.md)。

# 啟用傳輸中加密
<a name="in-transit-encryption-enable"></a>

所有無伺服器快取都會啟用傳輸中加密。在節點型叢集上，您可以使用AWS 管理主控台、 CLI 或 ElastiCache API AWS啟用傳輸中加密。

## 使用 啟用傳輸中加密AWS 管理主控台
<a name="in-transit-encryption-enable-console"></a>

### 使用 為新的節點型叢集啟用傳輸中加密AWS 管理主控台
<a name="in-transit-encryption-enable-con"></a>

自行設計叢集時，採用「輕鬆建立」方法的「開發/測試」和「生產」組態會使用傳輸中加密。當您自行選擇組態時，請進行下列選擇：
+ 選擇引擎版本 3.2.6、4.0.10 或更新版本。
+ 按一下**傳輸中加密**選項的**啟用**旁的核取方塊。

如需逐步操作程序，請參閱下列：
+ [建立 Valkey （停用叢集模式） 叢集 （主控台）](SubnetGroups.designing-cluster-pre.valkey.md#Clusters.Create.CON.valkey-gs)
+ [建立 Valkey 或 Redis OSS （啟用叢集模式） 叢集 （主控台）](Clusters.Create.md#Clusters.Create.CON.RedisCluster)

### 使用 啟用現有節點型叢集的傳輸中加密AWS 管理主控台
<a name="in-transit-encryption-enable-existing"></a>

啟用傳輸中加密有兩個步驟，您必須先將傳輸加密模式設為 `preferred`。此模式可讓您的 Valkey 或 Redis OSS 用戶端使用加密和未加密的連線進行連線。遷移所有 Valkey 或 Redis OSS 用戶端以使用加密連線後，您可以修改叢集組態，將傳輸加密模式設定為 `required`。將傳輸加密模式設為 `required` 會捨棄所有未加密連線，且僅允許加密連線。

**將您的**傳輸加密模式**設定為**偏好****

1. 登入AWS 管理主控台，並在 [https://console.aws.amazon.com/elasticache/](https://console.aws.amazon.com/elasticache/)：// 開啟 Amazon ElastiCache 主控台。

1. 從左側導覽窗格中列出的 ElastiCache **資源**中選擇 **Valkey 快取**或 **Redis OSS 快取**。

1. 選擇您要更新的快取。

1. 選擇 **Actions** (動作) 下拉式清單，然後選擇 **Modify** (修改)。

1. 在 **Security** (安全性) 區段的 **Encryption in transit** (傳輸中加密) 下選擇 **Enable** (啟用)。

1. 選擇 **Preferred** (偏好) 做為 **Transit encryption mode** (傳輸加密模式)。

1. 選擇 **Preview changes** (預覽變更)，然後儲存變更。

在您遷移所有 Valkey 或 Redis OSS 用戶端以使用加密連線之後：

**將您的**傳輸加密模式**設定為**必要****

1. 登入AWS 管理主控台，並在 [https://console.aws.amazon.com/elasticache/](https://console.aws.amazon.com/elasticache/)：// 開啟 Amazon ElastiCache 主控台。

1. 從左側導覽窗格中列出的 ElastiCache **資源**中選擇 **Valkey 快取**或 **Redis OSS 快取**。

1. 選擇您要更新的快取。

1. 選擇 **Actions** (動作) 下拉式清單，然後選擇 **Modify** (修改)。

1. 在 **Security** (安全性) 區段中，選擇 **Required** (必要) 做為 **Transit encryption mode** (傳輸加密模式)。

1. 選擇 **Preview changes** (預覽變更)，然後儲存變更。

## 使用 啟用傳輸中加密AWS CLI
<a name="in-transit-encryption-enable-cli"></a>

若要在使用 建立 Valkey 或 Redis OSS 複寫群組時啟用傳輸中加密AWS CLI，請使用 參數 `transit-encryption-enabled`。

### 針對 Valkey 或 Redis OSS （停用叢集模式），在新的節點型叢集上啟用傳輸中加密 (CLI)
<a name="in-transit-encryption-enable-cli-redis-classic-rg"></a>

使用AWS CLI操作`create-replication-group`和下列參數來建立具有已啟用傳輸中加密複本的 Valkey 或 Redis OSS 複寫群組：

**重要參數：**
+ **--engine**- 必須為 `valkey`或 `redis`。
+ **--engine-version**- 如果引擎是 Redis OSS，這必須是 3.2.6、4.0.10 或更新版本。
+ **--transit-encryption-enabled** - 必要項目。如果您啟用傳輸中加密，您也必須為 `--cache-subnet-group` 參數提供一個值。
+ **--num-cache-clusters** - 必須至少為 1。此參數的最大值為 6。

如需詳細資訊，請參閱下列內容：
+ [從頭開始建立 Valkey 或 Redis OSS （停用叢集模式） 複寫群組 (AWS CLI)](Replication.CreatingReplGroup.NoExistingCluster.Classic.md#Replication.CreatingReplGroup.NoExistingCluster.Classic.CLI)
+ [create-replication-group](https://docs.aws.amazon.com/cli/latest/reference/elasticache/create-replication-group.html)

### 針對 Valkey 或 Redis OSS （啟用叢集模式），在新的節點型叢集上啟用傳輸中加密 (CLI)
<a name="in-transit-encryption-enable-cli-redis-cluster"></a>

使用AWS CLI操作`create-replication-group`和下列參數來建立啟用傳輸中加密的 Valkey 或 Redis OSS （啟用叢集模式） 複寫群組：

**重要參數：**
+ **--engine**- 必須為 `valkey`或 `redis`。
+ **--engine-version**- 如果引擎是 Redis OSS，這必須是 3.2.6、4.0.10 或更新版本。
+ **--transit-encryption-enabled** - 必要項目。如果您啟用傳輸中加密，您也必須為 `--cache-subnet-group` 參數提供一個值。
+ 使用下列其中一個參數集來指定複寫群組之節點群組的組態：
  + **--num-node-groups** - 指定此複寫群組中碎片 (節點群組) 的數量。此參數的最大值為 500。

    **--replicas-per-node-group** - 指定每個節點群組中複本節點的數量。此處指定的值會套用到此複寫群組中的所有碎片。此參數的最大值為 5。
  + **--node-group-configuration** - 獨立指定每個碎片的組態。

如需詳細資訊，請參閱下列內容：
+ [從頭開始建立 Valkey 或 Redis OSS （啟用叢集模式） 複寫群組 (AWS CLI)](Replication.CreatingReplGroup.NoExistingCluster.Cluster.md#Replication.CreatingReplGroup.NoExistingCluster.Cluster.CLI)
+ [create-replication-group](https://docs.aws.amazon.com/cli/latest/reference/elasticache/create-replication-group.html)

### 在使用AWS CLI的現有叢集上啟用傳輸中加密
<a name="in-transit-encryption-enable-cli-redis-cluster-existing-cli"></a>

啟用傳輸中加密有兩個步驟，您必須先將傳輸加密模式設為 `preferred`。此模式可讓您的 Valkey 或 Redis OSS 用戶端使用加密和未加密的連線進行連線。遷移所有 Valkey 或 Redis OSS 用戶端以使用加密連線後，您可以修改叢集組態，將傳輸加密模式設定為 `required`。將傳輸加密模式設為 `required` 會捨棄所有未加密連線，且僅允許加密連線。

使用AWS CLI操作`modify-replication-group`和下列參數來更新停用傳輸中加密的 Valkey 或 Redis OSS （啟用叢集模式） 複寫群組。

**啟用傳輸中加密**

1. 使用下列參數，將 transit-encryption-mode 設為 `preferred`
   + **--transit-encryption-enabled** - 必要項目。
   + **--transit-encryption-mode**—必須設定為 `preferred`。

1. 使用下列參數，將 transit-encryption-mode 設為 `required`：
   + **--transit-encryption-enabled** - 必要項目。
   + **--transit-encryption-mode**—必須設定為 `required`。

# 使用 valkey-cli 透過傳輸中加密連線至 ElastiCache (Valkey) 或 Amazon ElastiCache for Redis OSS
<a name="connect-tls"></a>

若要從啟用傳輸中加密的 ElastiCache for Redis OSS 快取存取資料，您可以使用使用 Secure Socket Layer (SSL) 的用戶端。您也可以在 Amazon Linux 和 Amazon Linux 2 上使用 valkey-cli 搭配 TLS/SSL。如果您的用戶端不支援 TLS，您可以在用戶端主機上使用 `stunnel`命令來建立 Redis OSS 節點的 SSL 通道。

## 與 Linux 的加密連線
<a name="connect-tls.linux"></a>

若要使用 valkey-cli 連線到在 Amazon Linux 2 或 Amazon Linux 上啟用傳輸中加密的 Valkey 或 Redis OSS 叢集，請遵循下列步驟。

1. 下載並編譯 valkey-cli 公用程式。此公用程式包含在 Valkey 軟體分發中。

1. 在 EC2 執行個體的命令提示字元中，針對您正在使用的 Linux 版本輸入適當的命令。

   **Amazon Linux 2**

   如果使用 Amazon Linux 2，請輸入以下內容：

   ```
   sudo yum -y install openssl-devel gcc
   wget https://github.com/valkey-io/valkey/archive/refs/tags/7.2.6.tar.gz
   tar xvzf valkey-7.2.6.tar.gz
   cd valkey-7.2.6
   make distclean
   make valkey-cli BUILD_TLS=yes
   sudo install -m 755 src/valkey-cli /usr/local/bin/
   ```

   **Amazon Linux**

   如果使用 Amazon Linux，請輸入以下內容：

   ```
   sudo yum install gcc jemalloc-devel openssl-devel tcl tcl-devel clang wget
   wget https://github.com/valkey-io/valkey/archive/refs/tags/8.0.0.tar.gz
   tar xvzf valkey-8.0.0.tar.gz
   cd valkey-8.0.0
   make valkey-cli CC=clang BUILD_TLS=yes
   sudo install -m 755 src/valkey-cli /usr/local/bin/
   ```

   在 Amazon Linux 上，您可能還需要執行下列額外步驟：

   ```
   sudo yum install clang
   CC=clang make
   sudo make install
   ```

1. 在您下載並安裝 valkey-cli 公用程式之後，建議您執行選用的 `make-test` 命令。

1. 若要連線至已啟用加密和身分驗證的叢集，請輸入此命令：

   ```
   valkey-cli -h Primary or Configuration Endpoint --tls -a 'your-password' -p 6379
   ```
**注意**  
如果您在 Amazon Linux 2023 上安裝 redis6，您現在可以使用 命令`redis6-cli`，而不是 `valkey-cli`：  

   ```
   redis6-cli -h Primary or Configuration Endpoint --tls -p 6379
   ```

## 使用 stunnel 的加密連線
<a name="connect-tls.stunnel"></a>

若要使用 valkey-cli 連線至使用 stunnel 啟用傳輸中加密的 Redis OSS 叢集，請遵循下列步驟。

1. 使用 SSH 連線到用戶端並安裝 `stunnel`。

   ```
   sudo yum install stunnel
   ```

1. 執行下列命令，使用下方提供的輸出做為範本，`'/etc/stunnel/valkey-cli.conf'`同時建立和編輯檔案，將 ElastiCache for Redis OSS 叢集端點新增至一或多個連線參數。

   ```
   vi /etc/stunnel/valkey-cli.conf
   
   				
   fips = no
   setuid = root
   setgid = root
   pid = /var/run/stunnel.pid
   debug = 7 
   delay = yes
   options = NO_SSLv2
   options = NO_SSLv3
   [valkey-cli]
      client = yes
      accept = 127.0.0.1:6379
      connect = primary.ssltest.wif01h.use1.cache.amazonaws.com:6379
   [valkey-cli-replica]
      client = yes
      accept = 127.0.0.1:6380
      connect = ssltest-02.ssltest.wif01h.use1.cache.amazonaws.com:6379
   ```

   在下一個範例中，組態檔案有兩個連線：`valkey-cli` 和 `valkey-cli-replica`。參數的設定方式如下：
   + **client** 設為 yes，以指定此 stunnel 執行個體為用戶端。
   + **accept** 設為用戶端 IP。在此範例中，主要 設定為連接埠 6379 上的 Redis OSS 預設 127.0.0.1。複本主機必須呼叫不同的連接埠，並設為 6380。您可以使用的暫時性連接埠為 1024–65535。如需詳細資訊，請參閱 *Amazon VPC 使用者指南*中的[暫時性連接埠](https://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_ACLs.html#VPC_ACLs_Ephemeral_Ports)。
   + **connect** 設定為 Redis OSS 伺服器端點。如需詳細資訊，請參閱[在 ElastiCache 中尋找連線端點](Endpoints.md)。

1. 啟動 `stunnel`。

   ```
   sudo stunnel /etc/stunnel/valkey-cli.conf
   ```

   使用 `netstat` 命令來確認通道已啟動。

   ```
   sudo netstat -tulnp | grep -i stunnel
   				
   tcp        0      0 127.0.0.1:6379              0.0.0.0:*                   LISTEN      3189/stunnel        
   tcp        0      0 127.0.0.1:6380              0.0.0.0:*                   LISTEN      3189/stunnel
   ```

1. 使用通道的本機端點連線至加密的 Redis OSS 節點。
   + 如果在建立 ElastiCache for Redis OSS 叢集期間未使用 AUTH 密碼，則此範例會使用 valkey-cli，在 Amazon Linux 上使用 valkey-cli 的完整路徑連線至 ElastiCache for Redis OSS 伺服器：

     ```
     /home/ec2-user/redis-7.2.5/src/valkey-cli -h localhost -p 6379
     ```

     如果在建立 Redis OSS 叢集期間使用 AUTH 密碼，此範例會使用 valkey-cli，在 Amazon Linux 上使用 valkey-cli 的完整路徑連線至 Redis OSS 伺服器：

     ```
      /home/ec2-user/redis-7.2.5/src/valkey-cli -h localhost -p 6379 -a my-secret-password
     ```

   或
   + 將目錄變更為 redis-7.2.5 並執行下列動作：

     如果在建立 ElastiCache for Redis OSS 叢集期間未使用 AUTH 密碼，則此範例會使用 valkey-cli，在 Amazon Linux 上使用 valkey-cli 的完整路徑連線至 ElastiCache for Redis OSS 伺服器：

     ```
     src/valkey-cli -h localhost -p 6379
     ```

     如果在 Redis OSS 叢集建立期間使用 AUTH 密碼，則此範例會使用 valkey-cli，在 Amazon Linux 上使用 valkey-cli 的完整路徑連線至 Valkey 或 Redis OSS 伺服器：

     ```
     src/valkey-cli -h localhost -p 6379 -a my-secret-password	
     ```

   此範例使用 Telnet 連線至 Valkey Redis OSS 伺服器。

   ```
   telnet localhost 6379
   			
   Trying 127.0.0.1...
   Connected to localhost.
   Escape character is '^]'.
   auth MySecretPassword
   +OK
   get foo
   $3
   bar
   ```

1. 若要停止和關閉 SSL 通道，請執行 `pkill` stunnel 程序。

   ```
   sudo pkill stunnel
   ```

# 使用 Python 在以節點為基礎的 Redis OSS 叢集上啟用傳輸中加密
<a name="in-transit-encryption-enable-python"></a>

下列指南將示範如何在最初在停用傳輸中加密的情況下建立的 Redis OSS 7.0 叢集上啟用傳輸中加密。在此程序期間，TCP 和 TLS 用戶端將繼續與叢集通訊，而不會停機。

Boto3 將從環境變量中取得所需的憑證 (`aws_access_key_id`、`aws_secret_access_key` 和 `aws_session_token`)。這些憑證將事先貼到同一個 bash 終端中，我們將在其中執行 `python3` 以處理本指南中顯示的 Python 程式碼。以下範例中的程式碼是從在相同 VPC 中啟動的 EC2 執行個體處理，該 VPC 將用於在其中建立 ElastiCache Redis OSS 叢集。

**注意**  
以下範例使用 boto3 SDK 進行 ElastiCache 管理作業 (叢集或使用者建立)，並使用 redis-py/redis-py-cluster 來處理資料。
您必須至少使用 boto3 版本 (=\$1) 1.26.39，才能搭配叢集修改 API 使用線上 TLS 遷移。
ElastiCache 僅支援具有 Valkey 7.2 版和更新版本或 Redis OSS 7.0 版或更新版本的叢集進行線上 TLS 遷移。因此，如果您的叢集執行的 Redis OSS 版本早於 7.0，則需要升級叢集的 Redis OSS 版本。如需這些版本差異的詳細資訊，請參閱 [與 Redis OSS 的主要引擎版本行為和相容性差異](VersionManagementConsiderations.md)。

**Topics**
+ [定義將啟動 ElastiCache Valkey 或 Redis OSS 叢集的字串常數](#enable-python-define-constants)
+ [定義叢集組態類別](#enable-python-define-classes)
+ [定義一個將代表叢集本身的類別](#enable-python-define-classes-cluster)
+ [（選用） 建立包裝函式類別，以示範用戶端與 Valkey 或 Redis OSS 叢集的連線](#enable-python-create-wrapper)
+ [建立主函數，以示範變更傳輸中加密組態的程序](#enable-python-main-function)

## 定義將啟動 ElastiCache Valkey 或 Redis OSS 叢集的字串常數
<a name="enable-python-define-constants"></a>

首先，讓我們定義一些簡單的 Python 字串常數，其中包含建立 ElastiCache 叢集所需的AWS實體名稱`Cache Subnet group`，例如 `security-group`、 和 `default parameter group`。所有這些AWS實體都必須在您願意使用的區域中AWS的帳戶中事先建立。

```
#Constants definitions 
SECURITY_GROUP = "sg-0492aa0a29c558427"
CLUSTER_DESCRIPTION = "This cluster has been launched as part of the online TLS migration user guide"
EC_SUBNET_GROUP = "client-testing"
DEFAULT_PARAMETER_GROUP_REDIS_7_CLUSTER_MODE_ENABLED = "default.redis7.cluster.on"
```

## 定義叢集組態類別
<a name="enable-python-define-classes"></a>

現在，讓我們定義一些簡單的 Python 類別，其將代表叢集的組態，該類別將保留有關叢集的中繼資料，例如 Valkey 或 Redis OSS 版本、執行個體類型，以及是否啟用或停用傳輸中加密 (TLS)。

```
#Class definitions

class Config:
    def __init__(
        self,
        instance_type: str = "cache.t4g.small",
        version: str = "7.0",
        multi_az: bool = True,
        TLS: bool = True,
        name: str = None,
    ):
        self.instance_type = instance_type
        self.version = version
        self.multi_az = multi_az
        self.TLS = TLS
        self.name = name or f"tls-test"

    def create_base_launch_request(self):
        return {
            "ReplicationGroupId": self.name,
            "TransitEncryptionEnabled": self.TLS,
            "MultiAZEnabled": self.multi_az,
            "CacheNodeType": self.instance_type,
            "Engine": "redis",
            "EngineVersion": self.version,
            "CacheSubnetGroupName": EC_SUBNET_GROUP ,
            "CacheParameterGroupName": DEFAULT_PARAMETER_GROUP_REDIS_7_CLUSTER_MODE_ENABLED ,
            "ReplicationGroupDescription": CLUSTER_DESCRIPTION,
            "SecurityGroupIds": [SECURITY_GROUP],
        }
        
class ConfigCME(Config):
    def __init__(
        self,
        instance_type: str = "cache.t4g.small",
        version: str = "7.0",
        multi_az: bool = True,
        TLS: bool = True,
        name: str = None,
        num_shards: int = 2,
        num_replicas_per_shard: int = 1,
    ):
        super().__init__(instance_type, version, multi_az, TLS, name)
        self.num_shards = num_shards
        self.num_replicas_per_shard = num_replicas_per_shard

    def create_launch_request(self) -> dict:
        launch_request = self.create_base_launch_request()
        launch_request["NumNodeGroups"] = self.num_shards
        launch_request["ReplicasPerNodeGroup"] = self.num_replicas_per_shard
        return launch_request
```

## 定義一個將代表叢集本身的類別
<a name="enable-python-define-classes-cluster"></a>

現在，讓我們定義一些簡單的 Python 類別，這些類別將代表 ElastiCache Valkey 或 Redis OSS 叢集本身。這個類別將有一個用戶端欄位，以保留一個 boto3 用戶端的 ElastiCache 管理操作，如建立叢集和查詢 ElastiCache API。

```
import botocore.config
import boto3

# Create boto3 client
def init_client(region: str = "us-east-1"):
    config = botocore.config.Config(retries={"max_attempts": 10, "mode": "standard"})
    init_request = dict()
    init_request["config"] = config
    init_request["service_name"] = "elasticache"
    init_request["region_name"] = region
    return boto3.client(**init_request) 
 
 
class ElastiCacheClusterBase:
    def __init__(self, name: str):
        self.name = name
        self.elasticache_client = init_client()

    def get_first_replication_group(self):
        return self.elasticache_client.describe_replication_groups(
        ReplicationGroupId=self.name
        )["ReplicationGroups"][0]
 
    def get_status(self) -> str:
        return self.get_first_replication_group()["Status"]
 
    def get_transit_encryption_enabled(self) -> bool:
        return self.get_first_replication_group()["TransitEncryptionEnabled"]
 
    def is_available(self) -> bool:
        return self.get_status() == "available"
        
    def is_modifying(self) -> bool:
        return self.get_status() == "modifying"
        
    def wait_for_available(self):
        while True:
            if self.is_available():
                break
            else:
                time.sleep(5)

    def wait_for_modifying(self):
        while True:
            if self.is_modifying():
                break
            else:
                time.sleep(5)
                
    def delete_cluster(self) -> bool:
        self.elasticache_client.delete_replication_group(
            ReplicationGroupId=self.name, RetainPrimaryCluster=False
        )
        
    def modify_transit_encryption_mode(self, new_transit_encryption_mode: str):
        # generate api call to migrate the cluster to TLS preffered or to TLS required
            self.elasticache_client.modify_replication_group(
                ReplicationGroupId=self.name,
                TransitEncryptionMode=new_transit_encryption_mode,
                TransitEncryptionEnabled=True,
                ApplyImmediately=True,
            )  
        self.wait_for_modifying()
              
 class ElastiCacheClusterCME(ElastiCacheClusterBase):
    def __init__(self, name: str):
        super().__init__(name)

    @classmethod
    def launch(cls, config: ConfigCME = None) -> ElastiCacheClusterCME:
        config = config or ConfigCME()
        print(config)
        new_cluster = ElastiCacheClusterCME(config.name)
        launch_request = config.create_launch_request()
        new_cluster.elasticache_client.create_replication_group(**launch_request)
        new_cluster.wait_for_available()
        return new_cluster

    def get_configuration_endpoint(self) -> str:
        return self.get_first_replication_group()["ConfigurationEndpoint"]["Address"]
     
#Since the code can throw exceptions, we define this class to make the code more readable and 
#so we won't forget to delete the cluster    
class ElastiCacheCMEManager:
    def __init__(self, config: ConfigCME = None):
        self.config = config or ConfigCME()

    def __enter__(self) -> ElastiCacheClusterCME:
        self.cluster = ElastiCacheClusterCME.launch(self.config)
        return self.cluster 
          
    def __exit__(self, exc_type, exc_val, exc_tb):
        self.cluster.delete_cluster()
```

## （選用） 建立包裝函式類別，以示範用戶端與 Valkey 或 Redis OSS 叢集的連線
<a name="enable-python-create-wrapper"></a>

現在，讓我們為 `redis-py-cluster` 用戶端建立一個包裝類別。這個包裝類別將支援使用一些鍵預先填充叢集，然後執行隨機重複的 `get` 命令。

**注意**  
這是一個選擇性步驟，但它簡化了在後面步驟中出現的主函數。

```
import redis
improt random
from time import perf_counter_ns, time


class DowntimeTestClient:
    def __init__(self, client):
        self.client = client

        # num of keys prefilled
        self.prefilled = 0
        # percent of get above prefilled
        self.percent_get_above_prefilled = 10 # nil result expected when get hit above prefilled
        # total downtime in nano seconds 
        self.downtime_ns = 0
        # num of success and fail operations
        self.success_ops = 0
        self.fail_ops = 0
        self.connection_errors = 0
        self.timeout_errors = 0
        

    def replace_client(self, client):
        self.client = client

    def prefill_data(self, timelimit_sec=60):
        end_time = time() + timelimit_sec
        while time() < end_time:
            self.client.set(self.prefilled, self.prefilled)
            self.prefilled += 1

    # unsuccesful operations throw exceptions
    def _exec(self, func):
        try:
            start_ns = perf_counter_ns()
            func()
            self.success_ops += 1
            elapsed_ms = (perf_counter_ns() - start_ns) // 10 ** 6
            # upon succesful execution of func
            # reset random_key to None so that the next command
            # will use a new random key
            self.random_key = None

        except Exception as e:
            elapsed_ns = perf_counter_ns() - start_ns
            self.downtime_ns += elapsed_ns
            # in case of failure- increment the relevant counters so that we will keep track 
            # of how many connection issues we had while trying to communicate with
            # the cluster.
            self.fail_ops += 1
            if e.__class__ is redis.exceptions.ConnectionError:
                self.connection_errors += 1
            if e.__class__ is redis.exceptions.TimeoutError:
                self.timeout_errors += 1

    def _repeat_exec(self, func, seconds):
        end_time = time() + seconds
        while time() < end_time:
            self._exec(func)

    def _new_random_key_if_needed(self, percent_above_prefilled):
        if self.random_key is None:
            max = int((self.prefilled * (100 + percent_above_prefilled)) / 100)
            return random.randint(0, max)
        return self.random_key

    def _random_get(self):
        key = self._new_random_key_if_needed(self.percent_get_above_prefilled)
        result = self.client.get(key)
        # we know the key was set for sure only in the case key < self.prefilled
        if key < self.prefilled:
            assert result.decode("UTF-8") == str(key)


    def repeat_get(self, seconds=60):
        self._repeat_exec(self._random_get, seconds)

    def get_downtime_ms(self) -> int:
        return self.downtime_ns // 10 ** 6


    def do_get_until(self, cond_check):
        while not cond_check():
            self.repeat_get()
        # do one more get cycle once condition is met
        self.repeat_get()
```

## 建立主函數，以示範變更傳輸中加密組態的程序
<a name="enable-python-main-function"></a>

現在，讓我們定義主函數，它將執行以下操作：

1. 使用 boto3 ElastiCache 用戶端建立叢集。

1. 初始化將使用不具備 TLS 的清楚 TCP 連線連接到叢集的 `redis-py-cluster` 用戶端。

1. `redis-py-cluster` 用戶端會用一些資料預先填充叢集。

1. boto3 用戶端將會觸發 TLS 從無 TLS 遷移至 TLS 偏好。

1. 當叢集正在遷移到 TLS `Preferred` 時，`redis-py-cluster` TCP 用戶端將向叢集發送重複的 `get` 操作，直到遷移完成。

1. 完成遷移至 TLS `Preferred` 之後，我們會宣告該叢集支援傳輸中加密。之後，我們將建立一個將使用 TLS 連接到叢集的 `redis-py-cluster` 用戶端。

1. 我們將使用新的 TLS 用戶端和舊的 TCP 用戶端發送一些 `get` 命令。

1. boto3 用戶端將觸發從 TLS `Preferred` 到 TLS 所需的 TLS 遷移。

1. 當叢集正在遷移到所需的 TLS 時，redis-py-cluster TLS 用戶端將向叢集發送重複的 `get` 操作，直到遷移完成。

```
import redis

def init_cluster_client(
    cluster: ElastiCacheClusterCME, prefill_data: bool, TLS: bool = True) -> DowntimeTestClient:
    # we must use for the host name the cluster configuration endpoint. 
    redis_client = redis.RedisCluster(
        host=cluster.get_configuration_endpoint(), ssl=TLS, socket_timeout=0.25, socket_connect_timeout=0.1
    )
    test_client = DowntimeTestClient(redis_client)
    if prefill_data:
        test_client.prefill_data()
    return test_client

if __name__ == '__main__':
    config = ConfigCME(TLS=False, instance_type="cache.m5.large")

    with ElastiCacheCMEManager(config) as cluster:
        # create a client that will connect to the cluster with clear tcp connection
        test_client_tcp = init_cluster_client(cluster, prefill_data=True, TLS=False)
        
       # migrate the cluster to TLS Preferred
        cluster.modify_transit_encryption_mode(new_transit_encryption_mode="preferred")
        
        # do repeated get commands until the cluster finishes the migration to TLS Preferred
        test_client_tcp.do_get_until(cluster.is_available)
        
       # verify that in transit encryption is enabled so that clients will be able to connect to the cluster with TLS
        assert cluster.get_transit_encryption_enabled() == True
        
       # create a client that will connect to the cluster with TLS connection. 
        # we must first make sure that the cluster indeed supports TLS
        test_client_tls = init_cluster_client(cluster, prefill_data=True, TLS=True)
        
        # by doing get commands with the tcp client for 60 more seconds
       # we can verify that the existing tcp connection to the cluster still works 
        test_client_tcp.repeat_get(seconds=60)
        
        # do get commands with the new TLS client for 60 more seconds
        test_client_tcp.repeat_get(seconds=60)
        
       # migrate the cluster to TLS required
        cluster.modify_transit_encryption_mode(new_transit_encryption_mode="required")
        
       # from this point the tcp clients will be disconnected and we must not use them anymore.
       # do get commands with the TLS client until the cluster finishes migartion to TLS required mode.
        test_client_tls.do_get_until(cluster.is_available)
```

# 啟用傳輸中加密時的最佳實務
<a name="enable-python-best-practices"></a>

## 啟用傳輸中加密之前：請確定您有適當的 DNS 記錄處理
<a name="enable-python-best-practices-before"></a>

**注意**  
在此過程中，我們正在變更和刪除舊端點。不正確使用端點可能會導致 Valkey 或 Redis OSS 用戶端使用舊的和已刪除的端點，以防止其連線至叢集。

當叢集從非 TLS 遷移至 TLS 偏好時，會保留舊的叢集組態端點 DNS 記錄，並以不同的格式產生新的叢集組態端點 DNS 記錄。啟用 TLS 的叢集使用與停用 TLS 的叢集不同的 DNS 記錄格式。ElastiCache 會保留兩個 DNS 記錄，`encryption mode: Preferred`以便應用程式和其他 Valkey 或 Redis OSS 用戶端可以在它們之間切換。DNS 記錄中的下列變更會在 TLS 遷移程序期間進行：

### 啟用傳輸中加密時所發生的 DNS 記錄變更說明
<a name="enable-python-best-practices-before-desc"></a>

**對於 CME 叢集**

當叢集設定為「傳輸加密模式：偏好」時：
+ 非 TLS 叢集的原始叢集組態端點將保持作用中狀態。將叢集從 TLS 加密模式「無」重新設定為「偏好」時，不會有停機時間。
+ 當叢集設定為 TLS 偏好模式時，將產生新的 TLS Valkey 或 Redis OSS 端點。這些新端點將解析為與舊端點 (非 TLS) 相同的 IP。
+ 新的 TLS Valkey 或 Redis OSS 組態端點將在 ElastiCache 主控台和 `describe-replication-group` API 回應中公開。

當叢集設定為「傳輸加密模式：需要」時：
+ 舊版未啟用 TLS 的端點將被刪除。TLS 叢集端點不會有停機時間。
+ 您可以從 ElastiCache 控制台或 `describe-replication-group` API 檢索新的 `cluster-configuration-endpoint`。

**對於啟用自動容錯移轉或停用自動容錯移轉的 CMD 叢集**

當複寫群組設為「傳輸加密模式：偏好」時：
+ 啟用非 TLS 叢集的原始主端點和讀取器端點將保持作用中狀態。
+ 當叢集設為 TLS `Preferred` 模式時，將產生新的 TLS 主要端點和讀取端點。此新端點將解析為與舊端點 (非 TLS) 相同的 IP。
+ 新的主要端點和讀取器端點將在 ElastiCache 控制台和對 `describe-replication-group` API 的反應中公開。

當複寫群組設為「傳輸加密模式：需要」時：
+ 舊的非 TLS 主端點和讀取器端點將被刪除。TLS 叢集端點不會有停機時間。
+ 您可以從 ElastiCache 控制台或 `describe-replication-group` API 檢索新的主要與讀取器端點。

### DNS 記錄的建議用法
<a name="enable-python-best-practices-before-usage"></a>

**對於 CME 叢集**
+ 使用叢集組態端點，而不是應用程式程式碼中的每個節點 DNS 記錄。不建議直接使用每個節點 DNS 名稱，因為在遷移期間，它們會變更，而應用程式程式碼會中斷與叢集的連線。
+ 請勿硬式編碼應用程式中的叢集組態端點，因為它會在此程序期間變更。
+ 在應用程式中硬式編碼叢集組態端點是錯誤的實務，因為在此過程中可以變更。傳輸中加密完成後，請使用 `describe-replication-group` API 查詢叢集組態端點 （如上所述 （粗體）)，並使用您從該時間點取得的 DNS 來回應。

**對於啟用自動容錯移轉的 CMD 叢集**
+ 使用主要端點和讀取器端點，而不是應用程式程式碼中的每節點 DNS 名稱，因為舊的每節點 DNS 名稱會被刪除，並在將叢集從非 TLS 移轉至 TLS 偏好時產生新的 DNS 名稱。不建議直接使用每個節點的 DNS 名稱，因為您未來可能會將複本新增至叢集。此外，啟用「自動容錯移轉」時，ElastiCache 服務會自動變更主要叢集和複本的角色，建議使用主要端點和讀取器端點來協助您追蹤這些變更。最後，使用讀取器端點可協助您在叢集中的複本之間平均分配複本的讀取。
+ 在應用程式中硬式編碼主要端點和讀取器端點是不好的做法，因為它可以在 TLS 遷移程序期間進行變更。完成 TLS 偏好的遷移變更後，請使用 describe-replication-group API 查詢主要端點和讀取器端點，並使用您從此時取得的 DNS 回應。如此，您將能夠以動態方式追踪端點中的變更。

**對於停用自動容錯移轉的 CMD 叢集**
+ 使用主要端點和讀取器端點，而不是應用程式程式碼中的每個節點 DNS 名稱。當停用自動容錯移轉時，在啟用自動容錯移轉時由 ElastiCache 服務自動管理的擴展、修補、容錯移轉和其他過程將由您完成。這可讓您更輕易地手動追蹤不同端點。由於舊的每個節點 DNS 名稱會被刪除，並在將叢集從非 TLS 移轉至 TLS 偏好時產生新名稱，因此請勿直接使用每個節點的 DNS 名稱。這是強制性的，因此用戶端才能夠在 TLS 遷移期間連線到叢集。此外，使用讀取器端點時，您將受益於在複本之間均勻分散讀取，並在從叢集中新增或刪除複本時追蹤 DNS 記錄。
+ 在應用程式中對叢集組態端點進行硬式編碼是一種不好的做法，因為它可以在 TLS 遷移過程中變更。

## 在傳輸過程中加密：注意遷移過程何時完成
<a name="enable-python-best-practices-during"></a>

傳輸加密模式的變更不是立即的，可能需要一些時間。大型叢集尤其如此。只有當叢集完成 TLS 的遷移作業時，才能接受並提供 TCP 和 TLS 連線。因此，在傳輸中加密完成之前，您不應該建立嘗試與叢集建立 TLS 連線的用戶端。

在傳輸中加密成功完成或失敗時，有幾種方法可以得到通知：(未顯示於上面的程式碼範例中)：
+ 使用 SNS 服務在加密完成時收到通知
+ 使用將在加密完成時發出事件的 `describe-events` API
+ 在 ElastiCache 主控台中看到加密已完成的訊息

您也可以在應用程式中實作邏輯，以瞭解加密是否完成。在上面的範例中，我們看到了幾種確保叢集完成遷移的方法：
+ 等待遷移程序開始 (叢集狀態變更為「修改」)，並等待修改完成 (叢集狀態會變回「可用」)
+ 透過查詢 `describe-replication-group` API 聲明叢集的 `transit_encryption_enabled` 已設為 True。

### 啟用傳輸中加密之後：確定您使用的用戶端設定正確
<a name="enable-python-best-practices-after"></a>

當叢集處於 TLS 偏好的模式時，您的應用程式應該開啟與叢集的 TLS 連線，並且只使用這些連線。如此一來，您的應用程式在啟用傳輸中加密時就不會遇到停機時間。您可以使用 SSL 區段下的資訊命令，確保沒有更明確的 TCP 連線至 Valkey 或 Redis OSS 引擎。

```
# SSL
ssl_enabled:yes
ssl_current_certificate_not_before_date:Mar 20 23:27:07 2017 GMT
ssl_current_certificate_not_after_date:Feb 24 23:27:07 2117 GMT
ssl_current_certificate_serial:D8C7DEA91E684163
tls_mode_connected_tcp_clients:0   (should be zero)
tls_mode_connected_tls_clients:100
```

## 使用 Openssl (Memcached) 連線至已啟用傳輸中加密的節點
<a name="in-transit-encryption-connect-mc"></a>

若要從啟用傳輸中加密的 ElastiCache for Memcached 節點存取資料，需使用可與 Secure Sockets Layer (SSL) 搭配的用戶端。您也可以在 Amazo Linux 和 Amazo Linux 2 上使用 Openssl s\$1client。

在 Amazo Linux 或 Amazo Linux 2 上，使用 Openssl s\$1client 來連線到啟用傳輸中加密的 Memcached 叢集：

```
/usr/bin/openssl s_client -connect memcached-node-endpoint:memcached-port
```

## 使用 Java 建立 TLS Memcached 用戶端
<a name="in-transit-encryption-connect-java"></a>

若要在 TLS 模式下建立用戶端，請執行下列操作，使用適當的 SSLContext 來初始化用戶端：

```
import java.security.KeyStore;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import net.spy.memcached.AddrUtil;
import net.spy.memcached.ConnectionFactoryBuilder;
import net.spy.memcached.MemcachedClient;
public class TLSDemo {
    public static void main(String[] args) throws Exception {
        ConnectionFactoryBuilder connectionFactoryBuilder = new ConnectionFactoryBuilder();
        // Build SSLContext
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init((KeyStore) null);
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, tmf.getTrustManagers(), null);
        // Create the client in TLS mode
        connectionFactoryBuilder.setSSLContext(sslContext);
        MemcachedClient client = new MemcachedClient(connectionFactoryBuilder.build(), AddrUtil.getAddresses("mycluster.fnjyzo.cfg.use1.cache.amazonaws.com:11211"));

        // Store a data item for an hour.
        client.set("theKey", 3600, "This is the data value");
    }
}
```

## 使用 PHP 建立 TLS Memcached 用戶端
<a name="in-transit-encryption-connect-php-mc"></a>

若要在 TLS 模式下建立用戶端，請執行下列操作，使用適當的 SSLContext 來初始化用戶端：

```
<?php

/**
 * Sample PHP code to show how to create a TLS Memcached client. In this example we
 * will use the Amazon ElastiCache Auto Descovery feature, but TLS can also be
 * used with a Static mode client. 
 * See Using the ElastiCache Cluster Client for PHP (https://docs.aws.amazon.com/AmazonElastiCache/latest/dg/AutoDiscovery.Using.ModifyApp.PHP.html) for more information 
 * about Auto Discovery and persistent-id.
 */

/* Configuration endpoint to use to initialize memcached client.
 * this is only an example */
$server_endpoint = "mycluster.fnjyzo.cfg.use1.cache.amazonaws.com";

/* Port for connecting to the cluster. 
 * This is only an example     */
$server_port = 11211;

/* Initialize a persistent Memcached client and configure it with the Dynamic client mode  */
$tls_client =  new Memcached('persistent-id');
$tls_client->setOption(Memcached::OPT_CLIENT_MODE, Memcached::DYNAMIC_CLIENT_MODE);

/* Add the memcached's cluster server/s */
$tls_client->addServer($server_endpoint, $server_port);

/* Configure the client to use TLS */
if(!$tls_client->setOption(Memcached::OPT_USE_TLS, 1)) {
    echo $tls_client->getLastErrorMessage(), "\n";
    exit(1);
}

/* Set your TLS context configurations values.
 * See MemcachedTLSContextConfig in memcached-api.php for all configurations */
$tls_config = new MemcachedTLSContextConfig();
$tls_config->hostname = '*.mycluster.fnjyzo.use1.cache.amazonaws.com';
$tls_config->skip_cert_verify = false;
$tls_config->skip_hostname_verify = false;

/* Use the created TLS context configuration object to create OpenSSL's SSL_CTX and set it to your client.
 * Note:  These TLS context configurations will be applied to all the servers connected to this client. */
$tls_client->createAndSetTLSContext((array)$tls_config);

/* test the TLS connection with set-get scenario: */

 /* store the data for 60 seconds in the cluster.
 * The client will decide which cache host will store this item.
 */
if($tls_client->set('key', 'value', 60)) {
    print "Successfully stored key\n";
} else {
    echo "Failed to set key: ", $tls_client->getLastErrorMessage(), "\n";
    exit(1);
}

/* retrieve the key */
if ($tls_client->get('key') === 'value') {
    print "Successfully retrieved key\n";
} else {
    echo "Failed to get key: ", $tls_client->getLastErrorMessage(), "\n";
    exit(1);
}
```

如需使用 PHP 用戶端的詳細資訊，請參閱[安裝適用於 PHP 的 ElastiCache 叢集用戶端](Appendix.PHPAutoDiscoverySetup.md)。

# ElastiCache 中的靜態加密
<a name="at-rest-encryption"></a>

為了協助保護您的資料安全，Amazon ElastiCache 和 Amazon S3 提供不同方式，可用於限制存取位於快取中資料。如需詳細資訊，請參閱[Amazon VPC 和 ElastiCache 安全性](VPCs.md)及[Amazon ElastiCache 中的 Identity and Access Management](IAM.md)。

ElastiCache 靜態加密功能可透過加密磁碟上的資料來提高資料安全性。此功能在無伺服器快取上一律為啟用狀態。啟用時，此功能會加密下列層面：
+ 同步、備份和交換操作期間的磁碟
+ 存放在 Amazon S3 中的備份 

儲存在 SSD (固態硬碟) 上已啟用資料分層之叢集中的資料一律會加密。

 ElastiCache 提供靜態預設 （服務受管） 加密，以及能夠在 Key Management Service (KMS) 中使用您自己的對稱客戶受管AWS KMS 金鑰。 [AWS](https://docs.aws.amazon.com/kms/latest/developerguide/overview.html)備份快取後，在加密選項中，選擇要使用預設加密金鑰或客戶受管金鑰。如需詳細資訊，請參閱[啟用靜態加密](#at-rest-encryption-enable)。

**重要**  
在現有的節點型 Valkey 或 Redis OSS 叢集上啟用靜態加密涉及在複寫群組上執行備份和還原**之後**刪除現有的複寫群組。

只有在快取上建立複寫群組後，才能啟用靜態加密。因為要加密和解密資料需要經過一些處理，因此在這些操作期間啟用靜態加密可能會影響效能。您應該針對使用靜態加密和未使用靜態加密的資料進行基準分析，以判斷對使用案例的效能影響。

**Topics**
+ [靜態加密條件](#at-rest-encryption-constraints)
+ [從AWS KMS 使用客戶受管金鑰](#using-customer-managed-keys-for-elasticache-security)
+ [啟用靜態加密](#at-rest-encryption-enable)
+ [另請參閱](#at-rest-encryption-see-also)

## 靜態加密條件
<a name="at-rest-encryption-constraints"></a>

規劃 ElastiCache 靜態加密實作時，應謹記下列 ElastiCache 靜態加密的限制：
+ 執行 Valkey 7.2 和更新版本以及 Redis OSS 版本 （為 EOL 排程 3.2.6，請參閱 [Redis OSS 版本生命週期結束排程](engine-versions.md#deprecated-engine-versions))、4.0.10 或更新版本的複寫群組支援靜態加密。
+ 只有在 Amazon VPC 中執行的複寫群組支援靜態加密。
+ 靜態加密僅支援執行下列節點類型的複寫群組。
  + R7g, R6gd, R6g, R5, R4, R3
  + M7g, M6g, M5, M4, M3
  + T4g、T3、T2
  + C7gn

  如需詳細資訊，請參閱[支援的節點類型](CacheNodes.SupportedTypes.md)
+ 透過將參數 `AtRestEncryptionEnabled` 明確設定為 `true`，可啟用靜態加密。
+ 您只能在建立複寫群組時，於複寫群組上啟用靜態加密。您無法透過修改複寫群組來將靜態加密切換為開啟和關閉。如需如何在現有複寫群組上實作靜態加密的資訊，請參閱[啟用靜態加密](#at-rest-encryption-enable)。
+ 如果叢集使用 r6gd 系列的節點類型，則無論是否啟用靜態加密，存放在 SSD 上的資料都會加密。
+ 使用客戶受管金鑰進行靜態加密的選項不適用於AWS GovCloud (us-gov-east-1 和 us-gov-west-1) 區域。
+ 如果叢集使用來自 r6gd 系列的節點類型，儲存在 SSD 上的資料會使用所選的客戶受管AWS KMS 金鑰 （或服務受管加密 in AWS GovCloud 區域） 加密。
+ 使用 Memcached 時，僅無伺服器快取支援靜態加密。
+ 使用 Memcached 時， GovCloud (us-gov-east-1 和 us-gov-west-1) 區域不提供AWS使用客戶受管金鑰進行靜態加密的選項。

實作靜態加密可能會在備份和節點同步操作期間降低效能。針對您自己的資料進行靜態加密與無加密的基準分析比較，以判斷對實作的效能影響。

## 從AWS KMS 使用客戶受管金鑰
<a name="using-customer-managed-keys-for-elasticache-security"></a>

ElastiCache 支援對稱客戶受管AWS KMS 金鑰 (KMS 金鑰） 進行靜態加密。客戶受管 KMS 金鑰是您在AWS帳戶中建立、擁有和管理的加密金鑰。如需詳細資訊，請參閱 *AWS Key Management Service 開發人員指南*中的 [AWS KMS 金鑰](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#root_keys)。金鑰必須先在AWS KMS 中建立，才能與 ElastiCache 搭配使用。

若要了解如何建立AWS KMS 根金鑰，請參閱 [Key Management Service 開發人員指南中的建立](https://docs.aws.amazon.com/kms/latest/developerguide/create-keys.html)*AWS金鑰*。

ElastiCache 可讓您與AWS KMS 整合。如需詳細資訊，請參閱 *AWS Key Management Service 開發人員指南*中的[使用授權](https://docs.aws.amazon.com/kms/latest/developerguide/grants.html)。不需要客戶動作即可啟用與AWS KMS 的 Amazon ElastiCache 整合。

`kms:ViaService` 條件金鑰會將AWS KMS 金鑰 (KMS 金鑰） 的使用限制為來自指定AWS服務的請求。若要搭配 ElastiCache 使用 `kms:ViaService`，請在條件索引鍵值中包含兩個 ViaService 名稱：`elasticache.AWS_region.amazonaws.com` 和 `dax.AWS_region.amazonaws.com`。如需詳細資訊，請參閱 [kms:ViaService](https://docs.aws.amazon.com/kms/latest/developerguide/policy-conditions.html#conditions-kms-via-service)。

您可以使用 [AWS CloudTrail](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-user-guide.html) 來追蹤 Amazon ElastiCache 代表您傳送給AWS Key Management Service的請求。所有與客戶受管金鑰AWS Key Management Service相關的 API 呼叫都有對應的 CloudTrail 日誌。您也可以透過呼叫 [ListGrants](https://docs.aws.amazon.com/kms/latest/APIReference/API_ListGrants.html) KMS API 呼叫來查看 ElastiCache 建立的授與。

使用客戶受管金鑰對複寫群組進行加密後，複寫群組的所有備份都會依以下方式進行加密：
+ 自動每日備份會使用與叢集關聯的客戶受管金鑰來進行加密。
+ 複寫群組被刪除時所建立的最終備份，也使用與複寫群組關聯的客戶受管金鑰進行加密。
+ 手動建立的備份在預設情況下，會使用與複寫群組關聯的金鑰來加密。您可以透過選擇其他客戶受管金鑰來覆寫此選項。
+ 複製備份預設為使用與來源備份關聯的客戶受管金鑰。您可以透過選擇其他客戶受管金鑰來覆寫此選項。

**注意**  
將備份匯出到所選 Amazon S3 儲存貯體時，無法使用客戶受管金鑰。不過，匯出至 Amazon S3 的所有備份都使用[伺服器端加密](https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingServerSideEncryption.html)來加密。您可以選擇將備份檔案複製到新的 S3 物件並使用客戶受管 KMS 金鑰來加密、將檔案複製到使用 KMS 金鑰以預設加密設定的另一個 S3 儲存貯體，或是變更檔案本身的加密選項。
您也可以使用客戶受管金鑰，為不是使用客戶受管金鑰進行加密的複寫群組，加密手動建立的備份。使用此選項時，即使原始複寫群組上的資料未加密，Amazon S3 中存放的備份檔案仍會使用 KMS 金鑰來進行加密。
從備份還原可讓您從可用的加密選項中進行選擇，類似於建立新複寫群組時可用的加密選項。
+ 如果刪除金鑰或[停用](https://docs.aws.amazon.com/kms/latest/developerguide/enabling-keys.html)金鑰，並針對您用來加密快取的金鑰[撤銷授權](https://docs.aws.amazon.com/kms/latest/APIReference/API_RevokeGrant.html)，則快取將變成無法恢復。換句話說，它無法在硬體故障後修改或復原。AWS KMS 只會在等待至少七天後刪除根金鑰。金鑰刪除後，您可以使用其他客戶受管金鑰建立備份以用於封存。
+ 自動金鑰輪換會保留AWS KMS 根金鑰的屬性，因此輪換不會影響您存取 ElastiCache 資料的能力。加密的 Amazon ElastiCache 快取不支援手動金鑰輪換，其中包含建立新的根金鑰和更新任何舊金鑰的參照。若要進一步了解，請參閱 Key *AWS Management Service 開發人員指南*中的[輪換AWS KMS 金鑰](https://docs.aws.amazon.com/kms/latest/developerguide/rotate-keys.html)。
+ 每個快取都需有一個授權，才能使用 KMS 金鑰加密 ElastiCache 快取。此授權將在快取的整個生命週期中使用。此外，在備份建立期間，每個備份會使用一個授權。建立備份後，此授權就會淘汰。
+ 如需AWS KMS 授予和限制的詳細資訊，請參閱 *AWS Key Management Service 開發人員指南*中的[限制](https://docs.aws.amazon.com/kms/latest/developerguide/limits.html)。

## 啟用靜態加密
<a name="at-rest-encryption-enable"></a>

所有無伺服器快取都會啟用靜態加密。

建立節點型叢集時，您可以將 參數設定為 `AtRestEncryptionEnabled` ，以啟用靜態加密`true`。您無法在現有複寫群組上啟用靜態加密。

 您可在建立 ElastiCache 快取時啟用靜態加密。您可以使用AWS 管理主控台、AWS CLI或 ElastiCache API 來執行此操作。

建立快取時，您可以選擇下列其中一個選項：
+ **預設** – 此選項使用服務管理的靜態加密。
+ **客戶受管金鑰 ** – 此選項可讓您從AWS KMS 提供金鑰 ID/ARN 以進行靜態加密。

若要了解如何建立AWS KMS 根金鑰，請參閱 [Key Management Service 開發人員指南中的建立](https://docs.aws.amazon.com/kms/latest/developerguide/create-keys.html)*AWS金鑰* 

**Contents**
+ [使用 啟用靜態加密AWS 管理主控台](#at-rest-encryption-enable-con)
+ [使用 啟用靜態加密AWS CLI](#at-rest-encryption-enable-cli)

### 在現有的節點型 Valkey 或 Redis OSS 叢集上啟用靜態加密
<a name="at-reset-encryption-enable-existing-cluster"></a>

您只能在建立 Valkey 或 Redis OSS 複寫群組時啟用靜態加密。如果您想要啟用現有複寫群組的靜態加密，請執行下列動作。

**啟用現有複寫群組的靜態加密**

1. 建立您現有複寫群組的手動備份。如需詳細資訊，請參閱「[取得手動備份](backups-manual.md)」。

1. 透過從備份還原來建立新的複寫群組。在新的複寫群組上，啟用靜態加密。如需詳細資訊，請參閱[從備份還原到新的快取](backups-restoring.md)。

1. 更新應用程式中的端點以指向新的複寫群組。

1. 刪除舊的複寫群組。如需詳細資訊，請參閱 [在 ElastiCache 中刪除叢集](Clusters.Delete.md) 或 [刪除複寫群組](Replication.DeletingRepGroup.md) 。

### 使用 啟用靜態加密AWS 管理主控台
<a name="at-rest-encryption-enable-con"></a>

#### 在無伺服器快取上啟用靜態加密 (主控台)
<a name="at-rest-encryption-enable-con-serverless"></a>

所有無伺服器快取都會啟用靜態加密。根據預設， 擁有AWS的 KMS 金鑰會用來加密資料。若要選擇您自己的AWS KMS金鑰，請進行下列選擇：
+ 展開**預設設定**區段。
+ 在**預設設定**區段下選擇**自訂預設設定**。
+ 在**安全性**區段下選擇**自訂安全性設定**。
+ 在**加密金鑰**設定下選擇**客戶受管 CMK**。
+ 在 **AWS KMS金鑰**設定下選擇一個金鑰。

#### 在以節點為基礎的叢集上啟用靜態加密 （主控台）
<a name="at-rest-encryption-enable-con-self-designed"></a>

自行設計快取時，採用「輕鬆建立」方法的「開發/測試」和「生產」組態會使用**預設**金鑰啟用靜態加密。當您自行選擇組態時，請進行下列選擇：
+ 選擇 3.2.6、4.0.10 或更新版本做為引擎版本。
+ 按一下**靜態加密**選項的**啟用**旁的核取方塊。
+ 選擇**預設金鑰**或**客戶受管 CMK**。

如需逐步操作程序，請參閱下列：
+ [建立 Valkey （停用叢集模式） 叢集 （主控台）](SubnetGroups.designing-cluster-pre.valkey.md#Clusters.Create.CON.valkey-gs)
+ [建立 Valkey 或 Redis OSS （啟用叢集模式） 叢集 （主控台）](Clusters.Create.md#Clusters.Create.CON.RedisCluster)

### 使用 啟用靜態加密AWS CLI
<a name="at-rest-encryption-enable-cli"></a>

若要在使用 建立 Valkey 或 Redis OSS 叢集時啟用靜態加密AWS CLI，請在建立複寫群組時使用 *--at-rest-encryption-enabled* 參數。

#### 在 Valkey 或 Redis OSS （停用叢集模式） 叢集 (CLI) 上啟用靜態加密
<a name="at-rest-encryption-enable-cli-redis-classic-rg"></a>

下列操作會建立`my-classic-rg`具有三個節點 (*--num-cache-clusters*)、主要複本和兩個僅供讀取複本的 Valkey 或 Redis OSS （停用叢集模式） 複寫群組。此複寫群組 (*--at-rest-encryption-enabled*) 的靜態加密已啟用。

若要啟用此複寫群組的加密，您必須使用下列參數和值：

**重要參數**
+ **--engine**- 必須為 `valkey`或 `redis`。
+ **--engine-version**- 如果引擎是 Redis OSS，這必須是 3.2.6、4.0.10 或更新版本。
+ **--at-rest-encryption-enabled** - 啟用靜態加密的必要項目。

**Example 1：Valkey 或 Redis OSS （停用叢集模式） 叢集與複本**  
針對 Linux、macOS 或 Unix：  

```
aws elasticache create-replication-group \
    --replication-group-id my-classic-rg \
    --replication-group-description "3 node replication group" \
    --cache-node-type cache.m4.large \
    --engine redis \    
    --at-rest-encryption-enabled \  
    --num-cache-clusters 3
```
針對 Windows：  

```
aws elasticache create-replication-group ^
    --replication-group-id my-classic-rg ^
    --replication-group-description "3 node replication group" ^
    --cache-node-type cache.m4.large ^
    --engine redis ^    
    --at-rest-encryption-enabled ^  
    --num-cache-clusters 3 ^
```

如需其他資訊，請參閱以下內容：
+ [從頭開始建立 Valkey 或 Redis OSS （停用叢集模式） 複寫群組 (AWS CLI)](Replication.CreatingReplGroup.NoExistingCluster.Classic.md#Replication.CreatingReplGroup.NoExistingCluster.Classic.CLI)
+ [create-replication-group](https://docs.aws.amazon.com/cli/latest/reference/elasticache/create-replication-group.html)

 

#### 在叢集上為 Valkey 或 Redis OSS 啟用靜態加密 （啟用叢集模式） (CLI)
<a name="at-rest-encryption-enable-cli-clustered-redis"></a>

下列操作會建立`my-clustered-rg`具有三個節點群組或碎片 (*--num-node-groups*) 的 Valkey 或 Redis OSS （啟用叢集模式） 複寫群組。每個都有三個節點、一個主要複本及兩個僅供讀取複本 (*--replicas-per-node-group*)。此複寫群組 (*--at-rest-encryption-enabled*) 的靜態加密已啟用。

若要啟用此複寫群組的加密，您必須使用下列參數和值：

**重要參數**
+ **--engine**- 必須為 `valkey`或 `redis`。
+ **--engine-version**- 如果引擎是 Redis OSS，這必須是 4.0.10 或更新版本。
+ **--at-rest-encryption-enabled** - 啟用靜態加密的必要項目。
+ **--cache-parameter-group** - 必須為 `default-redis4.0.cluster.on` 或其衍生項目，才能成為啟用複寫群組的叢集模式。

**Example 2：Valkey 或 Redis OSS （啟用叢集模式） 叢集**  
針對 Linux、macOS 或 Unix：  

```
aws elasticache create-replication-group \
   --replication-group-id my-clustered-rg \
   --replication-group-description "redis clustered cluster" \
   --cache-node-type cache.m3.large \
   --num-node-groups 3 \
   --replicas-per-node-group 2 \
   --engine redis \
   --engine-version 6.2 \
   --at-rest-encryption-enabled \
   --cache-parameter-group default.redis6.x.cluster.on
```
針對 Windows：  

```
aws elasticache create-replication-group ^
   --replication-group-id my-clustered-rg ^
   --replication-group-description "redis clustered cluster" ^
   --cache-node-type cache.m3.large ^
   --num-node-groups 3 ^
   --replicas-per-node-group 2 ^
   --engine redis ^
   --engine-version 6.2 ^
   --at-rest-encryption-enabled ^
   --cache-parameter-group default.redis6.x.cluster.on
```

如需其他資訊，請參閱以下內容：
+ [從頭開始建立 Valkey 或 Redis OSS （啟用叢集模式） 複寫群組 (AWS CLI)](Replication.CreatingReplGroup.NoExistingCluster.Cluster.md#Replication.CreatingReplGroup.NoExistingCluster.Cluster.CLI)
+ [create-replication-group](https://docs.aws.amazon.com/cli/latest/reference/elasticache/create-replication-group.html)

## 另請參閱
<a name="at-rest-encryption-see-also"></a>
+ [Amazon VPC 和 ElastiCache 安全性](VPCs.md)
+ [Amazon ElastiCache 中的 Identity and Access Management](IAM.md)

# 身分驗證和授權
<a name="auth-redis"></a>

AWS Identity and Access Management (IAM) 是一種 Web 服務，可協助您安全地控制對 AWS 資源的存取。ElastiCache 支援使用 IAM 和 Valkey 和 Redis OSS AUTH 命令驗證使用者，以及使用角色型存取控制 (RBAC) 授權使用者操作。

**Topics**
+ [角色型存取控制 (RBAC) 規則數量](Clusters.RBAC.md)
+ [使用 Valkey 和 Redis OSS AUTH 命令進行驗證](auth.md)
+ [在 ElastiCache Valkey 或 Redis OSS 快取上停用存取控制](in-transit-encryption-disable.md)

# 角色型存取控制 (RBAC) 規則數量
<a name="Clusters.RBAC"></a>

透過中所述的 Valkey 和 Redis OSS AUTH 命令[使用 Valkey 和 Redis OSS AUTH 命令進行驗證](auth.md)，您可以使用角色型存取控制 (RBAC)。RBAC 也是控制無伺服器快取存取的唯一方法。這適用於 Valkey 7.2 和更新版本，以及 Redis OSS 6.0 到 7.2。

RBAC 可讓您：
+ 透過使用者群組控制快取存取。這些使用者群組的設計目的是整理快取的存取權。
+ 使用 *authN* 時，每個使用者密碼具有 ，而不是每個叢集驗證字符。
+ 使用 *authZ* 時， 具有精細的使用者許可。
+ 以 ACLs為基礎存取叢集。

與 Valkey 和 Redis OSS AUTH 不同，其中所有已驗證的用戶端都具有完整快取存取權，如果其權杖已驗證，RBAC 可讓您根據使用者所需的角色指派使用者進行設定。這些集旨在組織對快取的存取。

使用 RBAC，您可以建立使用者，並使用存取字串將特定許可指派給他們，如下所說明。您可以將使用者指派給與特定角色 （管理員、人力資源） 一致的集合，然後部署到一或多個 ElastiCache 快取。透過這樣做，您可以在使用相同 Valkey 或 Redis OSS 快取的用戶端之間建立安全界限，並防止用戶端存取彼此的資料。

RBAC 旨在支援在 Redis OSS 6 中引入 [ACL](https://valkey.io/topics/acl/)。當您搭配 ElastiCache Valkey 或 Redis OSS 快取使用 RBAC 時，有一些限制：
+ 針對「VALKEY」引擎設定的使用者群組只能包含使用身分驗證機制 （密碼或 IAM) 的使用者。這表示具有引擎「VALKEY」的所有使用者，以及具有引擎「Redis」且其設定設定為使用密碼或 IAM 進行身分驗證的任何其他使用者，都可以在此使用者群組中。
+ 搭配 Valkey 叢集使用 RBAC 時，可以使用引擎「VALKEY」和引擎「REDIS」的兩個使用者群組。
+ 將 RBAC 與 Redis OSS 叢集搭配使用時，只能使用具有引擎 "REDIS" 的使用者群組。
+ 您無法在存取字串中指定密碼。您可以使用 [CreateUser](https://docs.aws.amazon.com/AmazonElastiCache/latest/APIReference/API_CreateUser.html) 或 [ModifyUser](https://docs.aws.amazon.com/AmazonElastiCache/latest/APIReference/API_ModifyUser.html) 呼叫來設定密碼。
+ 對於使用者權限，您可以使用 `on`和 啟用或停用使用者`off`，做為存取字串的一部分。如果存取字串中沒有指定這兩項，則會為使用者指派 `off`，且使用者沒有快取的存取權限。
+ 您無法使用禁止和重新命名的命令做為存取字串的一部分。如果您指定禁止或重新命名的命令，則會擲回例外情況。如果您想要將存取控制清單 (ACL) 用於重新命名的命令，請指定命令的原始名稱，也就是將命令重新命名之前的名稱。
+ 您無法使用 `reset` 命令作為存取字串的一部分。您可以使用 API 參數指定密碼，ElastiCache for Valkey 和 Redis OSS 會管理密碼。因此您無法使用 `reset`，因為它會刪除使用者的所有密碼。
+ Redis OSS 6 推出 [ACL LIST](https://valkey.io/commands/acl-list) 命令。此命令會傳回使用者清單，以及套用至每個使用者的 ACL 規則。ElastiCache 支援 `ACL LIST`命令，但不像 Redis OSS 一樣包含對密碼雜湊的支援。使用 ElastiCache，您可以使用 [DescribeUsers](https://docs.aws.amazon.com/AmazonElastiCache/latest/APIReference/API_DescribeUsers.html) 操作來取得類似資訊，包括存取字串中包含的規則。不過，[DescribeUsers](https://docs.aws.amazon.com/AmazonElastiCache/latest/APIReference/API_DescribeUsers.html) 不會擷取使用者密碼。
+ ElastiCache for Valkey 和 Redis OSS 支援的其他唯讀命令包括 [ACL WHOAMI](https://valkey.io/commands/acl-whoami)、[ACL USERS](https://valkey.io/commands/acl-users) 和 [ACL CAT](https://valkey.io/commands/acl-cat)。ElastiCache for Valkey 和 Redis OSS 不支援任何其他以寫入為基礎的 ACL 命令。
+ 適用下列限制：    
<a name="quotas-table"></a>[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/AmazonElastiCache/latest/dg/Clusters.RBAC.html)

**RBAC 搭配 Valkey**

搭配 Valkey 使用角色型存取控制時，使用者和使用者群組會使用「VALKEY」引擎類型建立。建議使用，因為根據預設，與 Redis OSS 相比，具有 RBAC 的 Valkey 可提供更高的安全性。佈建和無伺服器 Valkey 叢集都支援 VALKEY 使用者和使用者群組關聯。

Valkey 存取控制的主要功能包括：
+ Valkey 使用者僅限於 Valkey 使用者群組關聯。
+ Valkey 使用者群組可以包含 Valkey 使用者，以及受密碼保護或啟用 IAM 驗證的 Redis OSS 使用者。
+ Valkey 使用者必須使用密碼保護或 IAM 身分驗證。
+ VALKEY 使用者群組只能與 VALKEY 叢集建立關聯
+ 沒有預設的使用者需求。當 Valkey 使用者群組連接到叢集時，預設使用者需求會自動停用。使用 ACL LIST 命令時，客戶會看到預設使用者已關閉。

以下是搭配 ElastiCache for Valkey 和 Redis OSS 使用 RBAC 的詳細資訊。

**Topics**
+ [使用存取字串指定許可](#Access-string)
+ [將 RBAC 套用至 ElastiCache for Valkey 或 Redis OSS 的快取](#rbac-using)
+ [從 AUTH 遷移至 RBAC](#Migrate-From-RBAC-to-Auth)
+ [從 RBAC 遷移至 AUTH](#Migrate-From-RBAC-to-AUTH-1)
+ [自動輪換使用者密碼](User-Secrets-Manager.md)
+ [以 IAM 進行身分驗證](auth-iam.md)

## 使用存取字串指定許可
<a name="Access-string"></a>

若要指定 ElastiCache Valkey 或 Redis OSS 快取的許可，您可以建立存取字串，並透過AWS CLI或 將其指派給使用者AWS 管理主控台。

存取字串的定義是套用至使用者的空格分隔規則清單。用於定義使用者可以執行哪些命令，以及使用者可以操作哪些索引鍵。為了執行命令，使用者必須能存取執行中的命令以及該命令存取的所有索引鍵。規則會從左到右累積套用，如果提供的字串中存在冗餘項目，可以改用更簡單的字串而非提供的字串。

如需 ACL 規則語法的詳細資訊，請參閱 [ACL](https://valkey.io/topics/acl/)。

在下列範例中，存取字串代表有權存取所有可用索引鍵和命令的活躍使用者。

 `on ~* +@all`

存取字串語法可細分以下各項：
+ `on` - 使用者是活躍使用者。
+ `~*` - 存取權限提供給所有可用的索引鍵。
+ `+@all` - 存取權限提供給所有可用的命令。

先前的設定受到最低限度的限制。您可以修改這些設定，提高安全性。

在下面的範例中，存取字串代表對於以「app::」keyspace 開頭的索引鍵，存取權受限於讀取存取的使用者

`on ~app::* -@all +@read`

您可以列出使用者可存取的命令，進一步精簡這些許可：

`+command1` - 使用者對命令的存取權限受限於 *`command1`*。

 `+@category` - 使用者的存取權限受限於某個命令類別。

如需將存取字串指派給使用者的相關資訊，請參閱「[使用主控台和 CLI 建立使用者和使用者群組](#Users-management)」。

如果您要將現有的工作負載遷移至 ElastiCache，您可以透過呼叫 `ACL LIST` 來擷取存取字串，並排除使用者和任何密碼雜湊。

針對 Redis OSS 6.2 版及更新版本，也支援下列存取字串語法：
+ `&*` - 存取權限提供給所有可用的索引鍵。

針對 Redis OSS 7.0 版及更新版本，也支援下列存取字串語法：
+ `|` – 可用於封鎖子命令 (例如「-config\$1set」）。
+ `%R~<pattern>` – 新增指定的讀取金鑰模式。這與常態金鑰模式類似，但僅授予符合特定模式的金鑰讀取許可。如需詳細資訊，請參閱[金鑰許可](https://valkey.io/topics/acl/)。
+ `%W~<pattern>` – 新增指定的寫入金鑰模式。這與常態金鑰模式類似，但僅授予符合特定模式的金鑰寫入許可。如需詳細資訊，請參閱 [ACL 金鑰許可](https://valkey.io/topics/acl/)。
+ `%RW~<pattern>` – `~<pattern>` 的別名。
+ `(<rule list>)` – 建立新的選擇器以配對規則。選擇器會在使用者許可之後受到評估，並根據其定義的順序進行評估。如果命令符合使用者許可或任何選擇器，則允許該命令。如需詳細資訊，請參閱 [ACL selectors](https://valkey.io/topics/acl/) (ACL 選擇器)。
+ `clearselectors` – 刪除所有連接到使用者的選擇器。

## 將 RBAC 套用至 ElastiCache for Valkey 或 Redis OSS 的快取
<a name="rbac-using"></a>

若要使用 ElastiCache for Valkey 或 Redis OSS RBAC，請執行下列步驟：

1. 建立一或多位使用者。

1. 建立使用者群組，並為該群組新增使用者。

1. 將使用者群組指派給啟用傳輸中加密的快取。

這些步驟詳細說明如下。

**Topics**
+ [使用主控台和 CLI 建立使用者和使用者群組](#Users-management)
+ [使用主控台和 CLI 管理使用者群組](#User-Groups)
+ [將使用者群組指派至無伺服器快取](#Users-groups-to-serverless-caches)
+ [將使用者群組指派給複寫群組](#Users-groups-to-RGs)

### 使用主控台和 CLI 建立使用者和使用者群組
<a name="Users-management"></a>

RBAC 使用者的使用者資訊是使用者 ID、使用者名稱，以及選用的密碼和存取字串。存取字串提供索引鍵和命令的許可層級。使用者 ID 對使用者而言是唯一的，而使用者名稱是傳遞給引擎的內容。

請確定您提供的使用者許可對使用者群組的預期用途來說有意義。例如，如果您建立名為 `Administrators` 的使用者群組，則您新增至該群組的任何使用者都應該將其存取字串設為完整存取索引鍵和命令。針對 `e-commerce` 使用者群組中的，您可以將其存取字串設為唯讀存取。

ElastiCache 會以使用者 ID 和使用者名稱 `"default"` 自動設定預設使用者，並將其新增至所有使用者群組。您無法刪除或修改此使用者。此使用者旨在與先前 Redis OSS 版本的預設行為相容，並具有允許其呼叫所有命令和存取所有金鑰的存取字串。

若要將適當的存取控制新增至快取，請將此預設使用者取代為未啟用或未使用高強度密碼的新使用者。若要變更預設使用者，請將使用者名稱設定為 `default`。然後您可以將其與原始預設使用者交換。

下列程序說明如何交換原始 `default` 使用者與具有經修改存取字串的另一個 `default` 使用者。

**在主控台上修改預設使用者**

1. 登入AWS 管理主控台，並在 [https://console.aws.amazon.com/elasticache/](https://console.aws.amazon.com/elasticache/)：// 開啟 Amazon ElastiCache 主控台。

1. 從導覽窗格選擇**使用者群組管理**。

1. 針對**使用者群組 ID**，選擇您要修改的 ID。確定您選擇的是連結而非核取方塊。

1. 選擇 **Modify** (修改)。

1. 在**修改**視窗中，選擇**管理**。對於「選取您想要的使用者」，選取**使用者名稱**為預設值的使用者。

1. 選擇 **Choose (選擇)**。

1. 選擇 **Modify** (修改)。執行這項操作時，原始預設使用者所擁有的任何現有快取連線都會終止。

**使用 修改預設使用者AWS CLI**

1. 使用以下命令以使用者名稱 `default` 建立新使用者。

   針對 Linux、macOS 或 Unix：

   ```
   aws elasticache create-user \
    --user-id "new-default-user" \
    --user-name "default" \
    --engine "VALKEY" \
    --passwords "a-str0ng-pa))word" \
    --access-string "off +get ~keys*"
   ```

   針對 Windows：

   ```
   aws elasticache create-user ^
    --user-id "new-default-user" ^
    --user-name "default" ^
    --engine "VALKEY" ^
    --passwords "a-str0ng-pa))word" ^
    --access-string "off +get ~keys*"
   ```

1. 建立使用者群組並新增先前建立的使用者。

   針對 Linux、macOS 或 Unix：

   ```
   aws elasticache create-user-group \
     --user-group-id "new-group-2" \
     --engine "VALKEY" \
     --user-ids "new-default-user"
   ```

   針對 Windows：

   ```
   aws elasticache create-user-group ^
     --user-group-id "new-group-2" ^
     --engine "VALKEY" ^
     --user-ids "new-default-user"
   ```

建立使用者時，最多可以設定兩個密碼。修改密碼時，任何現有的快取連線都會保留。

特別是，在使用 RBAC for ElastiCache for Valkey 和 Redis OSS 時，請注意這些使用者密碼限制：
+ 密碼必須為 16 - 128 個可列印字元。
+ 不允許使用以下非英數字元：`,` `""` `/` `@`。

#### 使用主控台和 CLI 管理使用者
<a name="Users-console"></a>

透過下列程序，在主控台上管理使用者。

**在主控台上管理使用者**

1. 登入AWS 管理主控台，並在 [https://console.aws.amazon.com/elasticache/](https://console.aws.amazon.com/elasticache/)：// 開啟 Amazon ElastiCache 主控台。

1. 在 Amazon ElastiCache 儀表板上，選擇**使用者管理**。下列選項可供使用：
   + **建立使用者** - 建立使用者時，您需輸入使用者 ID、使用者名稱、身分驗證模式和存取字串。存取字串會為允許使用者存取的索引鍵和命令設定許可層級。

     建立使用者時，最多可以設定兩個密碼。修改密碼時，任何現有的快取連線都會保留。
   + **修改使用者** - 可讓您更新使用者的身分驗證設定或變更其存取字串。
   + **刪除使用者** - 將帳戶從其所屬的任何使用者群組中移除。

透過下列程序，使用AWS CLI來管理使用者。

**使用 CLI 修改使用者**
+  使用 `modify-user` 命令來更新使用者的密碼或密碼，或變更使用者的存取許可。

  修改使用者時，會更新與使用者相關聯的使用者群組，以及與使用者群組相關聯的任何快取。所有現有的連線都會保留。範例如下。

  針對 Linux、macOS 或 Unix：

  ```
  aws elasticache modify-user \
    --user-id user-id-1 \
    --access-string "~objects:* ~items:* ~public:*" \
    --authentication-mode Type=iam
  ```

  針對 Windows：

  ```
  aws elasticache modify-user ^
    --user-id user-id-1 ^
    --access-string "~objects:* ~items:* ~public:*" ^
    --authentication-mode Type=iam
  ```

**注意**  
不建議您使用 `nopass` 選項。如果您使用此選項，建議將使用者的許可設定為唯讀，並提供一組有限索引鍵的存取權。

**使用 CLI 刪除使用者**
+ 使用 `delete-user` 命令來刪除使用者。系統會刪除帳戶，並將其從所屬的任何使用者群組中移除。下列是 範例。

  針對 Linux、macOS 或 Unix：

  ```
  aws elasticache delete-user \
    --user-id user-id-2
  ```

  針對 Windows：

  ```
  aws elasticache delete-user ^
    --user-id user-id-2
  ```

若要查看使用者清單，請呼叫 [describe-users](https://docs.aws.amazon.com/cli/latest/reference/elasticache/describe-users.html) 作業。

```
aws elasticache describe-users
```

### 使用主控台和 CLI 管理使用者群組
<a name="User-Groups"></a>

您可以建立使用者群組來整理和控制使用者對一或多個快取的存取權，如下所示。

透過下列程序，使用主控台來管理使用者群組。

**使用主控台來管理使用者群組**

1. 登入AWS 管理主控台，並在 [https://console.aws.amazon.com/elasticache/](https://console.aws.amazon.com/elasticache/)：// 開啟 Amazon ElastiCache 主控台。

1. 在 Amazon ElastiCache 儀表板上，選擇**使用者群組管理**。

   可透過以下作業來建立新的使用者群組：
   + **建立** - 建立使用者群組時，您需新增使用者，然後將使用者群組指派給快取。例如，您可以為具有快取管理角色的使用者建立 `Admin` 使用者群組。
**重要**  
如果您不是使用 Valkey 或 Redis OSS 使用者群組，則必須在建立使用者群組時包含預設使用者。
   + **新增使用者** - 將使用者新增至使用者群組。
   + **移除使用者** - 從使用者群組中刪除使用者。將使用者從使用者群組中移除時，他們所擁有的任何現有快取連線都會終止。
   + **刪除** - 用來來刪除使用者群組。請注意，系統會刪除使用者群組本身，而不是屬於該群組的使用者。

   針對現有的使用者群組，您可以執行以下操作：
   + **新增使用者** - 將現有使用者新增到使用者群組中。
   + **刪除使用者** - 從使用者群組中移除現有使用者。
**注意**  
使用者會從使用者群組中移除，但不會從系統中刪除。

透過下列程序，使用 CLI 來管理使用者群組。

**使用 CLI 建立新的使用者群組並新增使用者**
+ 請使用 `create-user-group` 命令，如下列所示。

  針對 Linux、macOS 或 Unix：

  ```
  aws elasticache create-user-group \
    --user-group-id "new-group-1" \
    --engine "VALKEY" \
    --user-ids user-id-1, user-id-2
  ```

  針對 Windows：

  ```
  aws elasticache create-user-group ^
    --user-group-id "new-group-1" ^
    --engine "VALKEY" ^
    --user-ids user-id-1, user-id-2
  ```

**使用 CLI 新增使用者或移除目前成員來修改使用者群組**
+ 請使用 `modify-user-group` 命令，如下列所示。

  針對 Linux、macOS 或 Unix：

  ```
  aws elasticache modify-user-group --user-group-id new-group-1 \
  --user-ids-to-add user-id-3 \
  --user-ids-to-remove user-id-2
  ```

  針對 Windows：

  ```
  aws elasticache modify-user-group --user-group-id new-group-1 ^
  --user-ids-to-add user-id-3 ^
  --user-ids-to-removere user-id-2
  ```

**注意**  
屬於從使用者群組中移除之使用者的任何開啟連線，都會以此命令結束。

**使用 CLI 刪除使用者群組**
+ 請使用 `delete-user-group` 命令，如下列所示。系統會刪除使用者群組本身，而不是屬於該群組的使用者。

  針對 Linux、macOS 或 Unix：

  ```
  aws elasticache delete-user-group /
     --user-group-id
  ```

  針對 Windows：

  ```
  aws elasticache delete-user-group ^
     --user-group-id
  ```

若要查看使用者群組清單，您可以呼叫 [describe-user-groups](https://docs.aws.amazon.com/cli/latest/reference/elasticache/describe-user-groups.html) 作業。

```
aws elasticache describe-user-groups \
  --user-group-id test-group
```

### 將使用者群組指派至無伺服器快取
<a name="Users-groups-to-serverless-caches"></a>

建立使用者群組並新增使用者之後，實作 RBAC 的最後一個步驟是將使用者群組指派至無伺服器快取。

#### 使用主控台將使用者群組指派至無伺服器快取
<a name="Users-groups-to-SCs-CON"></a>

若要使用 將使用者群組新增至無伺服器快取AWS 管理主控台，請執行下列動作：
+ 如需停用叢集模式，請參閱「[建立 Valkey （停用叢集模式） 叢集 （主控台）](SubnetGroups.designing-cluster-pre.valkey.md#Clusters.Create.CON.valkey-gs)」
+ 如需啟用叢集模式，請參閱「[建立 Valkey 或 Redis OSS （啟用叢集模式） 叢集 （主控台）](Clusters.Create.md#Clusters.Create.CON.RedisCluster)」

#### 使用 將使用者群組指派給無伺服器快取AWS CLI
<a name="Users-groups-to-SCs-CLI"></a>

 下列AWS CLI操作會使用 值為 的 **user-group-id** 參數來建立無伺服器快取`my-user-group-id`。將子網路群組 `sng-test` 取代為已存在的子網路群組。

**重要參數**
+ **--engine** – 必須為 `VALKEY`或 `REDIS`。
+ **--user-group-id** - 此值提供由具有指定的快取存取許可之使用者所組成的使用者群組 ID。

針對 Linux、macOS 或 Unix：

```
aws elasticache create-serverless-cache \
    --serverless-cache-name "new-serverless-cache" \
    --description "new-serverless-cache" \
    --engine "VALKEY" \
    --user-group-id "new-group-1"
```

針對 Windows：

```
aws elasticache create-serverless-cache ^
    --serverless-cache-name "new-serverless-cache" ^
    --description "new-serverless-cache" ^
    --engine "VALKEY" ^
    --user-group-id "new-group-1"
```

下列AWS CLI操作會使用 值為 的 **user-group-id** 參數修改無伺服器快取`my-user-group-id`。

針對 Linux、macOS 或 Unix：

```
aws elasticache modify-serverless-cache \
    --serverless-cache-name serverless-cache-1 \
    --user-group-id "new-group-2"
```

針對 Windows：

```
aws elasticache modify-serverless-cache ^
    --serverless-cache-name serverless-cache-1 ^
    --user-group-id "new-group-2"
```

請注意，對快取所做的任何修改都會以非同步方式更新。您可以透過檢視事件來監控進度。如需詳細資訊，請參閱[檢視 ElastiCache 事件](ECEvents.Viewing.md)。

### 將使用者群組指派給複寫群組
<a name="Users-groups-to-RGs"></a>

建立使用者群組並新增使用者之後，實作 RBAC 的最後一個步驟是將使用者群組指派給複寫群組。

#### 使用主控台將使用者群組指派給複寫群組
<a name="Users-groups-to-RGs-CON"></a>

若要使用 將使用者群組新增至複寫AWS 管理主控台，請執行下列動作：
+ 如需停用叢集模式，請參閱「[建立 Valkey （停用叢集模式） 叢集 （主控台）](SubnetGroups.designing-cluster-pre.valkey.md#Clusters.Create.CON.valkey-gs)」
+ 如需啟用叢集模式，請參閱「[建立 Valkey 或 Redis OSS （啟用叢集模式） 叢集 （主控台）](Clusters.Create.md#Clusters.Create.CON.RedisCluster)」

#### 使用 將使用者群組指派給複寫群組AWS CLI
<a name="Users-groups-to-RGs-CLI"></a>

 下列AWS CLI操作會建立啟用傳輸中加密 (TLS) 的複寫群組，以及值為 的 **user-group-ids** 參數`my-user-group-id`。將子網路群組 `sng-test` 取代為已存在的子網路群組。

**重要參數**
+ **--engine** – 必須為 `valkey`或 `redis`。
+ **--engine-version** – 必須是 6.0 或更新版本。
+ **--transit-encryption-enabled** - 進行身分驗證和為使用者群組建立關聯所需的項目。
+ **--user-group-ids** - 此值提供由具有指定的快取存取許可之使用者所組成的使用者群組 ID。
+ **--cache-subnet-group** - 為使用者群組建立關聯所需的項目。

針對 Linux、macOS 或 Unix：

```
aws elasticache create-replication-group \
    --replication-group-id "new-replication-group" \
    --replication-group-description "new-replication-group" \
    --engine "VALKEY" \
    --cache-node-type cache.m5.large \
    --transit-encryption-enabled \
    --user-group-ids "new-group-1" \
    --cache-subnet-group "cache-subnet-group"
```

針對 Windows：

```
aws elasticache create-replication-group ^
    --replication-group-id "new-replication-group" ^
    --replication-group-description "new-replication-group" ^
    --engine "VALKEY" ^
    --cache-node-type cache.m5.large ^
    --transit-encryption-enabled ^
    --user-group-ids "new-group-1" ^
    --cache-subnet-group "cache-subnet-group"
```

下列AWS CLI操作會修改啟用傳輸中加密 (TLS) 的複寫群組，以及值為 的 **user-group-ids** 參數`my-user-group-id`。

針對 Linux、macOS 或 Unix：

```
aws elasticache modify-replication-group \
    --replication-group-id replication-group-1 \
    --user-group-ids-to-remove "new-group-1" \
    --user-group-ids-to-add "new-group-2"
```

針對 Windows：

```
aws elasticache modify-replication-group ^
    --replication-group-id replication-group-1 ^
    --user-group-ids-to-remove "new-group-1" ^
    --user-group-ids-to-add "new-group-2"
```

記下回應中的 `PendingChanges`。對快取所做的任何修改都會以非同步方式更新。您可以透過檢視事件來監控進度。如需詳細資訊，請參閱[檢視 ElastiCache 事件](ECEvents.Viewing.md)。

## 從 AUTH 遷移至 RBAC
<a name="Migrate-From-RBAC-to-Auth"></a>

如果您依 所述使用 AUTH，[使用 Valkey 和 Redis OSS AUTH 命令進行驗證](auth.md)並想要使用 RBAC 遷移至 ，請使用下列程序。

使用下列程序，使用主控台從 AUTH 遷移至 RBAC。

**使用主控台從 Valkey 或 Redis OSS AUTH 遷移至 RBAC**

1. 登入AWS 管理主控台，並在 https：//[https://console.aws.amazon.com/elasticache/](https://console.aws.amazon.com/elasticache/) 開啟 ElastiCache 主控台。

1. 從右上角的清單中，選擇您要修改的快取所在的AWS區域。

1. 在導覽窗格中，選擇在您要修改的快取上執行的引擎。

   接著會出現所選引擎的快取清單。

1. 在快取清單中，選擇您要修改之快取的名稱。

1. 在 **Actions** (動作) 中，選擇 **Modify** (修改)。

   **修改**視窗隨即出現。

1. 針對**存取控制**，選擇**使用者群組存取控制清單**。

1.  針對**使用者群組存取控制清單**，選擇一個使用者群組。

1. 選擇**預覽變更**，然後在下一個畫面上選擇**修改**。

使用下列程序，使用 CLI 從 Valkey 或 Redis OSS AUTH 遷移至 RBAC。

**使用 CLI 從 AUTH 遷移至 RBAC**
+  請使用 `modify-replication-group` 命令，如下列所示。

  針對 Linux、macOS 或 Unix：

  ```
  aws elasticache modify-replication-group --replication-group-id test \
      --auth-token-update-strategy DELETE \
      --user-group-ids-to-add user-group-1
  ```

  針對 Windows：

  ```
  aws elasticache modify-replication-group --replication-group-id test ^
      --auth-token-update-strategy DELETE ^
      --user-group-ids-to-add user-group-1
  ```

## 從 RBAC 遷移至 AUTH
<a name="Migrate-From-RBAC-to-AUTH-1"></a>

如果您使用 RBAC 並想要遷移至 Redis OSS AUTH，請參閱 [從 RBAC 遷移至 AUTH](auth.md#Migrate-From-RBAC-to-AUTH)。

**注意**  
如果您需要停用 ElastiCache 快取上的存取控制，則需要透過AWS CLI來進行。如需詳細資訊，請參閱[在 ElastiCache Valkey 或 Redis OSS 快取上停用存取控制](in-transit-encryption-disable.md)。

# 自動輪換使用者密碼
<a name="User-Secrets-Manager"></a>

使用 時AWS Secrets Manager，您可以使用對 Secrets Manager 的 API 呼叫取代程式碼中的硬式編碼登入資料 （包括密碼），以程式設計方式擷取秘密。這有助於確保不讓某人研究您的程式碼而盜用秘密，因為秘密根本不在程式碼中。此外，您可以設定 Secrets Manager，根據您指定的排程自動輪換秘密。這可讓您以短期秘密取代長期秘密，有助於大幅降低洩漏風險。

使用 Secrets Manager，您可以使用 Secrets Manager 提供的AWS Lambda函數自動輪換 ElastiCache for Redis OSS 密碼 （即秘密）。

如需詳細資訊AWS Secrets Manager，請參閱[什麼是AWS Secrets Manager？](https://docs.aws.amazon.com/secretsmanager/latest/userguide/intro.html)

## ElastiCache 如何使用秘密
<a name="how-elasticache-uses-secrets"></a>

Valkey 7.2 及更高版本具有同等功能，設定為 Redis OSS 7.0。在 Redis OSS 6 中，ElastiCache 推出[角色型存取控制 (RBAC) 規則數量](Clusters.RBAC.md)來保護 Valkey 或 Redis OSS 叢集。此功能允許以可執行命令和可存取金鑰限制部分連線。客戶使用 RBAC 以密碼建立使用者時，密碼值須以純文字手動輸入，讓運算子可見。

使用 Secret Manager 時，應用程式會從 Secrets Manager 擷取密碼，而非手動輸入，接著再將密碼儲存在應用程式組態。如需如何執行此作業的資訊，請參閱 [ElastiCache 使用者如何與秘密建立關聯](#How-User-Secrets-Manager-Associate)。

使用秘密會產生費用。如需定價資訊，請參閱 [AWS Secrets Manager 定價](https://aws.amazon.com/secrets-manager/pricing/)。

## ElastiCache 使用者如何與秘密建立關聯
<a name="How-User-Secrets-Manager-Associate"></a>

Secrets Manager 會在密碼的 `SecretString` 欄位保留關聯使用者的參考。不會有來自 ElastiCache 的秘密參考。

```
{
    "password": "strongpassword",
    "username": "user1",
    "user_arn": "arn:aws:elasticache:us-east-1:xxxxxxxxxx918:user:user1" //this is the bond between the secret and the user
}
```

## Lambda 輪換函數
<a name="lambda-rotation-function"></a>

若要啟用 Secrets Manager 自動密碼輪換，您要建立 Lambda 函數，該函數會與 [modify-user](https://docs.aws.amazon.com/cli/latest/reference/elasticache/modify-user.html) API 互動，以更新使用者密碼。

如需其運作方式的詳細資訊，請參閱[輪換的運作方式](https://docs.aws.amazon.com/secretsmanager/latest/userguide/rotating-secrets.html#rotate-secrets_how)。

**注意**  
對於某些AWS服務，為避免混淆代理人案例，AWS建議您同時使用 `aws:SourceArn`和 `aws:SourceAccount`全域條件金鑰。但是，如果在您的輪換函數政策中包含 `aws:SourceArn` 條件，則輪換函數只能用於輪換該 ARN 指定的秘密。建議您僅包含內容金鑰 `aws:SourceAccount`，以便可以將輪換函數用於多個秘密。

對於您可能遇到的任何問題，請參閱[對AWS Secrets Manager 輪換進行故障診斷](https://docs.aws.amazon.com/secretsmanager/latest/userguide/troubleshoot_rotation.html)。

## 如何建立 ElastiCache 使用者，並將其與 Secrets Manager 建立關聯
<a name="User-Secrets-Manager-Associate"></a>

下列步驟說明如何建立使用者，並將其與 Secrets Manager 建立關聯：

1. **建立非作用中的使用者**

   針對 Linux、macOS 或 Unix：

   ```
   aws elasticache create-user \
    --user-id user1 \
    --user-name user1 \
    --engine "REDIS" \
    --no-password \ // no authentication is required
    --access-string "*off* +get ~keys*" // this disables the user
   ```

   針對 Windows：

   ```
   aws elasticache create-user ^
    --user-id user1 ^
    --user-name user1 ^
    --engine "REDIS" ^
    --no-password ^ // no authentication is required
    --access-string "*off* +get ~keys*" // this disables the user
   ```

   您將看到類似以下的回應：

   ```
   {
       "UserId": "user1",
       "UserName": "user1",
       "Status": "active",
       "Engine": "redis",
       "AccessString": "off ~keys* -@all +get",
       "UserGroupIds": [],
       "Authentication": {
           "Type": "no_password"
       },
       "ARN": "arn:aws:elasticache:us-east-1:xxxxxxxxxx918:user:user1"
   }
   ```

1. **建立秘密**

   針對 Linux、macOS 或 Unix：

   ```
   aws secretsmanager create-secret \
   --name production/ec/user1 \
   --secret-string \
   '{
      "user_arn": "arn:aws:elasticache:us-east-1:123456xxxx:user:user1", 
       "username":"user1"
    }'
   ```

   針對 Windows：

   ```
   aws secretsmanager create-secret ^
   --name production/ec/user1 ^
   --secret-string ^
   '{
      "user_arn": "arn:aws:elasticache:us-east-1:123456xxxx:user:user1", 
       "username":"user1"
    }'
   ```

   您將看到類似以下的回應：

   ```
   {
    "ARN": "arn:aws:secretsmanager:us-east-1:123456xxxx:secret:production/ec/user1-eaFois",
    "Name": "production/ec/user1",
    "VersionId": "aae5b963-1e6b-4250-91c6-ebd6c47d0d95"
   }
   ```

1. **設定 Lambda 函數以輪換您的密碼**

   1. 登入AWS 管理主控台，並在 https：//[https://console.aws.amazon.com/lambda/](https://console.aws.amazon.com/elasticache/) 開啟 Lambda 主控台

   1. 在導覽面板上，選擇 **Functions** (函數)，然後選擇您所建立的函數。請選擇函數名稱，而非其左側的核取方塊。

   1. 選擇 **Configuration** (組態) 索引標籤。

   1. 在 **General configuration** (一般組態) 中，選擇 **Edit** (編輯)，然後將 **Timeout** (逾時) 設定為至少 12 分鐘。

   1. 選擇**儲存**。

   1. 選擇 **Environment variables** (環境變數)，然後設定下列項目：

      1. SECRETS\$1MANAGER\$1ENDPOINT – https://secretsmanager.**REGION**.amazonaws.com

      1. SECRET\$1ARN – 您在步驟 2 中建立的秘密 Amazon Resource Name (ARN)。

      1. USER\$1NAME – ElastiCache 使用者的使用者名稱，

      1. 選擇**儲存**。

   1. 選擇 **Permissions** (許可)

   1. 在 **Execution role** (執行角色) 下，選擇要在 IAM 主控台檢視的 Lambda 函數角色名稱。

   1. Lambda 函數需要下列許可，才能修改使用者和設定密碼：

      ElastiCache

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

****  

      ```
      {
          "Version":"2012-10-17",		 	 	 
          "Statement": [
              {
                  "Effect": "Allow",
                  "Action": [
                      "elasticache:DescribeUsers",
                      "elasticache:ModifyUser"
                  ],
                  "Resource": "arn:aws:elasticache:us-east-1:123456789012:user:user1"
              }
          ]
      }
      ```

------

      Secrets Manager

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

****  

      ```
      {
          "Version":"2012-10-17",		 	 	 
          "Statement": [
              {
                  "Effect": "Allow",
                  "Action": [
                      "secretsmanager:GetSecretValue",
                      "secretsmanager:DescribeSecret",
                      "secretsmanager:PutSecretValue",
                      "secretsmanager:UpdateSecretVersionStage"
                  ],
                  "Resource": "arn:aws:secretsmanager:us-east-1:123456789012:secret:XXXX"
              },
              {
                  "Effect": "Allow",
                  "Action": "secretsmanager:GetRandomPassword",
                  "Resource": "*"
              }
          ]
      }
      ```

------

1. 設定 Secrets Manager 秘密輪換

   1. **使用AWS 管理主控台，請參閱[使用主控台設定AWS Secrets Manager 秘密的自動輪](https://docs.aws.amazon.com/secretsmanager/latest/userguide/rotate-secrets_turn-on-for-other.html)換**

      如需輪換排程的詳細資訊，請參閱 [Secrets Manager 輪換中的排程表達式](https://docs.aws.amazon.com/secretsmanager/latest/userguide/rotate-secrets_schedule.html)。

   1. **使用AWS CLI，請參閱[AWS Secrets Manager使用 設定 的自動輪換AWS Command Line Interface](https://docs.aws.amazon.com/secretsmanager/latest/userguide/rotate-secrets-cli.html)**

# 以 IAM 進行身分驗證
<a name="auth-iam"></a>

**Topics**
+ [概觀](#auth-iam-overview)
+ [限制](#auth-iam-limits)
+ [設定](#auth-iam-setup)
+ [連接](#auth-iam-Connecting)

## 概觀
<a name="auth-iam-overview"></a>

透過 IAM 身分驗證，當您的快取設定為使用 Valkey 或 Redis OSS 第 7 版或更新版本時，您可以使用AWS IAM 身分驗證 ElastiCache for Valkey 或 Redis OSS 的連線。這可讓您強化安全模型，並簡化許多管理安全任務。您也可以使用 IAM 身分驗證為個別 ElastiCache 快取和 ElastiCache 使用者設定精細的存取控制，並遵循最低權限許可原則。ElastiCache 的 IAM 身分驗證的運作方式是在 Valkey 或 Redis OSS `AUTH`或 `HELLO`命令中提供短期 IAM 身分驗證字符，而非長期 ElastiCache 使用者密碼。如需 IAM 身分驗證字符的詳細資訊，請參閱《AWS一般參考指南》中的 [Signature 第 4 版簽署程序](https://docs.aws.amazon.com//general/latest/gr/signature-version-4.html)，以及下面的程式碼範例。

您可以使用 IAM 身分及其相關政策來進一步限制 Valkey 或 Redis OSS 存取。您也可以將使用者從聯合身分提供者的存取權直接授予 Valkey 或 Redis OSS 快取。

若要將AWS IAM 與 ElastiCache 搭配使用，您必須先建立身分驗證模式設定為 IAM 的 ElastiCache 使用者。然後，您可以建立或重複使用 IAM 身分。IAM 身分需有相關政策，才能將 `elasticache:Connect` 動作授予 ElastiCache 快取和使用者。設定完成後，您可以使用 IAM 使用者或角色的AWS登入資料建立 IAM 身分驗證字符。最後，您需要在連線至快取時，在 Valkey 或 Redis OSS 用戶端中提供短期 IAM 身分驗證字符做為密碼。支援登入資料的 Valkey 或 Redis OSS 用戶端可以為每個新連線自動產生臨時登入資料。ElastiCache 將對啟用 IAM 的 ElastiCache 使用者的連線請求執行 IAM 身分驗證，並將使用 IAM 驗證連線請求。

## 限制
<a name="auth-iam-limits"></a>

使用 IAM 身分驗證，會套用以下限制：
+ 使用 ElastiCache for Valkey 7.2 及更高版本或 Redis OSS 7.0 及更高版本時，可使用 IAM 身分驗證。
+ 針對已啟用 IAM 的 ElastiCache 使用者，使用者名稱和使用者 ID 屬性必須相同。
+ IAM 身分驗證字符的有效期限為 15 分鐘。對於長期連線，我們建議您使用支援登入資料提供者介面的 Valkey 或 Redis OSS 用戶端。
+ IAM 驗證的 ElastiCache for Valkey 或 Redis OSS 連線會在 12 小時後自動中斷連線。可以傳送包含新 IAM 身分驗證字符的 `AUTH` 或 `HELLO` 命令，將連線再延長 12 小時。
+ `MULTI EXEC` 命令不支援 IAM 身分驗證。
+ 目前，IAM 身分驗證支援下列全域條件內容金鑰：
  + 使用 IAM 身分驗證搭配無伺服器快取時，可支援 `aws:VpcSourceIp`、`aws:SourceVpc`、`aws:SourceVpce`、`aws:CurrentTime`、`aws:EpochTime` 和 `aws:ResourceTag/%s` (來自相關聯的無伺服器快取和使用者)。
  + 使用 IAM 身分驗證搭配複寫群組時，可支援 `aws:SourceIp` 和 `aws:ResourceTag/%s` (來自相關聯的複寫群組和使用者)。

  如需有關全域條件內容索引鍵的詳細資訊，請參閱《IAM 使用者指南》中的 [AWS全域條件內容索引鍵](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html)。

## 設定
<a name="auth-iam-setup"></a>

設定 IAM 身分驗證：

1. 建立快取

   ```
   aws elasticache create-serverless-cache \
     --serverless-cache-name cache-01  \
     --description "ElastiCache IAM auth application" \
     --engine redis
   ```

1. 為您的角色建立如下所示的 IAM 信任政策文件，讓您的帳戶擔任新角色。將政策儲存到名為 *trust-policy.json* 的檔案。

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

****  

   ```
   {
       "Version":"2012-10-17",		 	 	 
       "Statement": {
           "Effect": "Allow",
           "Principal": { "AWS": "arn:aws:iam::123456789012:root" },
           "Action": "sts:AssumeRole"
       }
   }
   ```

------

1. 建立 IAM 政策文件，如下所示。將政策儲存到名為 *policy.json* 的檔案。

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

****  

   ```
   {
     "Version":"2012-10-17",		 	 	 
     "Statement": [
       {
         "Effect" : "Allow",
         "Action" : [
           "elasticache:Connect"
         ],
         "Resource" : [
           "arn:aws:elasticache:us-east-1:123456789012:serverlesscache:cache-01",
           "arn:aws:elasticache:us-east-1:123456789012:user:iam-user-01"
         ]
       }
     ]
   }
   ```

------

1. 建立 IAM 角色。

   ```
   aws iam create-role \
   --role-name "elasticache-iam-auth-app" \
   --assume-role-policy-document file://trust-policy.json
   ```

1. 建立 IAM 政策。

   ```
   aws iam create-policy \
     --policy-name "elasticache-allow-all" \
     --policy-document file://policy.json
   ```

1. 將 IAM 政策連接至角色。

   ```
   aws iam attach-role-policy \
    --role-name "elasticache-iam-auth-app" \
    --policy-arn "arn:aws:iam::123456789012:policy/elasticache-allow-all"
   ```

1. 建立已啟用 IAM 的新使用者。

   ```
   aws elasticache create-user \
     --user-name iam-user-01 \
     --user-id iam-user-01 \
     --authentication-mode Type=iam \
     --engine redis \
     --access-string "on ~* +@all"
   ```

1. 建立使用者群組並連接使用者。

   ```
   aws elasticache create-user-group \
     --user-group-id iam-user-group-01 \
     --engine redis \
     --user-ids default iam-user-01
   
   aws elasticache modify-serverless-cache \
     --serverless-cache-name cache-01  \
     --user-group-id iam-user-group-01
   ```

## 連接
<a name="auth-iam-Connecting"></a>

**以字符做為密碼進行連線**

首先，您需要使用 [AWS SigV4 預先簽章的請求](https://docs.aws.amazon.com//general/latest/gr/sigv4-signed-request-examples.html)，產生短期 IAM 身分驗證字符。之後，您在連線至 Valkey 或 Redis OSS 快取時提供 IAM 身分驗證字符做為密碼，如以下範例所示。

```
String userId = "insert user id";
String cacheName = "insert cache name";
boolean isServerless = true;
String region = "insert region";

// Create a default AWS Credentials provider.
// This will look for AWS credentials defined in environment variables or system properties.
AWSCredentialsProvider awsCredentialsProvider = new DefaultAWSCredentialsProviderChain();

// Create an IAM authentication token request and signed it using the AWS credentials.
// The pre-signed request URL is used as an IAM authentication token for ElastiCache with Redis OSS.
IAMAuthTokenRequest iamAuthTokenRequest = new IAMAuthTokenRequest(userId, cacheName, region, isServerless);
String iamAuthToken = iamAuthTokenRequest.toSignedRequestUri(awsCredentialsProvider.getCredentials());

// Construct Redis OSS URL with IAM Auth credentials provider
RedisURI redisURI = RedisURI.builder()
    .withHost(host)
    .withPort(port)
    .withSsl(ssl)
    .withAuthentication(userId, iamAuthToken)
    .build();

// Create a new Lettuce Redis OSS client
RedisClient client = RedisClient.create(redisURI);
client.connect();
```

以下是 `IAMAuthTokenRequest` 的定義。

```
public class IAMAuthTokenRequest {
    private static final HttpMethodName REQUEST_METHOD = HttpMethodName.GET;
    private static final String REQUEST_PROTOCOL = "http://";
    private static final String PARAM_ACTION = "Action";
    private static final String PARAM_USER = "User";
    private static final String PARAM_RESOURCE_TYPE = "ResourceType";
    private static final String RESOURCE_TYPE_SERVERLESS_CACHE = "ServerlessCache";
    private static final String ACTION_NAME = "connect";
    private static final String SERVICE_NAME = "elasticache";
    private static final long TOKEN_EXPIRY_SECONDS = 900;

    private final String userId;
    private final String cacheName;
    private final String region;
    private final boolean isServerless;

    public IAMAuthTokenRequest(String userId, String cacheName, String region, boolean isServerless) {
        this.userId = userId;
        this.cacheName = cacheName;
        this.region = region;
        this.isServerless = isServerless;
    }

    public String toSignedRequestUri(AWSCredentials credentials) throws URISyntaxException {
        Request<Void> request = getSignableRequest();
        sign(request, credentials);
        return new URIBuilder(request.getEndpoint())
            .addParameters(toNamedValuePair(request.getParameters()))
            .build()
            .toString()
            .replace(REQUEST_PROTOCOL, "");
    }

    private <T> Request<T> getSignableRequest() {
        Request<T> request  = new DefaultRequest<>(SERVICE_NAME);
        request.setHttpMethod(REQUEST_METHOD);
        request.setEndpoint(getRequestUri());
        request.addParameters(PARAM_ACTION, Collections.singletonList(ACTION_NAME));
        request.addParameters(PARAM_USER, Collections.singletonList(userId));
        if (isServerless) {
            request.addParameters(PARAM_RESOURCE_TYPE, Collections.singletonList(RESOURCE_TYPE_SERVERLESS_CACHE));
        }
        return request;
    }

    private URI getRequestUri() {
        return URI.create(String.format("%s%s/", REQUEST_PROTOCOL, cacheName));
    }

    private <T> void sign(SignableRequest<T> request, AWSCredentials credentials) {
        AWS4Signer signer = new AWS4Signer();
        signer.setRegionName(region);
        signer.setServiceName(SERVICE_NAME);

        DateTime dateTime = DateTime.now();
        dateTime = dateTime.plus(Duration.standardSeconds(TOKEN_EXPIRY_SECONDS));

        signer.presignRequest(request, credentials, dateTime.toDate());
    }

    private static List<NameValuePair> toNamedValuePair(Map<String, List<String>> in) {
        return in.entrySet().stream()
            .map(e -> new BasicNameValuePair(e.getKey(), e.getValue().get(0)))
            .collect(Collectors.toList());
    }
}
```

**使用憑證提供者進行連線**

以下程式碼說明如何使用 IAM 身分驗證憑證提供者向 ElastiCache 進行身分驗證。

```
String userId = "insert user id";
String cacheName = "insert cache name";
boolean isServerless = true;
String region = "insert region";

// Create a default AWS Credentials provider.
// This will look for AWS credentials defined in environment variables or system properties.
AWSCredentialsProvider awsCredentialsProvider = new DefaultAWSCredentialsProviderChain();

// Create an IAM authentication token request. Once this request is signed it can be used as an
// IAM authentication token for ElastiCache with Redis OSS.
IAMAuthTokenRequest iamAuthTokenRequest = new IAMAuthTokenRequest(userId, cacheName, region, isServerless);

// Create a Redis OSS credentials provider using IAM credentials.
RedisCredentialsProvider redisCredentialsProvider = new RedisIAMAuthCredentialsProvider(
    userId, iamAuthTokenRequest, awsCredentialsProvider);
    
// Construct Redis OSS URL with IAM Auth credentials provider
RedisURI redisURI = RedisURI.builder()
    .withHost(host)
    .withPort(port)
    .withSsl(ssl)
    .withAuthentication(redisCredentialsProvider)
    .build();

// Create a new Lettuce Redis OSS client
RedisClient client = RedisClient.create(redisURI);
client.connect();
```

以下是 Lettuce Redis OSS 用戶端的範例，該用戶端會在登入資料提供者中包裝 IAMAuthTokenRequest，以在需要時自動產生臨時登入資料。

```
public class RedisIAMAuthCredentialsProvider implements RedisCredentialsProvider {
    private static final long TOKEN_EXPIRY_SECONDS = 900;

    private final AWSCredentialsProvider awsCredentialsProvider;
    private final String userId;
    private final IAMAuthTokenRequest iamAuthTokenRequest;
    private final Supplier<String> iamAuthTokenSupplier;

    public RedisIAMAuthCredentialsProvider(String userId,
        IAMAuthTokenRequest iamAuthTokenRequest,
        AWSCredentialsProvider awsCredentialsProvider) {
        this.userName = userName;
        this.awsCredentialsProvider = awsCredentialsProvider;
        this.iamAuthTokenRequest = iamAuthTokenRequest;      
        this.iamAuthTokenSupplier = Suppliers.memoizeWithExpiration(this::getIamAuthToken, TOKEN_EXPIRY_SECONDS, TimeUnit.SECONDS);
    }

    @Override
    public Mono<RedisCredentials> resolveCredentials() {
        return Mono.just(RedisCredentials.just(userId, iamAuthTokenSupplier.get()));
    }

    private String getIamAuthToken() {
        return iamAuthTokenRequest.toSignedRequestUri(awsCredentialsProvider.getCredentials());
    }
}
```

# 使用 Valkey 和 Redis OSS AUTH 命令進行驗證
<a name="auth"></a>

**注意**  
**AUTH** 已由 取代[角色型存取控制 (RBAC) 規則數量](Clusters.RBAC.md)。所有無伺服器快取都必須使用 RBAC 進行身分驗證。

Valkey 和 Redis OSS 身分驗證字符或密碼可讓 Valkey 和 Redis OSS 在允許用戶端執行命令之前要求密碼，藉此改善資料安全性。僅適用於**AUTH**節點型叢集。

**Topics**
+ [ElastiCache for Valkey 和 Redis OSS 中的 AUTH 概觀](#auth-overview)
+ [將身分驗證套用至 ElastiCache for Valkey 和 Redis OSS 叢集](#auth-using)
+ [修改現有叢集上的 AUTH 字符](#auth-modifyng-token)
+ [從 RBAC 遷移至 AUTH](#Migrate-From-RBAC-to-AUTH)

## ElastiCache for Valkey 和 Redis OSS 中的 AUTH 概觀
<a name="auth-overview"></a>

當您**AUTH**搭配 ElastiCache for Valkey 和 Redis OSS 叢集使用 時，有一些改進。

特別是，在使用 AUTH 時，請注意這些 AUTH 字符或密碼限制：
+ 字符 (或密碼) 必須為 16 - 128 個可列印字元。
+ 非英數字元僅限使用 (\$1、&、\$1、\$1、^、<、>、-)。
+ AUTH 只能針對啟用傳輸中加密的 Valkey 或 Redis OSS 叢集啟用。

若要設定高強度的字符，建議您遵循嚴格的密碼政策，例如需符合以下要求：
+ 字符或密碼必須至少包含下列三種字元類型：
  + 大寫字元
  + 小寫字元
  + 數字 
  + 非英數字元 (`!`、`&`、`#`、`$`、`^`、`<`、`>`、`-`)
+ 字符或密碼不得包含字典單字或稍微修改的字典單字。
+ 字符或密碼不得與最近使用的字符相同或相似。

## 將身分驗證套用至 ElastiCache for Valkey 和 Redis OSS 叢集
<a name="auth-using"></a>

您可以要求使用者在字符保護的 Valkey 或 Redis OSS 伺服器上輸入字符 （密碼）。若要執行此操作，請在您建立複寫群組或叢集時加入有正確字符的參數 `--auth-token` (API: `AuthToken`)。而且也要在複寫群組或叢集的所有後續命令中加入。

下列AWS CLI操作會建立啟用傳輸中加密 (TLS) 和**AUTH**字符 的複寫群組`This-is-a-sample-token`。將子網路群組 `sng-test` 取代為已存在的子網路群組。

**重要參數**
+ **--engine** – 必須為 `valkey`或 `redis`。
+ **--engine-version** – 如果引擎是 Redis OSS，則 必須是 3.2.6、4.0.10 或更新版本。
+ **--transit-encryption-enabled** - 身分驗證及符合 HIPAA 資格的必要項目。
+ **--auth-token** - 符合 HIPAA 資格的必要項目。此值必須是此字符保護的 Valkey 或 Redis OSS 伺服器的正確字符。
+ **--cache-subnet-group** - 符合 HIPAA 資格的必要項目。

針對 Linux、macOS 或 Unix：

```
aws elasticache create-replication-group \
    --replication-group-id authtestgroup \
    --replication-group-description authtest \
    --engine redis \ 
    --cache-node-type cache.m4.large \
    --num-node-groups 1 \
    --replicas-per-node-group 2 \    
    --transit-encryption-enabled \
    --auth-token This-is-a-sample-token \
    --cache-subnet-group sng-test
```

針對 Windows：

```
aws elasticache create-replication-group ^
    --replication-group-id authtestgroup ^
    --replication-group-description authtest ^
    --engine redis ^ 
    --cache-node-type cache.m4.large ^
    --num-node-groups 1 ^
    --replicas-per-node-group 2 ^    
    --transit-encryption-enabled ^
    --auth-token This-is-a-sample-token ^
    --cache-subnet-group sng-test
```

## 修改現有叢集上的 AUTH 字符
<a name="auth-modifyng-token"></a>

若要更輕鬆地更新身分驗證，您可以修改叢集上使用的**AUTH**字符。如果引擎版本為 Valkey 7.2 或更新版本，或 Redis 5.0.6 或更新版本，您可以進行此修改。ElastiCache 也必須啟用傳輸中加密。

Auth 字符修改支援兩種策略：ROTATE 和 SET。ROTATE 策略會將額外的 AUTH 字符新增至伺服器，同時保留先前的字符。SET 策略會更新伺服器，僅支援單一 AUTH 字符。使用 `--apply-immediately` 參數進行這些修改呼叫以立即套用變更。

### 輪換 AUTH 字符
<a name="auth-modifyng-rotate"></a>

若要使用新的 **AUTH 字符**更新 Valkey 或 Redis OSS 伺服器，請使用 `--auth-token` 參數呼叫 `ModifyReplicationGroup` API 做為新的**AUTH**字符，並使用`--auth-token-update-strategy`值 ROTATE 呼叫 。ROTATE 修改完成後，除了 `auth-token` 參數中指定的字符外，叢集還支援先前的 AUTH 字符。如果在 AUTH 權杖輪換之前未在複寫群組上設定 AUTH 權杖，則叢集除了支援在沒有身分驗證的情況下連線之外，還支援 `--auth-token` 參數中指定的 AUTH 權杖。請參閱 [設定 AUTH 字符](#auth-modifying-set) 以使用更新策略 SET 將 AUTH 權杖更新為必要。

**注意**  
如果您之前沒有設定 AUTH 字符，那麼一旦修改完成，除了 auth-token 參數中指定的字符之外，叢集將不支援任何 AUTH 字符。

如果在已支援兩個 AUTH 字符的伺服器上執行此修改，則在此操作期間也會移除最舊的 AUTH 字符。這可讓伺服器在特定時間支援最多兩個最新的 AUTH 字符。

此時，您可以更新用戶端以使用最新的 AUTH 字符以繼續。用戶端更新後，您可以使用 **AUTH** 字符輪換的 SET 策略 (於以下章節說明) 以僅開始使用新的字符。

下列AWS CLI操作會修改複寫群組以輪換**AUTH**字符 `This-is-the-rotated-token`。

針對 Linux、macOS 或 Unix：

```
aws elasticache modify-replication-group \
--replication-group-id authtestgroup \
--auth-token This-is-the-rotated-token \
--auth-token-update-strategy ROTATE \
--apply-immediately
```

針對 Windows：

```
aws elasticache modify-replication-group ^
--replication-group-id authtestgroup ^
--auth-token This-is-the-rotated-token ^
--auth-token-update-strategy ROTATE ^
--apply-immediately
```

### 設定 AUTH 字符
<a name="auth-modifying-set"></a>

若要更新 Valkey 或 Redis OSS 伺服器以支援單一必要**AUTH**字符，請使用與最後一個 AUTH 字符具有相同值的 `--auth-token` 參數呼叫 `ModifyReplicationGroup` API 操作，並使用值 呼叫 `--auth-token-update-strategy` 參數`SET`。SET 策略只能與具有 2 個 AUTH 字符或 1 個先前使用 ROTATE 策略之選用 AUTH 字符的叢集搭配使用。修改完成後，伺服器僅支援 auth-token 參數中指定的 AUTH 字符。

下列AWS CLI操作會修改複寫群組，將 AUTH 字符設定為 `This-is-the-set-token`。

針對 Linux、macOS 或 Unix：

```
aws elasticache modify-replication-group \
--replication-group-id authtestgroup \
--auth-token This-is-the-set-token \
--auth-token-update-strategy SET \
--apply-immediately
```

針對 Windows：

```
aws elasticache modify-replication-group ^
--replication-group-id authtestgroup ^
--auth-token This-is-the-set-token ^
--auth-token-update-strategy SET ^
--apply-immediately
```

### 在現有叢集上啟用身分驗證
<a name="auth-enabling"></a>

若要在現有的 Valkey 或 Redis OSS 伺服器上啟用身分驗證，請呼叫 `ModifyReplicationGroup` API 操作。使用 `--auth-token` 參數為新的字符，以及值為 ROTATE 的 `--auth-token-update-strategy` 呼叫 `ModifyReplicationGroup`。

ROTATE 修改完成後，叢集除了支援無需身分驗證的連線之外，還支援 `--auth-token` 參數中指定的**AUTH**字符。更新所有用戶端應用程式以使用 AUTH 字符驗證 Valkey 或 Redis OSS 後，請使用 SET 策略將 AUTH 字符標記為必要。只有啟用傳輸中加密 (TLS) 的 Valkey 和 Redis OSS 伺服器才支援啟用身分驗證。

## 從 RBAC 遷移至 AUTH
<a name="Migrate-From-RBAC-to-AUTH"></a>

如果您使用 Valkey 或 Redis OSS 角色型存取控制 (RBAC) 驗證使用者，如 中所述[角色型存取控制 (RBAC) 規則數量](Clusters.RBAC.md)，而且您想要遷移至 AUTH，請使用下列程序。您可以使用主控台或 CLI 進行遷移。

**使用主控台從 RBAC 遷移至 AUTH**

1. 登入AWS 管理主控台，並在 https：//[https://console.aws.amazon.com/elasticache/](https://console.aws.amazon.com/elasticache/) 開啟 ElastiCache 主控台。

1. 從右上角的清單中，選擇您要修改之叢集所在的AWS區域。

1. 在導覽窗格中，選擇您要修改之叢集所執行的引擎。

   接著會出現所選引擎的叢集清單。

1. 在叢集清單中，針對您要修改的叢集，選擇其名稱。

1. 在 **Actions** (動作) 中，選擇 **Modify** (修改)。

   **修改**視窗隨即出現。

1. 針對**存取控制**，選擇 **Valkey AUTH 預設使用者存取權**或 **Redis OSS AUTH 預設使用者存取權**。

1. 在 **Valkey AUTH 權**杖或 **Redis OSS AUTH 權杖**下，設定新的權杖。

1. 選擇**預覽變更**，然後在下一個畫面上選擇**修改**。

**使用 從 RBAC 遷移至 AUTH AWS CLI**

使用下列其中一個命令，為您的 Valkey 或 Redis OSS 複寫群組設定新的選用**AUTH**權杖。請注意，選用的身分驗證字符將允許未經驗證的複寫群組存取權，直到使用以下步驟`SET`中的更新策略將身分驗證字符標記為必要為止。

針對 Linux、macOS 或 Unix：

```
aws elasticache modify-replication-group \
    --replication-group-id test \
    --remove-user-groups \
    --auth-token This-is-a-sample-token \
    --auth-token-update-strategy ROTATE \ 
    --apply-immediately
```

針對 Windows：

```
aws elasticache modify-replication-group ^
    --replication-group-id test ^
    --remove-user-groups ^
    --auth-token This-is-a-sample-token ^
    --auth-token-update-strategy ROTATE ^ 
    --apply-immediately
```

執行上述命令後，您可以使用新設定的選用 AUTH 權杖，更新您的 Valkey 或 Redis OSS 應用程式以驗證 ElastiCache 複寫群組。若要完成身分驗證字符輪換，請在下列後續命令`SET`中使用更新策略。這將視需要標示為選用的 AUTH 字符。身分驗證字符更新完成時，複寫群組狀態會顯示為 `ACTIVE`，且此複寫群組的所有連線都需要身分驗證。

針對 Linux、macOS 或 Unix：

```
aws elasticache modify-replication-group \
			--replication-group-id test \
			--auth-token This-is-a-sample-token \
			--auth-token-update-strategy SET \ 
			--apply-immediately
```

針對 Windows：

```
aws elasticache modify-replication-group ^
			--replication-group-id test ^
			--remove-user-groups ^
			--auth-token This-is-a-sample-token ^
			--auth-token-update-strategy SET ^ 
			--apply-immediately
```

如需詳細資訊，請參閱[使用 Valkey 和 Redis OSS AUTH 命令進行驗證](#auth)。

**注意**  
如果您需要停用 ElastiCache 叢集的存取控制，請參閱 [在 ElastiCache Valkey 或 Redis OSS 快取上停用存取控制](in-transit-encryption-disable.md)。

# 在 ElastiCache Valkey 或 Redis OSS 快取上停用存取控制
<a name="in-transit-encryption-disable"></a>

請依照下列指示，在啟用 Valkey 或 Redis OSS TLS 的快取上停用存取控制。您的快取有兩種不同類型的組態：AUTH 預設使用者存取或使用者群組存取控制清單 (RBAC)。如果您的快取是使用 AUTH 組態所建立，則必須先將它變更為 RBAC 組態，才能藉由移除使用者群組來停用快取。如果您的快取是使用 RBAC 組態所建立，則可以直接將它停用。

**停用使用 RBAC 設定的 Valkey 或 Redis OSS 無伺服器快取**

1. 移除使用者群組以停用存取控制。

   ```
   aws elasticache modify-serverless-cache --serverless-cache-name <serverless-cache> --remove-user-group
   ```

1. (選用) 確認沒有與無伺服器快取相關聯的使用者群組。

   ```
   aws elasticache describe-serverless-caches --serverless-cache-name <serverless-cache>    
   {
       "..."
       "UserGroupId": ""
       "..."
   }
   ```

**停用使用 AUTH 字符設定的 Valkey 或 Redis OSS 快取**

1. 將 AUTH 字符變更為 RBAC 並指定要新增的使用者群組。

   ```
   aws elasticache modify-replication-group --replication-group-id <replication-group-id-value> --auth-token-update-strategy DELETE --user-group-ids-to-add <user-group-value>
   ```

1. 確認 AUTH 字符已停用且使用者群組已新增。

   ```
   aws elasticache describe-replication-groups --replication-group-id <replication-group-id-value>
   {
       "..."
       "AuthTokenEnabled": false,
       "UserGroupIds": [
           "<user-group-value>"
       ]
       "..."
   }
   ```

1. 移除使用者群組以停用存取控制。

   ```
   aws elasticache modify-replication-group --replication-group-id <replication-group-value> --user-group-ids-to-remove <user-group-value>
   {
       "..."
       "PendingModifiedValues": {
       "UserGroups": {
         "UserGroupIdsToAdd": [],
         "UserGroupIdsToRemove": [
           "<user-group-value>"
         ]
       }
       "..."
   }
   ```

1. (選用) 確認沒有與叢集相關聯的使用者群組。`AuthTokenEnabled` 欄位也應顯示 false。

   ```
   aws elasticache describe-replication-groups --replication-group-id <replication-group-value>    
   "AuthTokenEnabled": false
   ```

**停用使用 RBAC 設定的 Valkey 或 Redis OSS 叢集**

1. 移除使用者群組以停用存取控制。

   ```
   aws elasticache modify-replication-group --replication-group-id <replication-group-value> --user-group-ids-to-remove <user-group-value>
   {
       "..."
       "PendingModifiedValues": {
       "UserGroups": {
         "UserGroupIdsToAdd": [],
         "UserGroupIdsToRemove": [
           "<user-group-value>"
         ]
       }
       "..."
   }
   ```

1. (選用) 確認沒有與叢集相關聯的使用者群組。`AuthTokenEnabled` 欄位也應顯示 false。

   ```
   aws elasticache describe-replication-groups --replication-group-id <replication-group-value>    
   "AuthTokenEnabled": false
   ```