

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

# 使用 Python 取得 Secrets Manager 秘密值
<a name="retrieving-secrets-python"></a>

在應用程式中，您可以透過在任何 AWS SDKs `BatchGetSecretValue`中呼叫 `GetSecretValue`或 來擷取秘密。不過，建議您使用用戶端快取來快取您的秘密值。快取秘密可提高速度並降低成本。

**Topics**
+ [使用 Python 搭配用戶端快取取得 Secrets Manager 秘密值](retrieving-secrets_cache-python.md)
+ [使用 Python AWS SDK 取得 Secrets Manager 秘密值](retrieving-secrets-python-sdk.md)
+ [使用 Python AWS SDK 取得一批 Secrets Manager 秘密值](retrieving-secrets-python-batch.md)

# 使用 Python 搭配用戶端快取取得 Secrets Manager 秘密值
<a name="retrieving-secrets_cache-python"></a>

擷取秘密時，您可以使用 Secrets Manager Python 型快取元件進行快取以供將來使用。擷取快取的秘密比從 Secrets Manager 中擷取要快。由於呼叫 Secrets Manager API 需要花費成本，因此使用快取可以降低成本。如需您可以擷取機密的所有方法，請參閱 [取得秘密](retrieving-secrets.md)。

快取政策是「最近最少使用的 (LRU)」，因此當快取必須丟棄秘密時，其會丟棄最近最少使用的秘密。預設情況下，快取每小時重新整理一次秘密。您可以設定在快取中[重新整理機密的頻率](retrieving-secrets_cache-ref-secretcacheconfig.md)，並可以[掛接到機密擷取](retrieving-secrets_cache-ref-secretcachehook.md)以新增更多功能。

一旦釋放快取參考，快取不會強制執行垃圾回收。快取實作不包括快取失效。快取實作著重於快取本身，而不是強化或著重於安全性。如果您需要額外的安全性，例如加密快取中的項目，請使用提供的介面和抽象方法。

