

Le traduzioni sono generate tramite traduzione automatica. In caso di conflitto tra il contenuto di una traduzione e la versione originale in Inglese, quest'ultima prevarrà.

# Ottieni un valore segreto di Secrets Manager usando Python
<a name="retrieving-secrets-python"></a>

Nelle applicazioni, puoi recuperare i tuoi segreti chiamando `GetSecretValue` o `BatchGetSecretValue` in uno qualsiasi dei. AWS SDKs Tuttavia, ti consigliamo di memorizzare nella cache i valori del segreto utilizzando la caching lato client. Memorizzare i segreti nella cache migliora la velocità e riduce i costi.

**Topics**
+ [

# Ottieni un valore segreto di Secrets Manager usando Python con caching lato client
](retrieving-secrets_cache-python.md)
+ [

# Ottieni un valore segreto di Secrets Manager usando l'SDK Python AWS
](retrieving-secrets-python-sdk.md)
+ [

# Ottieni un batch di valori segreti di Secrets Manager usando Python SDK AWS
](retrieving-secrets-python-batch.md)

# Ottieni un valore segreto di Secrets Manager usando Python con caching lato client
<a name="retrieving-secrets_cache-python"></a>

Quando si recupera un segreto, è possibile utilizzare il componente di caching basato su Python di Secrets Manager per memorizzarlo nella cache per un uso futuro. Il recupero di un segreto memorizzato nella cache è più veloce rispetto al recupero da Secrets Manager. Poiché la chiamata a Secrets Manager comporta un costo APIs, l'utilizzo di una cache può ridurre i costi. Per tutti i modi in cui puoi recuperare i segreti, vedi [Ottieni segreti](retrieving-secrets.md).

La policy della cache è Least Recently Used (LRU), quindi quando la cache deve eliminare un segreto, elimina il segreto usato meno di recente. Di default, la cache aggiorna i segreti ogni ora. È possibile configurare [la frequenza con cui il segreto viene aggiornato](retrieving-secrets_cache-ref-secretcacheconfig.md) nella cache ed è possibile [collegarsi al recupero del segreto](retrieving-secrets_cache-ref-secretcachehook.md) per aggiungere altre funzionalità.

La cache non impone la rimozione di oggetti inutili (garbage collection) una volta liberati i riferimenti alla cache. L'implementazione della cache non include l'invalidazione della cache. L'implementazione della cache è incentrata sulla cache stessa e non è rafforzata o focalizzata sulla sicurezza. Se hai bisogno di un livello di sicurezza aggiuntivo, come la crittografia degli elementi nella cache, usa le interfacce e i metodi astratti forniti.

