

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

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

在应用程序中，您可以通过调用`GetSecretValue`或`BatchGetSecretValue`在任一应用程序中检索您的秘密 AWS SDKs。不过，我们建议您通过使用客户端缓存来缓存您的密钥值。缓存密钥可以提高速度并降低成本。

**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 需要付费 APIs，因此使用缓存可以降低成本。有关检索密钥的所有方法，请参阅 [获取密钥](retrieving-secrets.md)。

缓存策略为“最近最少使用 (LRU)”，因此当缓存必须丢弃某个密钥时，它会丢弃最近使用最少的密钥。原定设置下，缓存会每小时刷新一次秘密。您可以配置在缓存中[刷新密钥的频率](retrieving-secrets_cache-ref-secretcacheconfig.md)，也可以[挂钩到密钥检索中](retrieving-secrets_cache-ref-secretcachehook.md)以添加更多功能。

一旦释放缓存引用，缓存便不会进行强制垃圾回收。缓存实施不包括缓存失效。缓存实现侧重于缓存本身，而不是侧重加强安全性或以安全性为重点。如果您需要额外的安全性（例如加密缓存中的项目），请使用提供的接口和抽象方法。

要使用该组件，您必须满足以下条件：
+ Python 3.6 或更高版本。
+ botocore 1.12 或更高版本。请参阅[适用于 Python](https://aws.amazon.com/sdk-for-python/) 和 [Botocore 的AWS SDK](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/)。

要下载源代码，请参阅上的 S [ecrets 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' )
```

参数  
+ `secret_id`（*字符串*）：[必需] 密钥的名称或 ARN。
+ `version_stage`（*字符串*）：您要检索的密钥的版本。有关更多信息，请参阅 [secret versions](whats-in-a-secret.md)。默认值为“AWSCURRENT”。

返回类型  
字符串

## 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'
)
```

参数  
+ `secret_id`（*字符串*）：[必需] 密钥的名称或 ARN。
+ `version_stage`（*字符串*）：您要检索的密钥的版本。有关更多信息，请参阅 [secret versions](whats-in-a-secret.md)。默认值为“AWSCURRENT”。

返回类型  
[base64 编码的](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)。参数

`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)
+ [入](#retrieving-secrets_cache-ref-secretcachehook_get)

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

使对象为存储在缓存中做好准备。

请求语法  

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

参数  
+ `obj` (*对象*) -- [必需] 密钥或包含密钥的对象。

返回类型  
object

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

从已缓存对象派生对象。

请求语法  

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

参数  
+ `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>

在应用程序中，您可以通过调用`GetSecretValue`或`BatchGetSecretValue`在任一应用程序中检索您的秘密 AWS SDKs。不过，我们建议您通过使用客户端缓存来缓存您的密钥值。缓存密钥可以提高速度并降低成本。

对于 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
```