若要使用元件，您必須擁有下列項目：
+ Python 3.6 或更高版本。
+ botocore 1.12 或更高版本。請參閱 [AWS SDK for Python](https://aws.amazon.com/sdk-for-python/) 和 [Botocore](https://botocore.amazonaws.com/v1/documentation/api/latest/index.html)。
+ setuptools\$1scm 3.2 或更高版本。請參閱 [https://pypi.org/project/setuptools-scm/](https://pypi.org/project/setuptools-scm/)。

若要下載開放程式碼，請參閱 [Secrets Manager Python 型快取用戶端元件](https://github.com/aws/aws-secretsmanager-caching-python ) (在 GitHub 上)。

若要安裝元件，請使用下列命令。

```
$ pip install aws-secretsmanager-caching
```

**必要許可：**
+ `secretsmanager:DescribeSecret`
+ `secretsmanager:GetSecretValue`

如需詳細資訊，請參閱[許可參考](auth-and-access.md#reference_iam-permissions)。

**Topics**
+ [SecretCache](retrieving-secrets_cache-ref-secretcache.md)
+ [SecretCacheConfig](retrieving-secrets_cache-ref-secretcacheconfig.md)
+ [SecretCacheHook](retrieving-secrets_cache-ref-secretcachehook.md)
+ [@InjectSecretString](retrieving-secrets_cache-decor-string.md)
+ [@InjectKeywordedSecretString](retrieving-secrets_cache-decor-keyword.md)

**Example 擷取秘密**  
以下範例顯示如何為名為 *mysecret* 的秘密取得秘密值。  

```
import botocore 
import botocore.session 
from aws_secretsmanager_caching import SecretCache, SecretCacheConfig 

client = botocore.session.get_session().create_client('secretsmanager')
cache_config = SecretCacheConfig()
cache = SecretCache( config = cache_config, client = client)

secret = cache.get_secret_string('mysecret')
```

# SecretCache
<a name="retrieving-secrets_cache-ref-secretcache"></a>

從 Secrets Manager 擷取的秘密記憶體內快取。您使用 [get\$1secret\$1string](#retrieving-secrets_cache-ref-secretcache_get_secret_string) 或 [get\$1secret\$1binary](#retrieving-secrets_cache-ref-secretcache_get_secret_binary) 從快取中擷取秘密。您可以透過在建構函式的 [SecretCacheConfig](retrieving-secrets_cache-ref-secretcacheconfig.md) 物件中傳遞，設定快取設定。

如需包含範例的詳細資訊，請參閱 [使用 Python 搭配用戶端快取取得 Secrets Manager 秘密值](retrieving-secrets_cache-python.md)。

```
cache = SecretCache(
    config = SecretCacheConfig,
    client = [client](https://botocore.amazonaws.com/v1/documentation/api/latest/reference/services/secretsmanager.html)
)
```

**Topics**
+ [get\$1secret\$1string](#retrieving-secrets_cache-ref-secretcache_get_secret_string)
+ [get\$1secret\$1binary](#retrieving-secrets_cache-ref-secretcache_get_secret_binary)

## get\$1secret\$1string
<a name="retrieving-secrets_cache-ref-secretcache_get_secret_string"></a>

擷取秘密字串值。

請求語法  

```
response = cache.get_secret_string(
    secret_id='string',
    version_stage='string' )
```

Parameters  
+ `secret_id` (*字串*)：【必要】 秘密的名稱或 ARN。
+ `version_stage` (*字串*)：您要擷取的秘密版本。如需詳細資訊，請參閱[秘密版本](whats-in-a-secret.md)。預設值為 'AWSCURRENT'。

傳回類型  
string

## get\$1secret\$1binary
<a name="retrieving-secrets_cache-ref-secretcache_get_secret_binary"></a>

擷取秘密二進位值。

請求語法  

```
response = cache.get_secret_binary(
    secret_id='string',
    version_stage='string'
)
```

Parameters  
+ `secret_id` (*字串*)：【必要】 秘密的名稱或 ARN。
+ `version_stage` (*字串*)：您要擷取的秘密版本。如需詳細資訊，請參閱[秘密版本](whats-in-a-secret.md)。預設值為 'AWSCURRENT'。

傳回類型  
[base64-encoded](https://tools.ietf.org/html/rfc4648#section-4) 字串

# SecretCacheConfig
<a name="retrieving-secrets_cache-ref-secretcacheconfig"></a>

[SecretCache](retrieving-secrets_cache-ref-secretcache.md) 的快取組態選項，例如最大快取大小和快取秘密的存留時間 (TTL)。Parameters

`max_cache_size` (*int*)  
最大快取大小。預設值為 `1024` 個秘密。

`exception_retry_delay_base` (*int*)  
重試請求前遇到異常之後等待的秒數。預設值為 `1`。

`exception_retry_growth_factor` (*int*)pur  
用於計算失敗請求重試之間等待時間的增長係數。預設值為 `2`。

`exception_retry_delay_max` (*int*)  
在失敗請求之間等待的時間上限 (以秒為單位)。預設值為 `3600`。

`default_version_stage` (*str*)  
要快取的秘密版本。如需詳細資訊，請參閱[秘密版本](whats-in-a-secret.md#term_version)。預設為 `'AWSCURRENT'`。

`secret_refresh_interval` (*int*)  
重新整理快取秘密資訊之間的等待秒數。預設值為 `3600`。

`secret_cache_hook` (*SecretCacheHook*)  
`SecretCacheHook` 摘要類別的實作。預設值為 `None`。

# SecretCacheHook
<a name="retrieving-secrets_cache-ref-secretcachehook"></a>

用於掛接到 [SecretCache](retrieving-secrets_cache-ref-secretcache.md)，以對存放在快取中的秘密執行動作的介面。

**Topics**
+ [put](#retrieving-secrets_cache-ref-secretcachehook_put)
+ [get](#retrieving-secrets_cache-ref-secretcachehook_get)

## put
<a name="retrieving-secrets_cache-ref-secretcachehook_put"></a>

準備要存放在快取中的物件。

請求語法  

```
response = hook.put(
    obj='secret_object'
)
```

Parameters  
+ `obj` (*物件*) – [必需] 包含秘密的秘密或物件。

傳回類型  
object

## get
<a name="retrieving-secrets_cache-ref-secretcachehook_get"></a>

從快取的物件中衍生物件。

請求語法  

```
response = hook.get(
    obj='secret_object'
)
```

Parameters  
+ `obj` (*物件*)：【必要】 包含秘密的秘密或物件。

傳回類型  
object

# @InjectSecretString
<a name="retrieving-secrets_cache-decor-string"></a>

此裝飾項目需要秘密 ID 字串和 [SecretCache](retrieving-secrets_cache-ref-secretcache.md) 作為第一個和第二個引數。裝飾項目傳回秘密字串值。秘密必須包含字串。

```
from aws_secretsmanager_caching import SecretCache 
from aws_secretsmanager_caching import InjectKeywordedSecretString,  InjectSecretString 

cache = SecretCache()

@InjectSecretString ( 'mysecret' ,  cache ) 
def function_to_be_decorated( arg1,  arg2,  arg3):
```

# @InjectKeywordedSecretString
<a name="retrieving-secrets_cache-decor-keyword"></a>

此裝飾項目需要秘密 ID 字串和 [SecretCache](retrieving-secrets_cache-ref-secretcache.md) 作為第一個和第二個引數。剩餘的引數將參數從包裝函數映射到秘密中的 JSON 金鑰。秘密必須包含 JSON 結構中的字串。

對於包含此 JSON 的秘密：

```
{
  "username": "saanvi",
  "password": "EXAMPLE-PASSWORD"
}
```

下列範例顯示如何從秘密擷取 `username` 和 `password` 的 JSON 值。

```
from aws_secretsmanager_caching import SecretCache 
  from aws_secretsmanager_caching import InjectKeywordedSecretString,  InjectSecretString 
  
  cache = SecretCache()
  
  @InjectKeywordedSecretString ( secret_id = 'mysecret' ,  cache = cache ,  func_username = 'username' ,  func_password = 'password' ) 
  def function_to_be_decorated( func_username,  func_password):
       print( 'Do something with the func_username and func_password parameters')
```

# 使用 Python AWS SDK 取得 Secrets Manager 秘密值
<a name="retrieving-secrets-python-sdk"></a>

在應用程式中，您可以透過在任何 AWS SDKs `BatchGetSecretValue`中呼叫 `GetSecretValue`或 來擷取秘密。不過，建議您使用用戶端快取來快取您的秘密值。快取秘密可提高速度並降低成本。

對於 Python 應用程式，請使用 [Secrets Manager Python 型快取元件](retrieving-secrets_cache-python.md)或使用 [https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/secretsmanager/client/get_secret_value.html](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/secretsmanager/client/get_secret_value.html) 或 [https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/secretsmanager/client/batch_get_secret_value.html](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/secretsmanager/client/batch_get_secret_value.html) 直接呼叫 SDK。

下列程式碼範例示範如何使用 `GetSecretValue`。

**必要許可：**`secretsmanager:GetSecretValue`

```
"""
Purpose

Shows how to use the AWS SDK for Python (Boto3) with AWS
Secrets Manager to get a specific of secrets that match a
specified name
"""
import boto3
import logging

from get_secret_value import GetSecretWrapper

# Configure logging
logging.basicConfig(level=logging.INFO)


def run_scenario(secret_name):
    """
    Retrieve a secret from AWS Secrets Manager.

    :param secret_name: Name of the secret to retrieve.
    :type secret_name: str
    """
    try:
        # Validate secret_name
        if not secret_name:
            raise ValueError("Secret name must be provided.")
        # Retrieve the secret by name
        client = boto3.client("secretsmanager")
        wrapper = GetSecretWrapper(client)
        secret = wrapper.get_secret(secret_name)
        # Note: Secrets should not be logged.
        return secret
    except Exception as e:
        logging.error(f"Error retrieving secret: {e}")
        raise

class GetSecretWrapper:
    def __init__(self, secretsmanager_client):
        self.client = secretsmanager_client


    def get_secret(self, secret_name):
        """
        Retrieve individual secrets from AWS Secrets Manager using the get_secret_value API.
        This function assumes the stack mentioned in the source code README has been successfully deployed.
        This stack includes 7 secrets, all of which have names beginning with "mySecret".

        :param secret_name: The name of the secret fetched.
        :type secret_name: str
        """
        try:
            get_secret_value_response = self.client.get_secret_value(
                SecretId=secret_name
            )
            logging.info("Secret retrieved successfully.")
            return get_secret_value_response["SecretString"]
        except self.client.exceptions.ResourceNotFoundException:
            msg = f"The requested secret {secret_name} was not found."
            logger.info(msg)
            return msg
        except Exception as e:
            logger.error(f"An unknown error occurred: {str(e)}.")
            raise
```

# 使用 Python AWS SDK 取得一批 Secrets Manager 秘密值
<a name="retrieving-secrets-python-batch"></a>

下列程式碼範例示範如何取得 Secrets Manager 秘密值的批次。

**必要許可：**
+ `secretsmanager:BatchGetSecretValue` 
+ `secretsmanager:GetSecretValue` 您要擷取之每個秘密的 許可。
+ 如果您使用過濾器，則還必須擁有 `secretsmanager:ListSecrets`。

如需許可政策範例，請參閱 [範例：擷取批次中一組秘密值的許可](auth-and-access_iam-policies.md#auth-and-access_examples_batch)。

**重要**  
如果您的 VPCE 原則拒絕擷取您要擷取之群組中個別密碼的權限，則 `BatchGetSecretValue` 不會傳回任何秘密值，而且會傳回錯誤。

```
class BatchGetSecretsWrapper:
    def __init__(self, secretsmanager_client):
        self.client = secretsmanager_client


    def batch_get_secrets(self, filter_name):
        """
        Retrieve multiple secrets from AWS Secrets Manager using the batch_get_secret_value API.
        This function assumes the stack mentioned in the source code README has been successfully deployed.
        This stack includes 7 secrets, all of which have names beginning with "mySecret".

        :param filter_name: The full or partial name of secrets to be fetched.
        :type filter_name: str
        """
        try:
            secrets = []
            response = self.client.batch_get_secret_value(
                Filters=[{"Key": "name", "Values": [f"{filter_name}"]}]
            )
            for secret in response["SecretValues"]:
                secrets.append(json.loads(secret["SecretString"]))
            if secrets:
                logger.info("Secrets retrieved successfully.")
            else:
                logger.info("Zero secrets returned without error.")
            return secrets
        except self.client.exceptions.ResourceNotFoundException:
            msg = f"One or more requested secrets were not found with filter: {filter_name}"
            logger.info(msg)
            return msg
        except Exception as e:
            logger.error(f"An unknown error occurred:\n{str(e)}.")
            raise
```