Per usare il componente, devi disporre dei seguenti elementi: 
+ Python 3.6 o versioni successive.
+ botocore 1.12 o versioni successive. Consulta [AWS SDK for Python](https://aws.amazon.com/sdk-for-python/) e [Botocore](https://botocore.amazonaws.com/v1/documentation/api/latest/index.html). 
+ setuptools\$1scm 3.2 o versioni successive. Vedi [https://pypi. org/project/setuptools-scm/](https://pypi.org/project/setuptools-scm/).

Per scaricare il codice sorgente, consulta il componente client di [caching basato su Python di Secrets Manager](https://github.com/aws/aws-secretsmanager-caching-python ) su. GitHub

Per installare il componente, utilizza il comando seguente.

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

**Autorizzazioni richieste:**
+ `secretsmanager:DescribeSecret`
+ `secretsmanager:GetSecretValue`

Per ulteriori informazioni, consulta [Riferimento per le autorizzazioni](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 Recupero di un segreto**  
L'esempio seguente mostra come ottenere il valore segreto per un segreto denominato. *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>

Una cache in memoria per i segreti recuperati da Secrets Manager. Si usa [get\$1secret\$1string](#retrieving-secrets_cache-ref-secretcache_get_secret_string) o [get\$1secret\$1binary](#retrieving-secrets_cache-ref-secretcache_get_secret_binary) per recuperare un segreto dalla cache. È possibile configurare le impostazioni della cache specificando un oggetto [SecretCacheConfig](retrieving-secrets_cache-ref-secretcacheconfig.md) nel costruttore. 

Per ulteriori informazioni, inclusi esempi, consulta [Ottieni un valore segreto di Secrets Manager usando Python con caching lato client](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>

Recupera il valore della stringa del segreto.

Sintassi della richiesta  

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

Parameters  
+ `secret_id`(*string*): [Obbligatorio] Il nome o l'ARN del segreto.
+ `version_stage`(*stringa*): La versione dei segreti che desideri recuperare. Per ulteriori informazioni, [consulta Versioni segrete](whats-in-a-secret.md). Il valore di default è 'AWSCURRENT'. 

Tipo restituito  
stringa

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

Recupera il valore binario del segreto.

Sintassi della richiesta  

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

Parameters  
+ `secret_id`(*string*): [Obbligatorio] Il nome o l'ARN del segreto.
+ `version_stage`(*stringa*): La versione dei segreti che desideri recuperare. Per ulteriori informazioni, [consulta Versioni segrete](whats-in-a-secret.md). Il valore di default è 'AWSCURRENT'. 

Tipo restituito  
Stringa [con codifica Base64](https://tools.ietf.org/html/rfc4648#section-4)

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

Opzioni di configurazione della cache per una [SecretCache](retrieving-secrets_cache-ref-secretcache.md), ad esempio dimensione massima della cache e durata (TTL) per i segreti memorizzati nella cache.Parameters

`max_cache_size` (*int*)  
La dimensione massima della cache. Il valore predefinito è `1024` segreti. 

`exception_retry_delay_base` (*int*)  
Il numero di secondi di attesa dopo aver riscontrato un'eccezione prima di riprovare la richiesta. Il valore predefinito è `1`.

`exception_retry_growth_factor` (*int*)pur  
Il fattore di crescita da utilizzare per calcolare il tempo di attesa tra i tentativi di richieste non riuscite. Il valore predefinito è `2`. 

`exception_retry_delay_max` (*int*)  
Il numero massimo di secondi di attesa tra le richieste non riuscite. Il valore predefinito è `3600`.

`default_version_stage` (*str*)  
Imposta la versione dei segreti che si desidera memorizzare nella cache. Per ulteriori informazioni, consulta [Versioni del segreto](whats-in-a-secret.md#term_version). Il valore predefinito è `'AWSCURRENT'`.

`secret_refresh_interval` (*int*)  
Il numero di secondi da attendere tra gli aggiornamenti delle informazioni del segreto memorizzate nella cache. Il valore predefinito è `3600`.

`secret_cache_hook` (*SecretCacheHook*)  
Un'implementazione della classe astratta di `SecretCacheHook`. Il valore predefinito è `None`.

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

Un'interfaccia per collegarsi a una [SecretCache](retrieving-secrets_cache-ref-secretcache.md) per eseguire operazioni sui segreti memorizzati al suo interno. 

**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>

Prepara l'oggetto per la memorizzazione nella cache.

Sintassi della richiesta  

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

Parameters  
+ `obj` (*object*) -- [Obbligatorio] Il segreto o l'oggetto che contiene il segreto.

Tipo restituito  
oggetto

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

Deriva l'oggetto dall'oggetto memorizzato nella cache.

Sintassi della richiesta  

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

Parameters  
+ `obj`(*oggetto*): [Obbligatorio] Il segreto o l'oggetto che contiene il segreto.

Tipo restituito  
oggetto

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

Questo decoratore prevede una stringa identificativa del segreto e [SecretCache](retrieving-secrets_cache-ref-secretcache.md) come primo e secondo argomento. Il decoratore restituisce il valore della stringa del segreto. Il segreto deve contenere una stringa. 

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

Questo decoratore prevede una stringa identificativa del segreto e [SecretCache](retrieving-secrets_cache-ref-secretcache.md) come primo e secondo argomento. Gli argomenti rimanenti mappano i parametri dalla funzione wrapping alle chiavi JSON nel segreto. Il segreto deve contenere una stringa nella struttura JSON. 

Per un segreto che contiene questo JSON:

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

Gli esempi seguenti mostrano come estrarre i valori JSON per `username` e `password` dal segreto.

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

# Ottieni un valore segreto di Secrets Manager usando l'SDK Python AWS
<a name="retrieving-secrets-python-sdk"></a>

Nelle applicazioni, puoi recuperare i tuoi segreti chiamando `GetSecretValue` o `BatchGetSecretValue` in uno qualsiasi dei. AWS SDKs Tuttavia, ti consigliamo di memorizzare nella cache i valori del segreto utilizzando la caching lato client. Memorizzare i segreti nella cache migliora la velocità e riduce i costi.

Per le applicazioni Python, utilizza il [componente di caching basato su Python di Secrets Manager](retrieving-secrets_cache-python.md) o chiama direttamente l'SDK con [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) o [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).

Gli esempi di codice seguenti mostrano come utilizzare `GetSecretValue`.

**Autorizzazioni richieste:**`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
```

# Ottieni un batch di valori segreti di Secrets Manager usando Python SDK AWS
<a name="retrieving-secrets-python-batch"></a>

Il seguente esempio di codice mostra come ottenere un batch di valori segreti di Secrets Manager.

**Autorizzazioni richieste:**
+ `secretsmanager:BatchGetSecretValue` 
+ `secretsmanager:GetSecretValue`autorizzazione per ogni segreto che desideri recuperare.
+ Se usi i filtri, devi avere anche `secretsmanager:ListSecrets`. 

Per un esempio di policy delle autorizzazioni, consulta [Esempio: autorizzazione a recuperare un gruppo di valori segreti in un batch](auth-and-access_iam-policies.md#auth-and-access_examples_batch).

**Importante**  
Se hai una policy VPCE che nega l'autorizzazione per recuperare un singolo segreto nel gruppo su cui stai agendo, `BatchGetSecretValue` non restituirà alcun valore segreto e restituirà un errore.

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