

# Get secrets from AWS Secrets Manager
<a name="retrieving-secrets"></a>

Secrets Manager generates a CloudTrail log entry when you retrieve a secret. For more information, see [Log AWS Secrets Manager events with AWS CloudTrail](monitoring-cloudtrail.md).

**Topics**
+ [Java](retrieving-secrets-java.md)
+ [Python](retrieving-secrets-python.md)
+ [.NET](retrieving-secrets-net.md)
+ [Go](retrieving-secrets-go.md)
+ [Rust](retrieving-secrets-rust.md)
+ [Amazon EKS](integrate_eks.md)
+ [AWS Lambda](retrieving-secrets_lambda.md)
+ [Secrets Manager Agent](secrets-manager-agent.md)
+ [C\$1\$1](retrieving-secrets-cpp.md)
+ [JavaScript](retrieving-secrets-javascript.md)
+ [Kotlin](retrieving-secrets-kotlin.md)
+ [PHP](retrieving-secrets-php.md)
+ [Ruby](retrieving-secrets-ruby.md)
+ [AWS CLI](retrieving-secrets_cli.md)
+ [AWS console](retrieving-secrets-console.md)
+ [AWS Batch](integrating_BATCH.md)
+ [CloudFormation](cfn-example_reference-secret.md)
+ [GitHub jobs](retrieving-secrets_github.md)
+ [GitLab](integrating_gitlab.md)
+ [AWS IoT Greengrass](integrating-greengrass.md)
+ [Parameter Store](integrating_parameterstore.md)

# Get a Secrets Manager secret value using Java
<a name="retrieving-secrets-java"></a>

In applications, you can retrieve your secrets by calling `GetSecretValue` or `BatchGetSecretValue`in any of the AWS SDKs. However, we recommend that you cache your secret values by using client-side caching. Caching secrets improves speed and reduces your costs.

To connect to a database using the credentials in a secret, you can use the Secrets Manager SQL Connection drivers, which wrap the base JDBC driver. This also uses client-side caching, so it can reduce the cost for calling Secrets Manager APIs.

**Topics**
+ [

# Get a Secrets Manager secret value using Java with client-side caching
](retrieving-secrets_cache-java.md)
+ [

# Connect to a SQL database using JDBC with credentials in an AWS Secrets Manager secret
](retrieving-secrets_jdbc.md)
+ [

# Get a Secrets Manager secret value using the Java AWS SDK
](retrieving-secrets-java-sdk.md)

# Get a Secrets Manager secret value using Java with client-side caching
<a name="retrieving-secrets_cache-java"></a>

When you retrieve a secret, you can use the Secrets Manager Java-based caching component to cache it for future use. Retrieving a cached secret is faster than retrieving it from Secrets Manager. Because there is a cost for calling Secrets Manager APIs, using a cache can reduce your costs. For all of the ways you can retrieve secrets, see [Get secrets](retrieving-secrets.md).

The cache policy is Least Recently Used (LRU), so when the cache must discard a secret, it discards the least recently used secret. By default, the cache refreshes secrets every hour. You can configure [how often the secret is refreshed](retrieving-secrets_cache-java-ref_SecretCacheConfiguration.md#retrieving-secrets_cache-java-ref_SecretCacheConfiguration_methods-getCacheItemTTL) in the cache, and you can [hook into the secret retrieval](retrieving-secrets_cache-java-ref_SecretCacheHook.md) to add more functionality.

The cache does not force garbage collection once cache references are freed. The cache implementation does not include cache invalidation. The cache implementation is focused around the cache itself, and is not security hardened or focused. If you require additional security such as encrypting items in the cache, use the interfaces and abstract methods provided.

To use the component, you must have the following: 
+ A Java 8 or higher development environment. See [Java SE Downloads](https://www.oracle.com/technetwork/java/javase/downloads/index.html) on the Oracle website.

To download the source code, see [Secrets Manager Java-based caching client component](https://github.com/aws/aws-secretsmanager-caching-java) on GitHub.

To add the component to your project, in your Maven pom.xml file, include the following dependency. For more information about Maven, see the [Getting Started Guide](https://maven.apache.org/guides/getting-started/index.html) on the Apache Maven Project website.

```
<dependency>
  <groupId>com.amazonaws.secretsmanager</groupId>
  <artifactId>aws-secretsmanager-caching-java</artifactId>
  <version>1.0.2</version>
</dependency>
```

**Required permissions: **
+ `secretsmanager:DescribeSecret`
+ `secretsmanager:GetSecretValue`

For more information, see [Permissions reference](auth-and-access.md#reference_iam-permissions).

**Topics**
+ [

# SecretCache
](retrieving-secrets_cache-java-ref_SecretCache.md)
+ [

# SecretCacheConfiguration
](retrieving-secrets_cache-java-ref_SecretCacheConfiguration.md)
+ [

# SecretCacheHook
](retrieving-secrets_cache-java-ref_SecretCacheHook.md)

**Example Retrieve a secret**  
The following code example shows a Lambda function that retrieves a secret string. It follows the [best practice](https://docs.aws.amazon.com/lambda/latest/dg/best-practices.html) of instantiating the cache outside of the function handler, so it doesn't keep calling the API if you call the Lambda function again.  

```
package com.amazonaws.secretsmanager.caching.examples;
    
    import com.amazonaws.services.lambda.runtime.Context;
    import com.amazonaws.services.lambda.runtime.RequestHandler;
    import com.amazonaws.services.lambda.runtime.LambdaLogger;
    
    import com.amazonaws.secretsmanager.caching.SecretCache;
    
    public class SampleClass implements RequestHandler<String, String> {
    
         private final SecretCache cache  = new SecretCache();
    
         @Override public String handleRequest(String secretId,  Context context) {
             final String secret  = cache.getSecretString(secretId);
    
            // Use the secret, return success;
    
        }
    }
```

# SecretCache
<a name="retrieving-secrets_cache-java-ref_SecretCache"></a>

An in-memory cache for secrets requested from Secrets Manager. You use [getSecretString](#retrieving-secrets_cache-java-ref_SecretCache-methods-getSecretString) or [getSecretBinary](#retrieving-secrets_cache-java-ref_SecretCache-methods-getSecretBinary) to retrieve a secret from the cache. You can configure the cache settings by passing in a [SecretCacheConfiguration](retrieving-secrets_cache-java-ref_SecretCacheConfiguration.md) object in the constructor. 

For more information, including examples, see [Get a Secrets Manager secret value using Java with client-side caching](retrieving-secrets_cache-java.md).

## Constructors
<a name="retrieving-secrets_cache-java-ref_SecretCache-constructors"></a>

`public SecretCache()`  
Default constructor for a `SecretCache` object.

`public SecretCache(AWSSecretsManagerClientBuilder builder)`  
Constructs a new cache using a Secrets Manager client created using the provided [https://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/secretsmanager/AWSSecretsManagerClientBuilder.html](https://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/secretsmanager/AWSSecretsManagerClientBuilder.html). Use this constructor to customize the Secrets Manager client, for example to use a specific Region or endpoint.

`public SecretCache(AWSSecretsManager client)`  
Constructs a new secret cache using the provided [https://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/secretsmanager/AWSSecretsManagerClient.html](https://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/secretsmanager/AWSSecretsManagerClient.html). Use this constructor to customize the Secrets Manager client, for example to use a specific Region or endpoint.

`public SecretCache(SecretCacheConfiguration config)`  
Constructs a new secret cache using the provided `SecretCacheConfiguration`.

## Methods
<a name="retrieving-secrets_cache-java-ref_SecretCache-methods"></a>

### getSecretString
<a name="retrieving-secrets_cache-java-ref_SecretCache-methods-getSecretString"></a>

`public String getSecretString(final String secretId)`

Retrieves a string secret from Secrets Manager. Returns a [https://docs.oracle.com/javase/7/docs/api/java/lang/String.html?is-external=true](https://docs.oracle.com/javase/7/docs/api/java/lang/String.html?is-external=true).

### getSecretBinary
<a name="retrieving-secrets_cache-java-ref_SecretCache-methods-getSecretBinary"></a>

`public ByteBuffer getSecretBinary(final String secretId)`

Retrieves a binary secret from Secrets Manager. Returns a [https://docs.oracle.com/javase/7/docs/api/java/nio/ByteBuffer.html](https://docs.oracle.com/javase/7/docs/api/java/nio/ByteBuffer.html).

### refreshNow
<a name="retrieving-secrets_cache-java-ref_SecretCache-methods-refreshNow"></a>

`public boolean refreshNow(final String secretId) throws InterruptedException`

Forces the cache to refresh. Returns `true` if the refresh completed without error, otherwise `false`.

### close
<a name="retrieving-secrets_cache-java-ref_SecretCache-methods-close"></a>

`public void close()`

Closes the cache.

# SecretCacheConfiguration
<a name="retrieving-secrets_cache-java-ref_SecretCacheConfiguration"></a>

Cache configuration options for a [SecretCache](retrieving-secrets_cache-java-ref_SecretCache.md), such as max cache size and Time to Live (TTL) for cached secrets.

## Constructor
<a name="retrieving-secrets_cache-java-ref_SecretCacheConfiguration_constructor"></a>

`public SecretCacheConfiguration`

Default constructor for a `SecretCacheConfiguration` object.

## Methods
<a name="retrieving-secrets_cache-java-ref_SecretCacheConfiguration_methods"></a>

### getClient
<a name="retrieving-secrets_cache-java-ref_SecretCacheConfiguration_methods-getClient"></a>

`public AWSSecretsManager getClient()`

Returns the [https://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/secretsmanager/AWSSecretsManagerClient.html](https://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/secretsmanager/AWSSecretsManagerClient.html) that the cache retrieves secrets from.

### setClient
<a name="retrieving-secrets_cache-java-ref_SecretCacheConfiguration_methods-setClient"></a>

`public void setClient(AWSSecretsManager client)`

Sets the [https://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/secretsmanager/AWSSecretsManagerClient.html](https://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/secretsmanager/AWSSecretsManagerClient.html) client that the cache retrieves secrets from.

### getCacheHook
<a name="retrieving-secrets_cache-java-ref_SecretCacheConfiguration_methods-getCacheHook"></a>

`public SecretCacheHook getCacheHook()`

Returns the [SecretCacheHook](retrieving-secrets_cache-java-ref_SecretCacheHook.md) interface used to hook cache updates.

### setCacheHook
<a name="retrieving-secrets_cache-java-ref_SecretCacheConfiguration_methods-setCacheHook"></a>

`public void setCacheHook(SecretCacheHook cacheHook)`

Sets the [SecretCacheHook](retrieving-secrets_cache-java-ref_SecretCacheHook.md) interface used to hook cache updates.

### getMaxCacheSize
<a name="retrieving-secrets_cache-java-ref_SecretCacheConfiguration_methods-getMaxCacheSize"></a>

`public int getMaxCacheSize()`

Returns the maximum cache size. The default is 1024 secrets.

### setMaxCacheSize
<a name="retrieving-secrets_cache-java-ref_SecretCacheConfiguration_methods-setMaxCacheSize"></a>

`public void setMaxCacheSize(int maxCacheSize)`

Sets the maximum cache size. The default is 1024 secrets.

### getCacheItemTTL
<a name="retrieving-secrets_cache-java-ref_SecretCacheConfiguration_methods-getCacheItemTTL"></a>

`public long getCacheItemTTL()`

Returns the TTL in milliseconds for the cached items. When a cached secret exceeds this TTL, the cache retrieves a new copy of the secret from the [https://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/secretsmanager/AWSSecretsManagerClient.html](https://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/secretsmanager/AWSSecretsManagerClient.html). The default is 1 hour in milliseconds. 

The cache refreshes the secret synchronously when the secret is requested after the TTL. If the synchronous refresh fails, the cache returns the stale secret. 

### setCacheItemTTL
<a name="retrieving-secrets_cache-java-ref_SecretCacheConfiguration_methods-setCacheItemTTL"></a>

`public void setCacheItemTTL(long cacheItemTTL)`

Sets the TTL in milliseconds for the cached items. When a cached secret exceeds this TTL, the cache retrieves a new copy of the secret from the [https://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/secretsmanager/AWSSecretsManagerClient.html](https://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/secretsmanager/AWSSecretsManagerClient.html). The default is 1 hour in milliseconds.

### getVersionStage
<a name="retrieving-secrets_cache-java-ref_SecretCacheConfiguration_methods-getVersionStage"></a>

`public String getVersionStage()`

Returns the version of secrets that you want to cache. For more information, see [Secret versions](whats-in-a-secret.md#term_version). The default is` "AWSCURRENT"`.

### setVersionStage
<a name="retrieving-secrets_cache-java-ref_SecretCacheConfiguration_methods-setVersionStage"></a>

`public void setVersionStage(String versionStage)`

Sets the version of secrets that you want to cache. For more information, see [Secret versions](whats-in-a-secret.md#term_version). The default is `"AWSCURRENT"`.

### SecretCacheConfiguration withClient
<a name="retrieving-secrets_cache-java-ref_SecretCacheConfiguration_methods-withClient"></a>

`public SecretCacheConfiguration withClient(AWSSecretsManager client)`

Sets the [https://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/secretsmanager/AWSSecretsManagerClient.html](https://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/secretsmanager/AWSSecretsManagerClient.html) to retrieve secrets from. Returns the updated `SecretCacheConfiguration` object with the new setting.

### SecretCacheConfiguration withCacheHook
<a name="retrieving-secrets_cache-java-ref_SecretCacheConfiguration_methods-withCacheHook"></a>

`public SecretCacheConfiguration withCacheHook(SecretCacheHook cacheHook)`

Sets the interface used to hook the in-memory cache. Returns the updated `SecretCacheConfiguration` object with the new setting.

### SecretCacheConfiguration withMaxCacheSize
<a name="retrieving-secrets_cache-java-ref_SecretCacheConfiguration_methods-withMaxCacheSize"></a>

`public SecretCacheConfiguration withMaxCacheSize(int maxCacheSize)`

Sets the maximum cache size. Returns the updated `SecretCacheConfiguration` object with the new setting.

### SecretCacheConfiguration withCacheItemTTL
<a name="retrieving-secrets_cache-java-ref_SecretCacheConfiguration_methods-withCacheItemTTL"></a>

`public SecretCacheConfiguration withCacheItemTTL(long cacheItemTTL)`

Sets the TTL in milliseconds for the cached items. When a cached secret exceeds this TTL, the cache retrieves a new copy of the secret from the [https://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/secretsmanager/AWSSecretsManagerClient.html](https://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/secretsmanager/AWSSecretsManagerClient.html). The default is 1 hour in milliseconds. Returns the updated `SecretCacheConfiguration` object with the new setting.

### SecretCacheConfiguration withVersionStage
<a name="retrieving-secrets_cache-java-ref_SecretCacheConfiguration_methods-withVersionStage"></a>

`public SecretCacheConfiguration withVersionStage(String versionStage)`

Sets the version of secrets that you want to cache. For more information, see [Secret versions](whats-in-a-secret.md#term_version). Returns the updated `SecretCacheConfiguration` object with the new setting.

# SecretCacheHook
<a name="retrieving-secrets_cache-java-ref_SecretCacheHook"></a>

An interface to hook into a [SecretCache](retrieving-secrets_cache-java-ref_SecretCache.md) to perform actions on the secrets being stored in the cache. 

## put
<a name="retrieving-secrets_cache-java-ref_SecretCacheHook-put"></a>

`Object put(final Object o)`

Prepare the object for storing in the cache.

Returns the object to store in the cache.

## get
<a name="retrieving-secrets_cache-java-ref_SecretCacheHook-get"></a>

`Object get(final Object cachedObject)`

Derive the object from the cached object.

Returns the object to return from the cache

# Connect to a SQL database using JDBC with credentials in an AWS Secrets Manager secret
<a name="retrieving-secrets_jdbc"></a>

In Java applications, you can use the Secrets Manager SQL Connection drivers to connect to MySQL, PostgreSQL, Oracle, MSSQLServer, Db2, and Redshift databases using credentials stored in Secrets Manager. Each driver wraps the base JDBC driver, so you can use JDBC calls to access your database. However, instead of passing a username and password for the connection, you provide the ID of a secret. The driver calls Secrets Manager to retrieve the secret value, and then uses the credentials in the secret to connect to the database. The driver also caches the credentials using the [Java client-side caching library](retrieving-secrets_cache-java.md), so future connections don't require a call to Secrets Manager. By default, the cache refreshes every hour and also when the secret is rotated. To configure the cache, see [SecretCacheConfiguration](retrieving-secrets_cache-java-ref_SecretCacheConfiguration.md).

You can download the source code from [GitHub](https://github.com/aws/aws-secretsmanager-jdbc ).

To use the Secrets Manager SQL Connection drivers:
+ Your application must be in Java 8 or higher.
+ Your secret must be one of the following:
  + A [database secret in the expected JSON structure](reference_secret_json_structure.md). To check the format, in the Secrets Manager console, view your secret and choose **Retrieve secret value**. Alternatively, in the AWS CLI, call [get-secret-value](https://docs.aws.amazon.com/cli/latest/reference/secretsmanager/get-secret-value.html).
  + An Amazon RDS [managed secret](integrating_how-services-use-secrets_RDS.md). For this type of secret, you must specify an endpoint and port when you establish the connection.
  + An Amazon Redshift [managed secret](integrating_how-services-use-secrets_RS.md). For this type of secret, you must specify an endpoint and port when you establish the connection.

If your database is replicated to other Regions, to connect to a replica database in another Region, you specify the regional endpoint and port when you create the connection. You can store regional connection information in the secret as extra key/value pairs, in SSM Parameter Store parameters, or in your code configuration. 

To add the driver to your project, in your Maven build file `pom.xml`, add the following dependency for the driver. For more information, see [Secrets Manager SQL Connection Library](https://search.maven.org/artifact/com.amazonaws.secretsmanager/aws-secretsmanager-jdbc) on the Maven Central Repository website.

```
<dependency>
    <groupId>com.amazonaws.secretsmanager</groupId>
    <artifactId>aws-secretsmanager-jdbc</artifactId>
    <version>1.0.12</version>
</dependency>
```

The driver uses the [https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/credentials.html](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/credentials.html). If you run the driver on Amazon EKS, it might pick up the credentials of the node it is running on instead of the service account role. To address this, add version 1 of `com.amazonaws:aws-java-sdk-sts` to your Gradle or Maven project file as a dependency.

To set an AWS PrivateLink DNS endpoint URL and a region in the `secretsmanager.properties` file:

```
drivers.vpcEndpointUrl = endpoint URL
drivers.vpcEndpointRegion = endpoint region
```

To override the primary region, set the `AWS_SECRET_JDBC_REGION` environment variable or make the following change to the `secretsmanager.properties` file:

```
drivers.region = region
```

**Required permissions: **
+ `secretsmanager:DescribeSecret`
+ `secretsmanager:GetSecretValue`

For more information, see [Permissions reference](auth-and-access.md#reference_iam-permissions).

**Topics**
+ [

## Establish a connection to a database
](#retrieving-secrets_jdbc_example)
+ [

## Establish a connection by specifying the endpoint and port
](#retrieving-secrets_jdbc_example_replica)
+ [

## Use c3p0 connection pooling to establish a connection
](#retrieving-secrets_jdbc_example_c3po)
+ [

## Use c3p0 connection pooling to establish a connection by specifying the endpoint and port
](#retrieving-secrets_jdbc_example_c3p0_replica)

## Establish a connection to a database
<a name="retrieving-secrets_jdbc_example"></a>

The following example shows how to establish a connection to a database using the credentials and connection information in a secret. Once you have the connection, you can use JDBC calls to access the database. For more information, see [JDBC Basics](https://docs.oracle.com/javase/tutorial/jdbc/basics/index.html) on the Java documentation website.

------
#### [ MySQL ]

```
// Load the JDBC driver
Class.forName( "com.amazonaws.secretsmanager.sql.AWSSecretsManagerMySQLDriver" ).newInstance();

// Retrieve the connection info from the secret using the secret ARN
String URL = "secretId";

// Populate the user property with the secret ARN to retrieve user and password from the secret
Properties info = new Properties( );
info.put( "user", "secretId" );

// Establish the connection
conn = DriverManager.getConnection(URL, info);
```

------
#### [ PostgreSQL ]

```
// Load the JDBC driver
Class.forName( "com.amazonaws.secretsmanager.sql.AWSSecretsManagerPostgreSQLDriver" ).newInstance();

// Retrieve the connection info from the secret using the secret ARN
String URL = "secretId";

// Populate the user property with the secret ARN to retrieve user and password from the secret
Properties info = new Properties( );
info.put( "user", "secretId" );

// Establish the connection
conn = DriverManager.getConnection(URL, info);
```

------
#### [ Oracle ]

```
// Load the JDBC driver
Class.forName( "com.amazonaws.secretsmanager.sql.AWSSecretsManagerOracleDriver" ).newInstance();

// Retrieve the connection info from the secret using the secret ARN
String URL = "secretId";

// Populate the user property with the secret ARN to retrieve user and password from the secret
Properties info = new Properties( );
info.put( "user", "secretId" );

// Establish the connection
conn = DriverManager.getConnection(URL, info);
```

------
#### [ MSSQLServer ]

```
// Load the JDBC driver
Class.forName( "com.amazonaws.secretsmanager.sql.AWSSecretsManagerMSSQLServerDriver" ).newInstance();

// Retrieve the connection info from the secret using the secret ARN
String URL = "secretId";

// Populate the user property with the secret ARN to retrieve user and password from the secret
Properties info = new Properties( );
info.put( "user", "secretId" );

// Establish the connection
conn = DriverManager.getConnection(URL, info);
```

------
#### [ Db2 ]

```
// Load the JDBC driver
Class.forName( "com.amazonaws.secretsmanager.sql.AWSSecretsManagerDb2Driver" ).newInstance();

// Retrieve the connection info from the secret using the secret ARN
String URL = "secretId";

// Populate the user property with the secret ARN to retrieve user and password from the secret
Properties info = new Properties( );
info.put( "user", "secretId" );

// Establish the connection
conn = DriverManager.getConnection(URL, info);
```

------
#### [ Redshift ]

```
// Load the JDBC driver
Class.forName( "com.amazonaws.secretsmanager.sql.AWSSecretsManagerRedshiftDriver" ).newInstance();

// Retrieve the connection info from the secret using the secret ARN
String URL = "secretId";

// Populate the user property with the secret ARN to retrieve user and password from the secret
Properties info = new Properties( );
info.put( "user", "secretId" );

// Establish the connection
conn = DriverManager.getConnection(URL, info);
```

------

## Establish a connection by specifying the endpoint and port
<a name="retrieving-secrets_jdbc_example_replica"></a>

The following example shows how to establish a connection to a database using the credentials in a secret with an endpoint and port that you specify. 

[Amazon RDS managed secrets](integrating_how-services-use-secrets_RDS.md) don't include the endpoint and port of the database. To connect to a database using master credentials in a secret that's managed by Amazon RDS, you specify them in your code. 

[Secrets that are replicated to other Regions](replicate-secrets.md) can improve latency for the connection to the regional database, but they do not contain different connection information from the source secret. Each replica is a copy of the source secret. To store regional connection information in the secret, add more key/value pairs for the endpoint and port information for the Regions. 

Once you have the connection, you can use JDBC calls to access the database. For more information, see [JDBC Basics](https://docs.oracle.com/javase/tutorial/jdbc/basics/index.html) on the Java documentation website.

------
#### [ MySQL ]

```
// Load the JDBC driver
Class.forName( "com.amazonaws.secretsmanager.sql.AWSSecretsManagerMySQLDriver" ).newInstance();

// Set the endpoint and port. You can also retrieve it from a key/value pair in the secret.
String URL = "jdbc-secretsmanager:mysql://example.com:3306";

// Populate the user property with the secret ARN to retrieve user and password from the secret
Properties info = new Properties( );
info.put( "user", "secretId" );

// Establish the connection
conn = DriverManager.getConnection(URL, info);
```

------
#### [ PostgreSQL ]

```
// Load the JDBC driver
Class.forName( "com.amazonaws.secretsmanager.sql.AWSSecretsManagerPostgreSQLDriver" ).newInstance();

// Set the endpoint and port. You can also retrieve it from a key/value pair in the secret.
String URL = "jdbc-secretsmanager:postgresql://example.com:5432/database";

// Populate the user property with the secret ARN to retrieve user and password from the secret
Properties info = new Properties( );
info.put( "user", "secretId" );

// Establish the connection
conn = DriverManager.getConnection(URL, info);
```

------
#### [ Oracle ]

```
// Load the JDBC driver
Class.forName( "com.amazonaws.secretsmanager.sql.AWSSecretsManagerOracleDriver" ).newInstance();

// Set the endpoint and port. You can also retrieve it from a key/value pair in the secret.
String URL = "jdbc-secretsmanager:oracle:thin:@example.com:1521/ORCL";

// Populate the user property with the secret ARN to retrieve user and password from the secret
Properties info = new Properties( );
info.put( "user", "secretId" );

// Establish the connection
conn = DriverManager.getConnection(URL, info);
```

------
#### [ MSSQLServer ]

```
// Load the JDBC driver
Class.forName( "com.amazonaws.secretsmanager.sql.AWSSecretsManagerMSSQLServerDriver" ).newInstance();

// Set the endpoint and port. You can also retrieve it from a key/value pair in the secret.
String URL = "jdbc-secretsmanager:sqlserver://example.com:1433";

// Populate the user property with the secret ARN to retrieve user and password from the secret
Properties info = new Properties( );
info.put( "user", "secretId" );

// Establish the connection
conn = DriverManager.getConnection(URL, info);
```

------
#### [ Db2 ]

```
// Load the JDBC driver
Class.forName( "com.amazonaws.com.rproxy.goskope.com.amazonaws.secretsmanager.sql.AWSSecretsManagerDb2Driver" ).newInstance();

// Set the endpoint and port. You can also retrieve it from a key/value pair in the secret.
String URL = "jdbc-secretsmanager:db2://example.com:50000";

// Populate the user property with the secret ARN to retrieve user and password from the secret
Properties info = new Properties( );
info.put( "user", "secretId" );

// Establish the connection
conn = DriverManager.getConnection(URL, info);
```

------
#### [ Redshift ]

```
// Load the JDBC driver
Class.forName( "com.amazonaws.com.rproxy.goskope.com.amazonaws.secretsmanager.sql.AWSSecretsManagerRedshiftDriver" ).newInstance();

// Set the endpoint and port. You can also retrieve it from a key/value pair in the secret.
String URL = "jdbc-secretsmanager:redshift://example.com:5439";

// Populate the user property with the secret ARN to retrieve user and password from the secret
Properties info = new Properties( );
info.put( "user", "secretId" );

// Establish the connection
conn = DriverManager.getConnection(URL, info);
```

------

## Use c3p0 connection pooling to establish a connection
<a name="retrieving-secrets_jdbc_example_c3po"></a>

The following example shows how to establish a connection pool with a `c3p0.properties` file that uses the driver to retrieve credentials and connection information from the secret. For `user` and `jdbcUrl`, enter the secret ID to configure the connection pool. Then you can retrieve connections from the pool and use them as any other database connections. For more information, see [JDBC Basics](https://docs.oracle.com/javase/tutorial/jdbc/basics/index.html) on the Java documentation website.

For more information about c3p0, see [c3p0](https://www.mchange.com/projects/c3p0/) on the Machinery For Change website. 

------
#### [ MySQL ]

```
c3p0.user=secretId
c3p0.driverClass=com.amazonaws.secretsmanager.sql.AWSSecretsManagerMySQLDriver
c3p0.jdbcUrl=secretId
```

------
#### [ PostgreSQL ]

```
c3p0.user=secretId
c3p0.driverClass=com.amazonaws.secretsmanager.sql.AWSSecretsManagerPostgreSQLDriver
c3p0.jdbcUrl=secretId
```

------
#### [ Oracle ]

```
c3p0.user=secretId
c3p0.driverClass=com.amazonaws.secretsmanager.sql.AWSSecretsManagerOracleDriver
c3p0.jdbcUrl=secretId
```

------
#### [ MSSQLServer ]

```
c3p0.user=secretId
c3p0.driverClass=com.amazonaws.secretsmanager.sql.AWSSecretsManagerMSSQLServerDriver
c3p0.jdbcUrl=secretId
```

------
#### [ Db2 ]

```
c3p0.user=secretId
c3p0.driverClass=com.amazonaws.secretsmanager.sql.AWSSecretsManagerDb2Driver
c3p0.jdbcUrl=secretId
```

------
#### [ Redshift ]

```
c3p0.user=secretId
c3p0.driverClass=com.amazonaws.secretsmanager.sql.AWSSecretsManagerRedshiftDriver
c3p0.jdbcUrl=secretId
```

------

## Use c3p0 connection pooling to establish a connection by specifying the endpoint and port
<a name="retrieving-secrets_jdbc_example_c3p0_replica"></a>

The following example shows how to establish a connection pool with a `c3p0.properties` file that uses the driver to retrieve credentials in a secret with an endpoint and port that you specify. Then you can retrieve connections from the pool and use them as any other database connections. For more information, see [JDBC Basics](https://docs.oracle.com/javase/tutorial/jdbc/basics/index.html) on the Java documentation website.

[Amazon RDS managed secrets](integrating_how-services-use-secrets_RDS.md) don't include the endpoint and port of the database. To connect to a database using master credentials in a secret that's managed by Amazon RDS, you specify them in your code. 

[Secrets that are replicated to other Regions](replicate-secrets.md) can improve latency for the connection to the regional database, but they do not contain different connection information from the source secret. Each replica is a copy of the source secret. To store regional connection information in the secret, add more key/value pairs for the endpoint and port information for the Regions. 

------
#### [ MySQL ]

```
c3p0.user=secretId
c3p0.driverClass=com.amazonaws.secretsmanager.sql.AWSSecretsManagerMySQLDriver
c3p0.jdbcUrl=jdbc-secretsmanager:mysql://example.com:3306
```

------
#### [ PostgreSQL ]

```
c3p0.user=secretId
c3p0.driverClass=com.amazonaws.secretsmanager.sql.AWSSecretsManagerPostgreSQLDriver
c3p0.jdbcUrl=jdbc-secretsmanager:postgresql://example.com:5432/database
```

------
#### [ Oracle ]

```
c3p0.user=secretId
c3p0.driverClass=com.amazonaws.secretsmanager.sql.AWSSecretsManagerOracleDriver
c3p0.jdbcUrl=jdbc-secretsmanager:oracle:thin:@example.com:1521/ORCL
```

------
#### [ MSSQLServer ]

```
c3p0.user=secretId
c3p0.driverClass=com.amazonaws.secretsmanager.sql.AWSSecretsManagerMSSQLServerDriver
c3p0.jdbcUrl=jdbc-secretsmanager:sqlserver://example.com:1433
```

------
#### [ Db2 ]

```
c3p0.user=secretId
c3p0.driverClass=com.amazonaws.secretsmanager.sql.AWSSecretsManagerDb2Driver
c3p0.jdbcUrl=jdbc-secretsmanager:db2://example.com:50000
```

------
#### [ Redshift ]

```
c3p0.user=secretId
c3p0.driverClass=com.amazonaws.secretsmanager.sql.AWSSecretsManagerRedshiftDriver
c3p0.jdbcUrl=jdbc-secretsmanager:redshift://example.com:5439
```

------

# Get a Secrets Manager secret value using the Java AWS SDK
<a name="retrieving-secrets-java-sdk"></a>

In applications, you can retrieve your secrets by calling `GetSecretValue` or `BatchGetSecretValue`in any of the AWS SDKs. However, we recommend that you cache your secret values by using client-side caching. Caching secrets improves speed and reduces your costs.
+ If you store database credentials in the secret, use the [Secrets Manager SQL connection drivers](retrieving-secrets_jdbc.md) to connect to a database using the credentials in the secret. 
+ For other types of secrets, use the [Secrets Manager Java-based caching component](retrieving-secrets_cache-java.md) or call the SDK directly with [https://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/secretsmanager/model/GetSecretValueResult.html](https://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/secretsmanager/model/GetSecretValueResult.html) or [https://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/secretsmanager/model/BatchGetSecretValueResult.html](https://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/secretsmanager/model/BatchGetSecretValueResult.html).

The following code examples show how to use `GetSecretValue`.

**Required permissions: **`secretsmanager:GetSecretValue`

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.secretsmanager.SecretsManagerClient;
import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueRequest;
import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueResponse;
import software.amazon.awssdk.services.secretsmanager.model.SecretsManagerException;

/**
 * Before running this Java V2 code example, set up your development
 * environment, including your credentials.
 *
 * For more information, see the following documentation topic:
 *
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 *
 * We recommend that you cache your secret values by using client-side caching.
 *
 * Caching secrets improves speed and reduces your costs. For more information,
 * see the following documentation topic:
 *
 * https://docs.aws.amazon.com/secretsmanager/latest/userguide/retrieving-secrets.html
 */
public class GetSecretValue {
    public static void main(String[] args) {
        final String usage = """

                Usage:
                    <secretName>\s

                Where:
                    secretName - The name of the secret (for example, tutorials/MyFirstSecret).\s
                """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String secretName = args[0];
        Region region = Region.US_EAST_1;
        SecretsManagerClient secretsClient = SecretsManagerClient.builder()
                .region(region)
                .build();

        getValue(secretsClient, secretName);
        secretsClient.close();
    }

    public static void getValue(SecretsManagerClient secretsClient, String secretName) {
        try {
            GetSecretValueRequest valueRequest = GetSecretValueRequest.builder()
                    .secretId(secretName)
                    .build();

            GetSecretValueResponse valueResponse = secretsClient.getSecretValue(valueRequest);
            String secret = valueResponse.secretString();
            System.out.println(secret);

        } catch (SecretsManagerException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```

# Get a Secrets Manager secret value using Python
<a name="retrieving-secrets-python"></a>

In applications, you can retrieve your secrets by calling `GetSecretValue` or `BatchGetSecretValue`in any of the AWS SDKs. However, we recommend that you cache your secret values by using client-side caching. Caching secrets improves speed and reduces your costs.

**Topics**
+ [

# Get a Secrets Manager secret value using Python with client-side caching
](retrieving-secrets_cache-python.md)
+ [

# Get a Secrets Manager secret value using the Python AWS SDK
](retrieving-secrets-python-sdk.md)
+ [

# Get a batch of Secrets Manager secret values using the Python AWS SDK
](retrieving-secrets-python-batch.md)

# Get a Secrets Manager secret value using Python with client-side caching
<a name="retrieving-secrets_cache-python"></a>

When you retrieve a secret, you can use the Secrets Manager Python-based caching component to cache it for future use. Retrieving a cached secret is faster than retrieving it from Secrets Manager. Because there is a cost for calling Secrets Manager APIs, using a cache can reduce your costs. For all of the ways you can retrieve secrets, see [Get secrets](retrieving-secrets.md).

The cache policy is Least Recently Used (LRU), so when the cache must discard a secret, it discards the least recently used secret. By default, the cache refreshes secrets every hour. You can configure [how often the secret is refreshed](retrieving-secrets_cache-ref-secretcacheconfig.md) in the cache, and you can [hook into the secret retrieval](retrieving-secrets_cache-ref-secretcachehook.md) to add more functionality.

The cache does not force garbage collection once cache references are freed. The cache implementation does not include cache invalidation. The cache implementation is focused around the cache itself, and is not security hardened or focused. If you require additional security such as encrypting items in the cache, use the interfaces and abstract methods provided.

To use the component, you must have the following: 
+ Python 3.6 or later.
+ botocore 1.12 or higher. See [AWS SDK for Python](https://aws.amazon.com/sdk-for-python/) and [Botocore](https://botocore.amazonaws.com/v1/documentation/api/latest/index.html). 
+ setuptools\$1scm 3.2 or higher. See [https://pypi.org/project/setuptools-scm/](https://pypi.org/project/setuptools-scm/).

To download the source code, see [Secrets Manager Python-based caching client component](https://github.com/aws/aws-secretsmanager-caching-python ) on GitHub.

To install the component, use the following command.

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

**Required permissions: **
+ `secretsmanager:DescribeSecret`
+ `secretsmanager:GetSecretValue`

For more information, see [Permissions reference](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 Retrieve a secret**  
The following example shows how to get the secret value for a secret named *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>

An in-memory cache for secrets retrieved from Secrets Manager. You use [get\$1secret\$1string](#retrieving-secrets_cache-ref-secretcache_get_secret_string) or [get\$1secret\$1binary](#retrieving-secrets_cache-ref-secretcache_get_secret_binary) to retrieve a secret from the cache. You can configure the cache settings by passing in a [SecretCacheConfig](retrieving-secrets_cache-ref-secretcacheconfig.md) object in the constructor. 

For more information, including examples, see [Get a Secrets Manager secret value using Python with client-side caching](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>

Retrieves the secret string value.

Request syntax  

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

Parameters  
+ `secret_id` (*string*): [Required] The name or ARN of the secret.
+ `version_stage` (*string*): The version of secrets that you want to retrieve. For more information, see [secret versions](whats-in-a-secret.md). The default is 'AWSCURRENT'. 

Return type  
string

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

Retrieves the secret binary value.

Request syntax  

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

Parameters  
+ `secret_id` (*string*): [Required] The name or ARN of the secret.
+ `version_stage` (*string*): The version of secrets that you want to retrieve. For more information, see [secret versions](whats-in-a-secret.md). The default is 'AWSCURRENT'. 

Return type  
[base64-encoded](https://tools.ietf.org/html/rfc4648#section-4) string

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

Cache configuration options for a [SecretCache](retrieving-secrets_cache-ref-secretcache.md) such as max cache size and Time to Live (TTL) for cached secrets.Parameters

`max_cache_size` (*int*)  
The maximum cache size. The default is `1024` secrets. 

`exception_retry_delay_base` (*int*)  
The number of seconds to wait after an exception is encountered before retrying the request. The default is `1`.

`exception_retry_growth_factor` (*int*)pur  
The growth factor to use for calculating the wait time between retries of failed requests. The default is `2`. 

`exception_retry_delay_max` (*int*)  
The maximum amount of time in seconds to wait between failed requests. The default is `3600`.

`default_version_stage` (*str*)  
The version of secrets that you want to cache. For more information, see [Secret versions](whats-in-a-secret.md#term_version). The default is `'AWSCURRENT'`.

`secret_refresh_interval` (*int*)  
The number of seconds to wait between refreshing cached secret information. The default is `3600`.

`secret_cache_hook` (*SecretCacheHook*)  
An implementation of the `SecretCacheHook` abstract class. The default value is `None`.

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

An interface to hook into a [SecretCache](retrieving-secrets_cache-ref-secretcache.md) to perform actions on the secrets being stored in the cache. 

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

Prepares the object for storing in the cache.

Request syntax  

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

Parameters  
+ `obj` (*object*) -- [Required] The secret or object that contains the secret.

Return type  
object

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

Derives the object from the cached object.

Request syntax  

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

Parameters  
+ `obj` (*object*): [Required] The secret or object that contains the secret.

Return type  
object

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

This decorator expects a secret ID string and [SecretCache](retrieving-secrets_cache-ref-secretcache.md) as the first and second arguments. The decorator returns the secret string value. The secret must contain a string. 

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

This decorator expects a secret ID string and [SecretCache](retrieving-secrets_cache-ref-secretcache.md) as the first and second arguments. The remaining arguments map parameters from the wrapped function to JSON keys in the secret. The secret must contain a string in JSON structure. 

For a secret that contains this JSON:

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

The following example shows how to extract the JSON values for `username` and `password` from the secret.

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

# Get a Secrets Manager secret value using the Python AWS SDK
<a name="retrieving-secrets-python-sdk"></a>

In applications, you can retrieve your secrets by calling `GetSecretValue` or `BatchGetSecretValue`in any of the AWS SDKs. However, we recommend that you cache your secret values by using client-side caching. Caching secrets improves speed and reduces your costs.

For Python applications, use the [Secrets Manager Python-based caching component](retrieving-secrets_cache-python.md) or call the SDK directly with [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) or [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).

The following code examples show how to use `GetSecretValue`.

**Required permissions: **`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
```

# Get a batch of Secrets Manager secret values using the Python AWS SDK
<a name="retrieving-secrets-python-batch"></a>

The following code example shows how to get a batch of Secrets Manager secret values.

**Required permissions: **
+ `secretsmanager:BatchGetSecretValue` 
+ `secretsmanager:GetSecretValue` permission for each secret you want to retrieve.
+ If you use filters, you must also have `secretsmanager:ListSecrets`. 

For an example permissions policy, see [Example: Permission to retrieve a group of secret values in a batch](auth-and-access_iam-policies.md#auth-and-access_examples_batch).

**Important**  
If you have a VPCE policy that denies permission to retrieve an individual secret in the group you are retrieving, `BatchGetSecretValue` will not return any secret values, and it will return an error.

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

# Get a Secrets Manager secret value using .NET
<a name="retrieving-secrets-net"></a>

In applications, you can retrieve your secrets by calling `GetSecretValue` or `BatchGetSecretValue`in any of the AWS SDKs. However, we recommend that you cache your secret values by using client-side caching. Caching secrets improves speed and reduces your costs.

**Topics**
+ [

# Get a Secrets Manager secret value using .NET with client-side caching
](retrieving-secrets_cache-net.md)
+ [

# Get a Secrets Manager secret value using the SDK for .NET
](retrieving-secrets-net-sdk.md)

# Get a Secrets Manager secret value using .NET with client-side caching
<a name="retrieving-secrets_cache-net"></a>

When you retrieve a secret, you can use the Secrets Manager .NET-based caching component to cache it for future use. Retrieving a cached secret is faster than retrieving it from Secrets Manager. Because there is a cost for calling Secrets Manager APIs, using a cache can reduce your costs. For all of the ways you can retrieve secrets, see [Get secrets](retrieving-secrets.md).

The cache policy is Least Recently Used (LRU), so when the cache must discard a secret, it discards the least recently used secret. By default, the cache refreshes secrets every hour. You can configure [how often the secret is refreshed](retrieving-secrets_cache-net-SecretCacheConfiguration.md#retrieving-secrets_cache-net-SecretCacheConfiguration-properties_CacheItemTTL) in the cache, and you can [hook into the secret retrieval](retrieving-secrets_cache-net-ISecretCacheHook.md) to add more functionality.

The cache does not force garbage collection once cache references are freed. The cache implementation does not include cache invalidation. The cache implementation is focused around the cache itself, and is not security hardened or focused. If you require additional security such as encrypting items in the cache, use the interfaces and abstract methods provided.

To use the component, you must have the following:
+ .NET Framework 4.6.2 or higher, or .NET Standard 2.0 or higher. See [Download .NET](https://dotnet.microsoft.com/en-us/download) on the Microsoft .NET website.
+ The AWS SDK for .NET. See [AWS SDKs](asm_access.md#asm-sdks).

To download the source code, see [Caching client for .NET](https://github.com/aws/aws-secretsmanager-caching-net ) on GitHub.

To use the cache, first instantiate it, then retrieve your secret by using `GetSecretString` or `GetSecretBinary`. On successive retrievals, the cache returns the cached copy of the secret.

**To get the caching package**
+ Do one of the following:
  + Run the following .NET CLI command in your project directory.

    ```
    dotnet add package AWSSDK.SecretsManager.Caching --version 1.0.6
    ```
  + Add the following package reference to your `.csproj` file.

    ```
    <ItemGroup>
        <PackageReference Include="AWSSDK.SecretsManager.Caching" Version="1.0.6" />
    </ItemGroup>
    ```

**Required permissions: **
+ `secretsmanager:DescribeSecret`
+ `secretsmanager:GetSecretValue`

For more information, see [Permissions reference](auth-and-access.md#reference_iam-permissions).

**Topics**
+ [

# SecretsManagerCache
](retrieving-secrets_cache-net-SecretsManagerCache.md)
+ [

# SecretCacheConfiguration
](retrieving-secrets_cache-net-SecretCacheConfiguration.md)
+ [

# ISecretCacheHook
](retrieving-secrets_cache-net-ISecretCacheHook.md)

**Example Retrieve a secret**  
The following code example shows a method that retrieves a secret named *MySecret*.  

```
using Amazon.SecretsManager.Extensions.Caching;

namespace LambdaExample 
{
    public class CachingExample 
    {
        private const string MySecretName ="MySecret";

        private SecretsManagerCache cache = new SecretsManagerCache();

        public async Task<Response>  FunctionHandlerAsync(string input, ILambdaContext context)
        {
            string MySecret = await cache.GetSecretString(MySecretName);
            
            // Use the secret, return success
            
        }
    }
}
```

**Example Configure the time to live (TTL) cache refresh duration**  
The following code example shows a method that retrieves a secret named *MySecret* and sets the TTL cache refresh duration to 24 hours.  

```
using Amazon.SecretsManager.Extensions.Caching;

namespace LambdaExample
{
    public class CachingExample
    {
        private const string MySecretName = "MySecret";
        
        private static SecretCacheConfiguration cacheConfiguration = new SecretCacheConfiguration
        {
            CacheItemTTL = 86400000
        };
        private SecretsManagerCache cache = new SecretsManagerCache(cacheConfiguration);
        public async Task<Response> FunctionHandlerAsync(string input, ILambdaContext context)
        {
            string mySecret = await cache.GetSecretString(MySecretName);

            // Use the secret, return success
        }
    }
}
```

# SecretsManagerCache
<a name="retrieving-secrets_cache-net-SecretsManagerCache"></a>

An in-memory cache for secrets requested from Secrets Manager. You use [GetSecretString](#retrieving-secrets_cache-net-SecretsManagerCache-methods-GetSecretString) or [GetSecretBinary](#retrieving-secrets_cache-net-SecretsManagerCache-methods-GetSecretBinary) to retrieve a secret from the cache. You can configure the cache settings by passing in a [SecretCacheConfiguration](retrieving-secrets_cache-net-SecretCacheConfiguration.md) object in the constructor. 

For more information, including examples, see [Get a Secrets Manager secret value using .NET with client-side caching](retrieving-secrets_cache-net.md).

## Constructors
<a name="retrieving-secrets_cache-net-SecretsManagerCache-constructors"></a>

`public SecretsManagerCache()`  
Default constructor for a `SecretsManagerCache` object.

`public SecretsManagerCache(IAmazonSecretsManager secretsManager)`  
Constructs a new cache using a Secrets Manager client created using the provided [AmazonSecretsManagerClient](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SecretsManager/TSecretsManagerClient.html). Use this constructor to customize the Secrets Manager client, for example to use a specific region or endpoint.  
**Parameters**    
secretsManager  
The [AmazonSecretsManagerClient](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SecretsManager/TSecretsManagerClient.html) to retrieve secrets from.

`public SecretsManagerCache(SecretCacheConfiguration config)`  
Constructs a new secret cache using the provided [SecretCacheConfiguration](retrieving-secrets_cache-net-SecretCacheConfiguration.md). Use this constructor to configure the cache, for example the number of secrets to cache and how often it refreshes.  
**Parameters**    
config  
A [SecretCacheConfiguration](retrieving-secrets_cache-net-SecretCacheConfiguration.md) that contains configuration information for the cache.

`public SecretsManagerCache(IAmazonSecretsManager secretsManager, SecretCacheConfiguration config)`  
Constructs a new cache using a Secrets Manager client created using the provided [AmazonSecretsManagerClient](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SecretsManager/TSecretsManagerClient.html) and a [SecretCacheConfiguration](retrieving-secrets_cache-net-SecretCacheConfiguration.md). Use this constructor to customize the Secrets Manager client, for example to use a specific region or endpoint as well as configure the cache, for example the number of secrets to cache and how often it refreshes.  
**Parameters**    
secretsManager  
The [AmazonSecretsManagerClient](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SecretsManager/TSecretsManagerClient.html) to retrieve secrets from.  
config  
A [SecretCacheConfiguration](retrieving-secrets_cache-net-SecretCacheConfiguration.md) that contains configuration information for the cache.

## Methods
<a name="retrieving-secrets_cache-net-SecretsManagerCache-methods"></a>

### GetSecretString
<a name="retrieving-secrets_cache-net-SecretsManagerCache-methods-GetSecretString"></a>

 `public async Task<String> GetSecretString(String secretId)`

Retrieves a string secret from Secrets Manager.Parameters

secretId  
The ARN or name of the secret to retrieve.

### GetSecretBinary
<a name="retrieving-secrets_cache-net-SecretsManagerCache-methods-GetSecretBinary"></a>

`public async Task<byte[]> GetSecretBinary(String secretId)`

Retrieves a binary secret from Secrets Manager.Parameters

secretId  
The ARN or name of the secret to retrieve.

### RefreshNowAsync
<a name="retrieving-secrets_cache-net-SecretsManagerCache-methods-RefreshNowAsync"></a>

`public async Task<bool> RefreshNowAsync(String secretId)`

Requests the secret value from Secrets Manager and updates the cache with any changes. If there is no existing cache entry, creates a new one. Returns `true` if the refresh is successful.Parameters

secretId  
The ARN or name of the secret to retrieve.

### GetCachedSecret
<a name="retrieving-secrets_cache-net-SecretsManagerCache-methods-GetCachedSecret"></a>

`public SecretCacheItem GetCachedSecret(string secretId)`

Returns the cache entry for the specified secret if it exists in the cache. Otherwise, retrieves the secret from Secrets Manager and creates a new cache entry.Parameters

secretId  
The ARN or name of the secret to retrieve.

# SecretCacheConfiguration
<a name="retrieving-secrets_cache-net-SecretCacheConfiguration"></a>

Cache configuration options for a [SecretsManagerCache](retrieving-secrets_cache-net-SecretsManagerCache.md), such as maximum cache size and Time to Live (TTL) for cached secrets.

## Properties
<a name="retrieving-secrets_cache-net-SecretCacheConfiguration-properties"></a>

### CacheItemTTL
<a name="retrieving-secrets_cache-net-SecretCacheConfiguration-properties_CacheItemTTL"></a>

`public uint CacheItemTTL { get; set; }`

The TTL of a cache item in milliseconds. The default is `3600000` ms or 1 hour. The maximum is `4294967295` ms, which is approximately 49.7 days.

### MaxCacheSize
<a name="retrieving-secrets_cache-net-SecretCacheConfiguration-properties_MaxCacheSize"></a>

`public ushort MaxCacheSize { get; set; }`

The maximum cache size. The default is 1024 secrets. The maximum is 65,535.

### VersionStage
<a name="retrieving-secrets_cache-net-SecretCacheConfiguration-properties_VersionStage"></a>

`public string VersionStage { get; set; }`

The version of secrets that you want to cache. For more information, see [Secret versions](whats-in-a-secret.md#term_version). The default is `"AWSCURRENT"`.

### Client
<a name="retrieving-secrets_cache-net-SecretCacheConfiguration-properties_Client"></a>

`public IAmazonSecretsManager Client { get; set; }`

The [AmazonSecretsManagerClient](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SecretsManager/TSecretsManagerClient.html) to retrieve secrets from. If it is `null`, the cache instantiates a new client. The default is `null`.

### CacheHook
<a name="retrieving-secrets_cache-net-SecretCacheConfiguration-properties_CacheHook"></a>

`public ISecretCacheHook CacheHook { get; set; }`

A [ISecretCacheHook](retrieving-secrets_cache-net-ISecretCacheHook.md).

# ISecretCacheHook
<a name="retrieving-secrets_cache-net-ISecretCacheHook"></a>

An interface to hook into a [SecretsManagerCache](retrieving-secrets_cache-net-SecretsManagerCache.md) to perform actions on the secrets being stored in the cache. 

## Methods
<a name="retrieving-secrets_cache-net-ISecretCacheHook-methods"></a>

### Put
<a name="retrieving-secrets_cache-net-ISecretCacheHook-methods-Put"></a>

`object Put(object o);`

Prepare the object for storing in the cache.

Returns the object to store in the cache.

### Get
<a name="retrieving-secrets_cache-net-ISecretCacheHook-methods-Get"></a>

`object Get(object cachedObject);`

Derive the object from the cached object.

Returns the object to return from the cache

# Get a Secrets Manager secret value using the SDK for .NET
<a name="retrieving-secrets-net-sdk"></a>

In applications, you can retrieve your secrets by calling `GetSecretValue` or `BatchGetSecretValue`in any of the AWS SDKs. However, we recommend that you cache your secret values by using client-side caching. Caching secrets improves speed and reduces your costs.

For .NET applications, use the [Secrets Manager .NET-based caching component](retrieving-secrets_cache-net.md) or call the SDK directly with [https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SecretsManager/TGetSecretValueRequest.html](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SecretsManager/TGetSecretValueRequest.html) or [https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SecretsManager/TBatchGetSecretValueRequest.html](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SecretsManager/TBatchGetSecretValueRequest.html).

The following code examples show how to use `GetSecretValue`.

**Required permissions: **`secretsmanager:GetSecretValue`

```
    using System;
    using System.IO;
    using System.Threading.Tasks;
    using Amazon.SecretsManager;
    using Amazon.SecretsManager.Model;

    /// <summary>
    /// This example uses the Amazon Web Service Secrets Manager to retrieve
    /// the secret value for the provided secret name.
    /// </summary>
    public class GetSecretValue
    {
        /// <summary>
        /// The main method initializes the necessary values and then calls
        /// the GetSecretAsync and DecodeString methods to get the decoded
        /// secret value for the secret named in secretName.
        /// </summary>
        public static async Task Main()
        {
            string secretName = "<<{{MySecretName}}>>";
            string secret;

            IAmazonSecretsManager client = new AmazonSecretsManagerClient();

            var response = await GetSecretAsync(client, secretName);

            if (response is not null)
            {
                secret = DecodeString(response);

                if (!string.IsNullOrEmpty(secret))
                {
                    Console.WriteLine($"The decoded secret value is: {secret}.");
                }
                else
                {
                    Console.WriteLine("No secret value was returned.");
                }
            }
        }

        /// <summary>
        /// Retrieves the secret value given the name of the secret to
        /// retrieve.
        /// </summary>
        /// <param name="client">The client object used to retrieve the secret
        /// value for the given secret name.</param>
        /// <param name="secretName">The name of the secret value to retrieve.</param>
        /// <returns>The GetSecretValueReponse object returned by
        /// GetSecretValueAsync.</returns>
        public static async Task<GetSecretValueResponse> GetSecretAsync(
            IAmazonSecretsManager client,
            string secretName)
        {
            GetSecretValueRequest request = new GetSecretValueRequest()
            {
                SecretId = secretName,
                VersionStage = "AWSCURRENT", // VersionStage defaults to AWSCURRENT if unspecified.
            };

            GetSecretValueResponse response = null;

            // For the sake of simplicity, this example handles only the most
            // general SecretsManager exception.
            try
            {
                response = await client.GetSecretValueAsync(request);
            }
            catch (AmazonSecretsManagerException e)
            {
                Console.WriteLine($"Error: {e.Message}");
            }

            return response;
        }

        /// <summary>
        /// Decodes the secret returned by the call to GetSecretValueAsync and
        /// returns it to the calling program.
        /// </summary>
        /// <param name="response">A GetSecretValueResponse object containing
        /// the requested secret value returned by GetSecretValueAsync.</param>
        /// <returns>A string representing the decoded secret value.</returns>
        public static string DecodeString(GetSecretValueResponse response)
        {
            // Decrypts secret using the associated AWS Key Management Service
            // Customer Master Key (CMK.) Depending on whether the secret is a
            // string or binary value, one of these fields will be populated.
            if (response.SecretString is not null)
            {
                var secret = response.SecretString;
                return secret;
            }
            else if (response.SecretBinary is not null)
            {
                var memoryStream = response.SecretBinary;
                StreamReader reader = new StreamReader(memoryStream);
                string decodedBinarySecret = System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(reader.ReadToEnd()));
                return decodedBinarySecret;
            }
            else
            {
                return string.Empty;
            }
        }
    }
```

# Get a Secrets Manager secret value using Go
<a name="retrieving-secrets-go"></a>

In applications, you can retrieve your secrets by calling `GetSecretValue` or `BatchGetSecretValue`in any of the AWS SDKs. However, we recommend that you cache your secret values by using client-side caching. Caching secrets improves speed and reduces your costs.

**Topics**
+ [

# Get a Secrets Manager secret value using Go with client-side caching
](retrieving-secrets_cache-go.md)
+ [

# Get a Secrets Manager secret value using the Go AWS SDK
](retrieving-secrets-go-sdk.md)

# Get a Secrets Manager secret value using Go with client-side caching
<a name="retrieving-secrets_cache-go"></a>

When you retrieve a secret, you can use the Secrets Manager Go-based caching component to cache it for future use. Retrieving a cached secret is faster than retrieving it from Secrets Manager. Because there is a cost for calling Secrets Manager APIs, using a cache can reduce your costs. For all of the ways you can retrieve secrets, see [Get secrets](retrieving-secrets.md).

The cache policy is Least Recently Used (LRU), so when the cache must discard a secret, it discards the least recently used secret. By default, the cache refreshes secrets every hour. You can configure [how often the secret is refreshed](retrieving-secrets_cache-go_CacheConfig.md) in the cache, and you can [hook into the secret retrieval](retrieving-secrets_cache-go_CacheHook.md) to add more functionality.

The cache does not force garbage collection once cache references are freed. The cache implementation does not include cache invalidation. The cache implementation is focused around the cache itself, and is not security hardened or focused. If you require additional security such as encrypting items in the cache, use the interfaces and abstract methods provided.

To use the component, you must have the following:
+ AWS SDK for Go. See [AWS SDKs](asm_access.md#asm-sdks).

To download the source code, see [Secrets Manager Go caching client](https://github.com/aws/aws-secretsmanager-caching-go ) on GitHub.

To set up a Go development environment, see [Golang Getting Started](https://golang.org/doc/install) on the Go Programming Language website.

**Required permissions: **
+ `secretsmanager:DescribeSecret`
+ `secretsmanager:GetSecretValue`

For more information, see [Permissions reference](auth-and-access.md#reference_iam-permissions).

**Topics**
+ [

# type Cache
](retrieving-secrets_cache-go_cache.md)
+ [

# type CacheConfig
](retrieving-secrets_cache-go_CacheConfig.md)
+ [

# type CacheHook
](retrieving-secrets_cache-go_CacheHook.md)

**Example Retrieve a secret**  
The following code example shows a Lambda function that retrieves a secret.  

```
package main

import (
	 "github.com/aws/aws-lambda-go/lambda"
	 "github.com/aws/aws-secretsmanager-caching-go/secretcache"
)

var (
	 secretCache, _ = secretcache.New()
)

func HandleRequest(secretId string) string {
	 result, _ := secretCache.GetSecretString(secretId)
	 
	 // Use the secret, return success
}

 func main() {
	 lambda. Start( HandleRequest)
}
```

# type Cache
<a name="retrieving-secrets_cache-go_cache"></a>

An in-memory cache for secrets requested from Secrets Manager. You use [GetSecretString](#retrieving-secrets_cache-go_cache_operations_GetCachedSecret) or [GetSecretBinary](#retrieving-secrets_cache-go_cache_operations_GetSecretBinary) to retrieve a secret from the cache. 

The following example shows how to configure the cache settings.

```
// Create a custom secretsmanager client
client := getCustomClient()

// Create a custom CacheConfig struct 
config := secretcache. CacheConfig{
    MaxCacheSize:  secretcache.DefaultMaxCacheSize + 10,
    VersionStage:  secretcache.DefaultVersionStage,
    CacheItemTTL:  secretcache.DefaultCacheItemTTL,
}
	
// Instantiate the cache 
cache, _ := secretcache.New(
    func( c *secretcache.Cache) {  c. CacheConfig = config },
    func( c *secretcache.Cache) {  c. Client = client },
)
```

For more information, including examples, see [Get a Secrets Manager secret value using Go with client-side caching](retrieving-secrets_cache-go.md).

## Methods
<a name="retrieving-secrets_cache-go_cache_operations"></a>

### New
<a name="retrieving-secrets_cache-go_cache_operations_New"></a>

`func New(optFns ...func(*Cache)) (*Cache, error)`

New constructs a secret cache using functional options, uses defaults otherwise. Initializes a SecretsManager Client from a new session. Initializes CacheConfig to default values. Initialises LRU cache with a default max size.

### GetSecretString
<a name="retrieving-secrets_cache-go_cache_operations_GetCachedSecret"></a>

`func (c *Cache) GetSecretString(secretId string) (string, error)`

GetSecretString gets the secret string value from the cache for given secret ID. Returns the secret string and an error if operation failed.

### GetSecretStringWithStage
<a name="retrieving-secrets_cache-go_cache_operations_GetSecretStringWithStage"></a>

`func (c *Cache) GetSecretStringWithStage(secretId string, versionStage string) (string, error)`

GetSecretStringWithStage gets the secret string value from the cache for given secret ID and [version stage](whats-in-a-secret.md#term_version). Returns the secret string and an error if operation failed.

### GetSecretBinary
<a name="retrieving-secrets_cache-go_cache_operations_GetSecretBinary"></a>

`func (c *Cache) GetSecretBinary(secretId string) ([]byte, error) {`

GetSecretBinary gets the secret binary value from the cache for given secret ID. Returns the secret binary and an error if operation failed.

### GetSecretBinaryWithStage
<a name="retrieving-secrets_cache-go_cache_operations_GetSecretBinaryWithStage"></a>

`func (c *Cache) GetSecretBinaryWithStage(secretId string, versionStage string) ([]byte, error)`

GetSecretBinaryWithStage gets the secret binary value from the cache for given secret ID and [version stage](whats-in-a-secret.md#term_version). Returns the secret binary and an error if operation failed. 

# type CacheConfig
<a name="retrieving-secrets_cache-go_CacheConfig"></a>

Cache configuration options for a [Cache](retrieving-secrets_cache-go_cache.md), such as maximum cache size, default [version stage](whats-in-a-secret.md#term_version), and Time to Live (TTL) for cached secrets.

```
type CacheConfig struct {

    // The maximum cache size. The default is 1024 secrets.
    MaxCacheSize int
            
    // The TTL of a cache item in nanoseconds. The default is 
    // 3.6e10^12 ns or 1 hour.
    CacheItemTTL int64
            
    // The version of secrets that you want to cache. The default 
    // is "AWSCURRENT".
    VersionStage string
            
    // Used to hook in-memory cache updates.
    Hook CacheHook
}
```

# type CacheHook
<a name="retrieving-secrets_cache-go_CacheHook"></a>

An interface to hook into a [Cache](retrieving-secrets_cache-go_cache.md) to perform actions on the secret being stored in the cache.

## Methods
<a name="retrieving-secrets_cache-go_CacheHook_operations"></a>

### Put
<a name="retrieving-secrets_cache-go_CacheHook_operations_Put"></a>

`Put(data interface{}) interface{}`

Prepares the object for storing in the cache.

### Get
<a name="retrieving-secrets_cache-go_CacheHook_operations_Get"></a>

`Get(data interface{}) interface{}`

Derives the object from the cached object.

# Get a Secrets Manager secret value using the Go AWS SDK
<a name="retrieving-secrets-go-sdk"></a>

In applications, you can retrieve your secrets by calling `GetSecretValue` or `BatchGetSecretValue`in any of the AWS SDKs. However, we recommend that you cache your secret values by using client-side caching. Caching secrets improves speed and reduces your costs.

For Go applications, use the [Secrets Manager Go-based caching component](retrieving-secrets_cache-go.md) or call the SDK directly with [https://docs.aws.amazon.com/sdk-for-go/api/service/secretsmanager/#SecretsManager.GetSecretValue](https://docs.aws.amazon.com/sdk-for-go/api/service/secretsmanager/#SecretsManager.GetSecretValue) or [https://docs.aws.amazon.com/sdk-for-go/api/service/secretsmanager/#SecretsManager.BatchGetSecretValue](https://docs.aws.amazon.com/sdk-for-go/api/service/secretsmanager/#SecretsManager.BatchGetSecretValue).

The following code example shows how to get a Secrets Manager secret value.

**Required permissions: **`secretsmanager:GetSecretValue`

```
  // Use this code snippet in your app.
  // If you need more information about configurations or implementing the sample code, visit the AWS docs:   
  // https://aws.github.io/aws-sdk-go-v2/docs/getting-started/
  
  import (
    "context"
    "log"
  
    "github.com/aws/aws-sdk-go-v2/aws"
    "github.com/aws/aws-sdk-go-v2/config"
    "github.com/aws/aws-sdk-go-v2/service/secretsmanager"
  )
  
  func main() {
    secretName := "<<{{MySecretName}}>>"
    region := "<<{{MyRegionName}}>>"
  
    config, err := config.LoadDefaultConfig(context.TODO(), config.WithRegion(region))
    if err != nil {
      log.Fatal(err)
    }
  
    // Create Secrets Manager client
    svc := secretsmanager.NewFromConfig(config)
  
    input := &secretsmanager.GetSecretValueInput{
      SecretId:     aws.String(secretName),
      VersionStage: aws.String("AWSCURRENT"), // VersionStage defaults to AWSCURRENT if unspecified
    }
  
    result, err := svc.GetSecretValue(context.TODO(), input)
    if err != nil {
      // For a list of exceptions thrown, see
      // https://<<{{DocsDomain}}>>/secretsmanager/latest/apireference/API_GetSecretValue.html
      log.Fatal(err.Error())
    }
  
    // Decrypts secret using the associated KMS key.
    var secretString string = *result.SecretString
  
    // Your code goes here.
  }
```

# Get a Secrets Manager secret value using Rust
<a name="retrieving-secrets-rust"></a>

In applications, you can retrieve your secrets by calling `GetSecretValue` or `BatchGetSecretValue`in any of the AWS SDKs. However, we recommend that you cache your secret values by using client-side caching. Caching secrets improves speed and reduces your costs.

**Topics**
+ [

# Get a Secrets Manager secret value using Rust with client-side caching
](retrieving-secrets_cache-rust.md)
+ [

# Get a Secrets Manager secret value using the Rust AWS SDK
](retrieving-secrets-rust-sdk.md)

# Get a Secrets Manager secret value using Rust with client-side caching
<a name="retrieving-secrets_cache-rust"></a>

When you retrieve a secret, you can use the Secrets Manager Rust-based caching component to cache it for future use. Retrieving a cached secret is faster than retrieving it from Secrets Manager. Because there is a cost for calling Secrets Manager APIs, using a cache can reduce your costs. For all of the ways you can retrieve secrets, see [Get secrets](retrieving-secrets.md).

The cache policy is First In First Out (FIFO), so when the cache must discard a secret, it discards the oldest secret. By default, the cache refreshes secrets every hour. You can configure the following:
+ `max_size` – The maximum number of cached secrets to maintain before evicting secrets that have not been accessed recently.
+ `ttl` – The duration a cached item is considered valid before requiring a refresh of the secret state.

The cache implementation does not include cache invalidation. The cache implementation is focused around the cache itself, and is not security hardened or focused. If you require additional security such as encrypting items in the cache, use the traits provided to modify the cache.

To use the component, you must have a Rust 2021 development environment with `tokio`. For more information, see [Getting started](https://www.rust-lang.org/learn/get-started) on the Rust Programming Language website.

To download the source code, see [Secrets Manager Rust-based caching client component](https://github.com/aws/aws-secretsmanager-agent/tree/main/aws_secretsmanager_caching) on GitHub.

To install the caching component, use the following command.

```
cargo add aws_secretsmanager_caching
```

**Required permissions: **
+ `secretsmanager:DescribeSecret`
+ `secretsmanager:GetSecretValue`

For more information, see [Permissions reference](auth-and-access.md#reference_iam-permissions).

**Example Retrieve a secret**  
The following example shows how to get the secret value for a secret named *MyTest*.  

```
use aws_secretsmanager_caching::SecretsManagerCachingClient;
use std::num::NonZeroUsize;
use std::time::Duration;

let client = match SecretsManagerCachingClient::default(
    NonZeroUsize::new(10).unwrap(),
    Duration::from_secs(60),
)
.await
{
    Ok(c) => c,
    Err(_) => panic!("Handle this error"),
};

let secret_string = match client.get_secret_value("MyTest", None, None).await {
    Ok(s) => s.secret_string.unwrap(),
    Err(_) => panic!("Handle this error"),
};

// Your code here
```

**Example Instantiating Cache with a custom configuration and a custom client**  
The following example shows how to configure the cache and then get the secret value for a secret named *MyTest*.  

```
let config = aws_config::load_defaults(BehaviorVersion::latest())
    .await
    .into_builder()
    .region(Region::from_static("us-west-2"))
    .build();

let asm_builder = aws_sdk_secretsmanager::config::Builder::from(&config);

let client = match SecretsManagerCachingClient::from_builder(
    asm_builder,
    NonZeroUsize::new(10).unwrap(),
    Duration::from_secs(60),
)
.await
{
    Ok(c) => c,
    Err(_) => panic!("Handle this error"),
};

let secret_string = client
    .get_secret_value("MyTest", None, None)
    .await 
    {
        Ok(c) => c.secret_string.unwrap(),
        Err(_) => panic!("Handle this error"),
    };

// Your code here
```
```

# Get a Secrets Manager secret value using the Rust AWS SDK
<a name="retrieving-secrets-rust-sdk"></a>

In applications, you can retrieve your secrets by calling `GetSecretValue` or `BatchGetSecretValue`in any of the AWS SDKs. However, we recommend that you cache your secret values by using client-side caching. Caching secrets improves speed and reduces your costs.

For Rust applications, use the [Secrets Manager Rust-based caching component](retrieving-secrets_cache-rust.md) or call the [SDK directly](https://docs.rs/releases/search?query=aws-sdk-secretsmanager) with GetSecretValue or BatchGetSecretValue.

The following code example shows how to get a Secrets Manager secret value.

**Required permissions: **`secretsmanager:GetSecretValue`

```
async fn show_secret(client: &Client, name: &str) -> Result<(), Error> {
    let resp = client.get_secret_value().secret_id(name).send().await?;

    println!("Value: {}", resp.secret_string().unwrap_or("No value!"));

    Ok(())
}
```

# Use AWS Secrets Manager secrets in Amazon Elastic Kubernetes Service
<a name="integrate_eks"></a>

To show secrets from AWS Secrets Manager (ASCP) as files mounted in Amazon EKS Pods, you can use the AWS Secrets and Configuration Provider for the Kubernetes Secrets Store CSI Driver. The ASCP works with Amazon Elastic Kubernetes Service 1.17\$1 running an Amazon EC2 node group. AWS Fargate node groups are not supported. With the ASCP, you can store and manage your secrets in Secrets Manager and then retrieve them through your workloads running on Amazon EKS. If your secret contains multiple key-value pairs in JSON format, you can choose which ones to mount in Amazon EKS. The ASCP uses JMESPath syntax to query the key-value pairs in your secret. The ASCP also works with Parameter Store parameters. The ASCP offers two methods of authentication with Amazon EKS The first approach uses IAM Roles for Service Accounts (IRSA). The second approach uses Pod Identities. Each approach has its benefits and use cases.

## ASCP with IAM Roles for Service Accounts (IRSA)
<a name="csi_driver_overview"></a>

The ASCP with IAM Roles for Service Accounts (IRSA) allows you to mount secrets from AWS Secrets Manager as files in your Amazon EKS Pods. This approach is suitable when:
+ You need to mount secrets as files in your Pods.
+ You're using Amazon EKS version 1.17 or later with Amazon EC2 node groups.
+ You want to retrieve specific key-value pairs from JSON-formatted secrets.

For more information, see [Use AWS Secrets and Configuration Provider CSI with IAM Roles for Service Accounts (IRSA)](integrating_ascp_irsa.md).

## ASCP with Pod Identity
<a name="pod_identity_overview"></a>

The ASCP with Pod Identity method enhances security and simplifies configuration for accessing secrets in Amazon EKS. This approach is beneficial when:
+ You need more granular permission management at the Pod level.
+ You're using Amazon EKS version 1.24 or later.
+ You want improved performance and scalability.

For more information, see [Use AWS Secrets and Configuration Provider CSI with Pod Identity for Amazon EKS](ascp-pod-identity-integration.md).

## Choosing the right approach
<a name="comparison"></a>

Consider the following factors when deciding between ASCP with IRSA and ASCP with Pod Identity:
+ Amazon EKSversion: Pod Identity requires Amazon EKS 1.24\$1, while CSI driver works with Amazon EKS 1.17\$1.
+ Security requirements: Pod Identity offers more granular control at the Pod level.
+ Performance: Pod Identity generally performs better in high-scale environments.
+ Complexity: Pod Identity simplifies setup by eliminating the need for separate service accounts.

Choose the method that best aligns with your specific requirements and Amazon EKS environment.

# Install ASCP for Amazon EKS
<a name="ascp-eks-installation"></a>

This section explains how to install the AWS Secrets and Configuration Provider for Amazon EKS. With ASCP, you can mount secrets from Secrets Manager and parameters from AWS Systems Manager as files in Amazon EKS Pods.

## Prerequisites
<a name="prerequisites"></a>
+ An Amazon EKS cluster
  + Version 1.24 or later for Pod Identity
  + Version 1.17 or later for IRSA
+ The AWS CLI installed and configured
+ kubectl installed and configured for your Amazon EKS cluster
+ Helm (version 3.0 or later)

## Install and configure the ASCP
<a name="integrating_csi_driver_install"></a>

The ASCP is available on GitHub in the [secrets-store-csi-provider-aws](https://github.com/aws/secrets-store-csi-driver-provider-aws) repository. The repo also contains example YAML files for creating and mounting a secret. 

During installation, you can configure the ASCP to use a FIPS endpoint. For a list of endpoints, see [AWS Secrets Manager endpoints](asm_access.md#endpoints).

**To install the ASCP as an EKS add-on**

1. Install `eksctl` ([installation instructions](https://docs.aws.amazon.com/eks/latest/eksctl/installation.html))

1. Run the following command to install the add-on with the [default configuration](https://github.com/aws/secrets-store-csi-driver-provider-aws/blob/main/charts/secrets-store-csi-driver-provider-aws/values.yaml):

   ```
   eksctl create addon --cluster <your_cluster> --name aws-secrets-store-csi-driver-provider
   ```

   If you'd like to configure the add-on, run the following installation command instead:

   ```
   aws eks create-addon --cluster-name <your_cluster> --addon-name aws-secrets-store-csi-driver-provider --configuration-values 'file://path/to/config.yaml'
   ```

   The configuration file can be a YAML or JSON file. To see the configuration schema for the add-on:

   1. Run the following command and note the latest version of the add-on:

      ```
      aws eks describe-addon-versions --addon-name aws-secrets-store-csi-driver-provider
      ```

   1. Run the following command to see the add-on's configuration schema, replacing `<version>` with the version from the previous step:

      ```
      aws eks describe-addon-configuration --addon-name aws-secrets-store-csi-driver-provider --addon-version <version>
      ```

**To install the ASCP by using Helm**

1. To make sure the repo is pointing to the latest charts, use `helm repo update.`

1. Install the chart. The following is an example of the `helm install` command:

   ```
   helm install -n kube-system secrets-provider-aws aws-secrets-manager/secrets-store-csi-driver-provider-aws
   ```

   1. To use a FIPS endpoint, add the following flag: `--set useFipsEndpoint=true`

   1. To configure throttling, add the following flag: `--set-json 'k8sThrottlingParams={"qps": "number of queries per second", "burst": "number of queries per second"}'`

   1. If the Secrets Store CSI Driver is already installed on your cluster, add the following flag: `--set secrets-store-csi-driver.install=false`. This will skip installing Secrets Store CSI Driver as a dependency.

**To install by using the YAML in the repo**
+ Use the following commands.

  ```
  helm repo add secrets-store-csi-driver https://kubernetes-sigs.github.io/secrets-store-csi-driver/charts
  helm install -n kube-system csi-secrets-store secrets-store-csi-driver/secrets-store-csi-driver
  kubectl apply -f https://raw.githubusercontent.com/aws/secrets-store-csi-driver-provider-aws/main/deployment/aws-provider-installer.yaml
  ```

## Verify the installations
<a name="verify-ascp-installations"></a>

To verify the installations of your EKS cluster, Secrets Store CSI driver, and ASCP plugin, follow these steps:

1. Verify the EKS cluster:

   ```
   eksctl get cluster --name clusterName
   ```

   This command should return information about your cluster.

1. Verify the Secrets Store CSI driver installation:

   ```
   kubectl get pods -n kube-system -l app=secrets-store-csi-driver
   ```

   You should see Pods running with names like `csi-secrets-store-secrets-store-csi-driver-xxx`.

1. Verify the ASCP plugin installation:

------
#### [ YAML installation ]

   ```
   $ kubectl get pods -n kube-system -l app=csi-secrets-store-provider-aws
   ```

   Example output:

   ```
   NAME                                     READY   STATUS    RESTARTS   AGE
   csi-secrets-store-provider-aws-12345      1/1     Running   0          2m
   ```

------
#### [ Helm installation ]

   ```
   $  kubectl get pods -n kube-system -l app=secrets-store-csi-driver-provider-aws
   ```

   Example output:

   ```
   NAME                                              READY   STATUS    RESTARTS   AGE
   secrets-provider-aws-secrets-store-csi-driver-provider-67890       1/1     Running   0          2m
   ```

------

   You should see Pods in the `Running` state.

After running these commands, if everything is set up correctly, you should see all components running without any errors. If you encounter any issues, you may need to troubleshoot by checking the logs of the specific Pods that are having problems.

## Troubleshooting
<a name="troubleshooting"></a>

1. To check the logs of the ASCP provider, run:

   ```
   kubectl logs -n kube-system -l app=csi-secrets-store-provider-aws
   ```

1. Check the status of all pods in the `kube-system` namespace:

   ```
   kubectl -n kube-system get pods
   ```

   ```
   kubectl -n kube-system logs pod/PODID
   ```

   All Pods related to the CSI driver and ASCP should be in the 'Running' state.

1. Check the CSI driver version:

   ```
   kubectl get csidriver secrets-store.csi.k8s.io -o yaml
   ```

   This command should return information about the installed CSI driver.

## Additional resources
<a name="additional-resources"></a>

For more information about using ASCP with Amazon EKS, see the following resources:
+ [Using Pod Identity with Amazon EKS](https://docs.aws.amazon.com/eks/latest/userguide/pod-identities.html)
+ [AWS Secrets Store CSI Driver on GitHub](https://github.com/aws/secrets-store-csi-driver-provider-aws)

# Use AWS Secrets and Configuration Provider CSI with Pod Identity for Amazon EKS
<a name="ascp-pod-identity-integration"></a>

The AWS Secrets and Configuration Provider integration with the Pod Identity Agent for Amazon Elastic Kubernetes Service provides enhanced security, simplified configuration, and improved performance for applications running on Amazon EKS. Pod Identity simplifies IAM authentication for Amazon EKS when retrieving secrets from Secrets Manager or parameters from AWS Systems Manager Parameter Store.

Amazon EKS Pod Identity streamlines the process of configuring IAM permissions for Kubernetes applications by allowing permissions to be set up directly through Amazon EKS interfaces, reducing the number of steps and eliminating the need to switch between Amazon EKS and IAM services. Pod Identity enables the use of a single IAM role across multiple clusters without updating trust policies and supports [role session tags](https://docs.aws.amazon.com/eks/latest/userguide/pod-id-abac.html#pod-id-abac-tags) for more granular access control. This approach not only simplifies policy management by allowing reuse of permission policies across roles but also enhances security by enabling access to AWS resources based on matching tags.

## How it works
<a name="how-it-works"></a>

1. Pod Identity assigns an IAM role to the Pod.

1. ASCP uses this role to authenticate with AWS services.

1. If authorized, ASCP retrieves the requested secrets and makes them available to the Pod.

For more information, see [Understand how Amazon EKS Pod Identity works](https://docs.aws.amazon.com/eks/latest/userguide/pod-id-how-it-works.html) in the *Amazon EKS User Guide*.

## Prerequisites
<a name="prerequisites"></a>

**Important**  
Pod Identity is supported only for Amazon EKS in the cloud. It is not supported for [Amazon EKS Anywhere](https://aws.amazon.com/eks/eks-anywhere/), [Red Hat OpenShift Service on AWS](https://aws.amazon.com/rosa/), or self-managed Kubernetes clusters on Amazon EC2 instances.
+ Amazon EKS cluster (version 1.24 or later)
+ Access to AWS CLI and Amazon EKS cluster via `kubectl`
+ Access to two AWS accounts (for cross-account access)

## Install the Amazon EKS Pod Identity Agent
<a name="install-pod-identity-agent"></a>

To use Pod Identity with your cluster, you must install the Amazon EKS Pod Identity Agent add-on.

**To install the Pod Identity Agent**
+ Install the Pod Identity Agent add-on on your cluster:

  ```
  eksctl create addon \
    --name eks-pod-identity-agent \
    --cluster clusterName \
    --region region
  ```

## Set up ASCP with Pod Identity
<a name="pod-identity-setup"></a>

1. Create a permissions policy that grants `secretsmanager:GetSecretValue` and `secretsmanager:DescribeSecret` permission to the secrets that the Pod needs to access. For an example policy, see [Example: Permission to read and describe individual secrets](auth-and-access_iam-policies.md#auth-and-access_examples-read-and-describe).

1. Create an IAM role that can be assumed by the Amazon EKS service principal for Pod Identity:

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

****  

   ```
   {
       "Version":"2012-10-17",		 	 	 
       "Statement": [
         {
           "Effect": "Allow",
           "Principal": {
             "Service": "pods.eks.amazonaws.com"
           },
           "Action": [
             "sts:AssumeRole",
             "sts:TagSession"
           ]
         }
       ]
     }
   ```

------

   Attach the IAM policy to the role:

   ```
   aws iam attach-role-policy \
     --role-name MY_ROLE \
     --policy-arn POLICY_ARN
   ```

1. Create a Pod Identity association. For an example, see [Create a Pod Identity association ](https://docs.aws.amazon.com/eks/latest/userguide/pod-id-association.html#pod-id-association-create) in the *Amazon EKS User Guide*

1. Create the `SecretProviderClass` that specifies which secrets to mount in the Pod:

   ```
   kubectl apply -f https://raw.githubusercontent.com/aws/secrets-store-csi-driver-provider-aws/main/examples/ExampleSecretProviderClass-PodIdentity.yaml
   ```

   The key difference in `SecretProviderClass` between IRSA and Pod Identity is the optional parameter `usePodIdentity`. It is an optional field that determines the authentication approach. When not specified, it defaults to using IAM Roles for Service Accounts (IRSA).
   + To use EKS Pod Identity, use any of these values: `"true", "True", "TRUE", "t", "T"`.
   + To explicitly use IRSA, set to any of these values: `"false", "False", "FALSE", "f", or "F"`.

1. Deploy the Pod that mounts the secrets under `/mnt/secrets-store`:

   ```
   kubectl apply -f https://raw.githubusercontent.com/aws/secrets-store-csi-driver-provider-aws/main/examples/ExampleDeployment-PodIdentity.yaml
   ```

1. If you use a private Amazon EKS cluster, make sure that the VPC that the cluster is in has an AWS STS endpoint. For information about creating an endpoint, see [Interface VPC endpoints](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_interface_vpc_endpoints.html) in the *AWS Identity and Access Management User Guide*.

### Verify the secret mount
<a name="verify-secret-mount"></a>

To verify that the secret is mounted properly, run the following command:

```
kubectl exec -it $(kubectl get pods | awk '/pod-identity-deployment/{print $1}' | head -1) -- cat /mnt/secrets-store/MySecret
```

**To set up Amazon EKS Pod Identity to access to secrets in Secrets Manager**

1. Create a permissions policy that grants `secretsmanager:GetSecretValue` and `secretsmanager:DescribeSecret` permission to the secrets that the Pod needs to access. For an example policy, see [Example: Permission to read and describe individual secrets](auth-and-access_iam-policies.md#auth-and-access_examples-read-and-describe).

1. Create a secret in Secrets Manager, if you do not already have one.

## Troubleshoot
<a name="integrating_aspc_pod_trouble"></a>

You can view most errors by describing the Pod deployment.

**To see error messages for your container**

1. Get a list of Pod names with the following command. If you aren't using the default namespace, use `-n NAMESPACE`.

   ```
   kubectl get pods
   ```

1. To describe the Pod, in the following command, for *PODID* use the Pod ID from the Pods you found in the previous step. If you aren't using the default namespace, use `-n NAMESPACE`.

   ```
   kubectl describe pod/PODID
   ```

**To see errors for the ASCP**
+ To find more information in the provider logs, in the following command, for *PODID* use the ID of the *csi-secrets-store-provider-aws* Pod.

  ```
  kubectl -n kube-system get pods
  kubectl -n kube-system logs pod/PODID
  ```

# Use AWS Secrets and Configuration Provider CSI with IAM Roles for Service Accounts (IRSA)
<a name="integrating_ascp_irsa"></a>

**Topics**
+ [

## Prerequisites
](#prerequisites)
+ [

## Set up access control
](#integrating_ascp_irsa_access)
+ [

## Identify which secrets to mount
](#integrating_ascp_irsa_mount)
+ [

## Troubleshoot
](#integrating_ascp_irsa_trouble)

## Prerequisites
<a name="prerequisites"></a>
+ Amazon EKS cluster (version 1.17 or later)
+ Access to AWS CLI and Amazon EKS cluster via `kubectl`

## Set up access control
<a name="integrating_ascp_irsa_access"></a>

The ASCP retrieves the Amazon EKS Pod Identity and exchanges it for an IAM role. You set permissions in an IAM policy for that IAM role. When the ASCP assumes the IAM role, it gets access to the secrets you authorized. Other containers can't access the secrets unless you also associate them with the IAM role. 

**To grant your Amazon EKS Pod access to secrets in Secrets Manager**

1. Create a permissions policy that grants `secretsmanager:GetSecretValue` and `secretsmanager:DescribeSecret` permission to the secrets that the Pod needs to access. For an example policy, see [Example: Permission to read and describe individual secrets](auth-and-access_iam-policies.md#auth-and-access_examples-read-and-describe).

1. Create an IAM OpenID Connect (OIDC) provider for the cluster if you don't already have one. For more information, see [Create an IAM OIDC provider for your cluster](https://docs.aws.amazon.com/eks/latest/userguide/enable-iam-roles-for-service-accounts.html) in the *Amazon EKS User Guide*.

1. Create an [IAM role for service account](https://docs.aws.amazon.com/eks/latest/userguide/iam-roles-for-service-accounts.html) and attach the policy to it. For more information, see [Create an IAM role for a service account](https://docs.aws.amazon.com/eks/latest/userguide/iam-roles-for-service-accounts.html) in the *Amazon EKS User Guide*.

1. If you use a private Amazon EKS cluster, make sure that the VPC that the cluster is in has an AWS STS endpoint. For information about creating an endpoint, see [Interface VPC endpoints](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_interface_vpc_endpoints.html) in the *AWS Identity and Access Management User Guide*.

## Identify which secrets to mount
<a name="integrating_ascp_irsa_mount"></a>

To determine which secrets the ASCP mounts in Amazon EKS as files on the filesystem, you create a [SecretProviderClass](ascp-examples.md#ascp-examples-secretproviderclass) YAML file. The `SecretProviderClass` lists the secrets to mount and the file name to mount them as. The `SecretProviderClass` must be in the same namespace as the Amazon EKS Pod it references.

### Mount the secrets as files
<a name="mount-secrets"></a>

The following instructions show how to mount secrets as files using example YAML files [ExampleSecretProviderClass.yaml](https://github.com/aws/secrets-store-csi-driver-provider-aws/blob/main/examples/ExampleSecretProviderClass-IRSA.yaml) and [ExampleDeployment.yaml](https://github.com/aws/secrets-store-csi-driver-provider-aws/blob/main/examples/ExampleDeployment-IRSA.yaml).

**To mount secrets in Amazon EKS**

1. Apply the `SecretProviderClass` to the Pod:

   ```
   kubectl apply -f ExampleSecretProviderClass.yaml
   ```

1. Deploy your Pod:

   ```
   kubectl apply -f ExampleDeployment.yaml
   ```

1. The ASCP mounts the files.

## Troubleshoot
<a name="integrating_ascp_irsa_trouble"></a>

You can view most errors by describing the Pod deployment. 

**To see error messages for your container**

1. Get a list of Pod names with the following command. If you aren't using the default namespace, use `-n nameSpace`.

   ```
   kubectl get pods
   ```

1. To describe the Pod, in the following command, for *podId* use the Pod ID from the Pods you found in the previous step. If you aren't using the default namespace, use `-n nameSpace`.

   ```
   kubectl describe pod/podId
   ```

**To see errors for the ASCP**
+ To find more information in the provider logs, in the following command, for *podId* use the ID of the *csi-secrets-store-provider-aws* Pod.

  ```
  kubectl -n kube-system get pods
  kubectl -n kube-system logs Pod/podId
  ```
+ 

**Verify that the `SecretProviderClass` CRD is installed:**

  ```
  kubectl get crd secretproviderclasses.secrets-store.csi.x-k8s.io
  ```

  This command should return information about the `SecretProviderClass` custom resource definition.
+ 

**Verify that the SecretProviderClass object was created.**

  ```
  kubectl get secretproviderclass SecretProviderClassName -o yaml
  ```

# AWS Secrets and Configuration Provider code examples
<a name="ascp-examples"></a>

## ASCP authentication and access control examples
<a name="ascp-auth-access-examples"></a>

### Example: IAM policy allowing Amazon EKS Pod Identity service (pods.eks.amazonaws.com) to assume the role and tag the session:
<a name="w2aac19c17c18b5b3"></a>

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Service": "pods.eks.amazonaws.com"
      },
      "Action": [
        "sts:AssumeRole",
        "sts:TagSession"
      ]
    }
  ]
}
```

------

## SecretProviderClass
<a name="ascp-examples-secretproviderclass"></a>

You use YAML to describe which secrets to mount in Amazon EKS using the ASCP. For examples, see [SecretProviderClass usage](#ascp-scenarios-secretproviderclass).

### SecretProviderClass YAML structure
<a name="w2aac19c17c18c25b5"></a>

```
apiVersion: secrets-store.csi.x-k8s.io/v1
kind: SecretProviderClass
metadata:
   name: name
spec:
  provider: aws
  parameters:
    region:
    failoverRegion:
    pathTranslation:
    usePodIdentity:
    preferredAddressType:
    objects:
```

The parameters field contains the details of the mount request:

**region**  
(Optional) The AWS Region of the secret. If you don't use this field, the ASCP looks up the Region from the annotation on the node. This lookup adds overhead to mount requests, so we recommend that you provide the Region for clusters that use large numbers of Pods.  
If you also specify `failoverRegion`, the ASCP tries to retrieve the secret from both Regions. If either Region returns a 4xx error, for example for an authentication issue, the ASCP does not mount either secret. If the secret is retrieved successfully from `region`, then the ASCP mounts that secret value. If the secret is not retrieved successfully from `region`, but it is retrieved successfully from `failoverRegion`, then the ASCP mounts that secret value.

**failoverRegion**  
(Optional) If you include this field, the ASCP tries to retrieve the secret from the Regions defined in `region` and this field. If either Region returns a 4xx error, for example for an authentication issue, the ASCP does not mount either secret. If the secret is retrieved successfully from `region`, then the ASCP mounts that secret value. If the secret is not retrieved successfully from `region`, but it is retrieved successfully from `failoverRegion`, then the ASCP mounts that secret value. For an example of how to use this field, see [Multi-Region secret failover](#multi-region-failover).

**pathTranslation**  
(Optional) A single substitution character to use if the file name in Amazon EKS will contain the path separator character, such as slash (/) on Linux. The ASCP can't create a mounted file that contains a path separator character. Instead, the ASCP replaces the path separator character with a different character. If you don't use this field, the replacement character is underscore (\$1), so for example, `My/Path/Secret` mounts as `My_Path_Secret`.   
To prevent character substitution, enter the string `False`.

**usePodIdentity**  
(Optional) Determines the authentication approach. When not specified, it defaults to IAM Roles for Service Accounts (IRSA) (IRSA).  
+ To use EKS Pod Identity, use any of these values: `"true"`", `"True"`, `"TRUE"`, `"t"`, or `"T"`.
+ To explicitly use IRSA, set to any of these values: `"false"`, `"False"`, `"FALSE"`, `"f"`, or `"F"`"=.

**preferredAddressType**  
(Optional) Specifies the preferred IP address type for Pod Identity Agent endpoint communication. The field is only applicable when using EKS Pod Identity feature and will be ignored when using IAM Roles for Service Accounts.Values are case-insensitive. Valid values are:  
+ `"ipv4"`, `"IPv4"`", or `"IPV4"` – Force the use of Pod Identity Agent IPv4 endpoint
+ `"ipv6"`, `"IPv6"`, or `"IPV6"` – Force the use of Pod Identity Agent IPv6 endpoint
+ not specified – Use auto endpoint selection, trying IPv4 endpoint first and falling back to IPv6 endpoint if IPv4 fails

**objects**  
A string containing a YAML declaration of the secrets to be mounted. We recommend using a YAML multi-line string or pipe (\$1) character.    
**objectName**  
Required. Specifies the name of the secret or parameter to be fetched. For Secrets Manager this is the [https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_GetSecretValue.html#API_GetSecretValue_RequestParameters](https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_GetSecretValue.html#API_GetSecretValue_RequestParameters) parameter and can be either the friendly name or full ARN of the secret. For SSM Parameter Store, this is the [https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_GetParameter.html#API_GetParameter_RequestParameters](https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_GetParameter.html#API_GetParameter_RequestParameters) of the parameter and can be either the name or full ARN of the parameter.  
**objectType**  
Required if you don't use a Secrets Manager ARN for `objectName`. Can be either `secretsmanager` or `ssmparameter`.   
**objectAlias**  
(Optional) The file name of the secret in the Amazon EKS Pod. If you don't specify this field, the `objectName` appears as the file name.  
**filePermission**  
(Optional) The 4 digit octal string which specifies the file permission to mount secret with. If you don't specify this field it will default to `"0644"`.   
**objectVersion**  
(Optional) The version ID of the secret. Not recommended because you must update the version ID every time you update the secret. By default the most recent version is used. If you include a `failoverRegion`, this field represents the primary `objectVersion`.  
**objectVersionLabel**  
(Optional) The alias for the version. The default is the most recent version AWSCURRENT. For more information, see [Secret versions](whats-in-a-secret.md#term_version). If you include a `failoverRegion`, this field represents the primary `objectVersionLabel`.  
**jmesPath**  
(Optional) A map of the keys in the secret to the files to be mounted in Amazon EKS. To use this field, your secret value must be in JSON format. If you use this field, you must include the subfields `path` and `objectAlias`.    
**path**  
A key from a key-value pair in the JSON of the secret value. If the field contains a hyphen, use single quotes to escape it, for example: `path: '"hyphenated-path"'`  
**objectAlias**  
The file name to be mounted in the Amazon EKS Pod. If the field contains a hyphen, use single quotes to escape it, for example: `objectAlias: '"hyphenated-alias"'`  
**filePermission**  
(Optional) The 4 digit octal string which specifies the file permission to mount secret with. If you don't specify this field it will default to the parent object's file permission.   
**failoverObject**  
(Optional) If you specify this field, the ASCP tries to retrieve both the secret specified in the primary `objectName` and the secret specified in the `failoverObject` `objectName` sub-field. If either returns a 4xx error, for example for an authentication issue, the ASCP does not mount either secret. If the secret is retrieved successfully from the primary `objectName`, then the ASCP mounts that secret value. If the secret is not retrieved successfully from the primary `objectName`, but it is retrieved successfully from the failover `objectName`, then the ASCP mounts that secret value. If you include this field, you must include the field `objectAlias`. For an example of how to use this field, see [Failover to a different secret](#failover-secret).  
You typically use this field when the failover secret isn't a replica. For an example of how to specify a replica, see [Multi-Region secret failover](#multi-region-failover).    
**objectName**  
The name or full ARN of the failover secret. If you use an ARN, the Region in the ARN must match the field `failoverRegion`.  
**objectVersion**  
(Optional) The version ID of the secret. Must match the primary `objectVersion`. Not recommended because you must update the version ID every time you update the secret. By default the most recent version is used.   
**objectVersionLabel**  
(Optional) The alias for the version. The default is the most recent version AWSCURRENT. For more information, see [Secret versions](whats-in-a-secret.md#term_version). 

### Create a basic SecretProviderClass configuration to mount secrets in your Amazon EKS Pods.
<a name="w2aac19c17c18c25c11"></a>

------
#### [ Pod Identity ]

SecretProviderClass to use a secret in the same Amazon EKS cluster:

```
apiVersion: secrets-store.csi.x-k8s.io/v1
kind: SecretProviderClass
metadata:
  name: aws-secrets-manager
spec:
  provider: aws
  parameters:
    objects: |
      - objectName: "mySecret"
        objectType: "secretsmanager"
    usePodIdentity: "true"
```

------
#### [ IRSA ]

```
apiVersion: secrets-store.csi.x-k8s.io/v1
kind: SecretProviderClass
metadata:
  name: deployment-aws-secrets
spec:
  provider: aws
  parameters:
    objects: |
        - objectName: "MySecret"
          objectType: "secretsmanager"
```

------

### SecretProviderClass usage
<a name="ascp-scenarios-secretproviderclass"></a>

Use these examples to create SecretProviderClass configurations for different scenarios.

#### Example: Mount secrets by name or ARN
<a name="mount-by-name-arn"></a>

This example shows how to mount three different types of secrets:
+ A secret specified by full ARN
+ A secret specified by name
+ A specific version of a secret

```
apiVersion: secrets-store.csi.x-k8s.io/v1
kind: SecretProviderClass
metadata:
  name: aws-secrets
spec:
  provider: aws
  parameters:
    objects: |
      - objectName: "arn:aws:secretsmanager:us-east-2:777788889999:secret:MySecret2-d4e5f6"
      - objectName: "MySecret3"
        objectType: "secretsmanager"
      - objectName: "MySecret4"
        objectType: "secretsmanager"
        objectVersionLabel: "AWSCURRENT"
```

#### Example: Mount key-value pairs from a secret
<a name="mount-key-value-pairs"></a>

This example shows how to mount specific key-value pairs from a JSON-formatted secret:

```
apiVersion: secrets-store.csi.x-k8s.io/v1
kind: SecretProviderClass
metadata:
  name: aws-secrets
spec:
  provider: aws
  parameters:
    objects: |
      - objectName: "arn:aws:secretsmanager:us-east-2:777788889999:secret:MySecret-a1b2c3"
        jmesPath: 
            - path: username
              objectAlias: dbusername
            - path: password
              objectAlias: dbpassword
```

#### Example: Mount secrets by file permission
<a name="mount-by-permission"></a>

This example shows how to mount a secret with a specific file permission

```
apiVersion: secrets-store.csi.x-k8s.io/v1
kind: SecretProviderClass
metadata:
  name: aws-secrets
spec:
  provider: aws
  parameters:
    objects: |
      - objectName: "mySecret"
        objectType: "secretsmanager"
        filePermission: "0600"
        jmesPath: 
            - path: username
              objectAlias: dbusername
              filePermission: "0400"
```

#### Example: Failover configuration examples
<a name="failover-examples"></a>

These examples show how to configure failover for secrets.

##### Multi-Region secret failover
<a name="multi-region-failover"></a>

This example shows how to configure automatic failover for a secret replicated across multiple Regions:

```
apiVersion: secrets-store.csi.x-k8s.io/v1
kind: SecretProviderClass
metadata:
  name: aws-secrets
spec:
  provider: aws
  parameters:
    region: us-east-1
    failoverRegion: us-east-2
    objects: |
      - objectName: "MySecret"
```

##### Failover to a different secret
<a name="failover-secret"></a>

This example shows how to configure failover to a different secret (not a replica):

```
apiVersion: secrets-store.csi.x-k8s.io/v1
kind: SecretProviderClass
metadata:
  name: aws-secrets
spec:
  provider: aws
  parameters:
    region: us-east-1
    failoverRegion: us-east-2
    objects: |
      - objectName: "arn:aws:secretsmanager:us-east-1:777788889999:secret:MySecret-a1b2c3"
        objectAlias: "MyMountedSecret"
        failoverObject: 
          - objectName: "arn:aws:secretsmanager:us-east-2:777788889999:secret:MyFailoverSecret-d4e5f6"
```

## Additional resources
<a name="additional-resources"></a>

For more information about using ASCP with Amazon EKS, see the following resources:
+ [Using Pod Identity with Amazon EKS](https://docs.aws.amazon.com/eks/latest/userguide/pod-identities.html)
+ [Using AWS Secrets and Configuration Provider](https://docs.aws.amazon.com/secretsmanager/latest/userguide/integrating_ascp_csi.html)
+ [AWS Secrets Store CSI Driver on GitHub](https://github.com/aws/secrets-store-csi-driver-provider-aws)

# Use AWS Secrets Manager secrets in AWS Lambda functions
<a name="retrieving-secrets_lambda"></a>

AWS Lambda is a serverless compute service that lets you run code without provisioning or managing servers. Parameter Store, a capability of AWS Systems Manager, provides secure, hierarchical storage for configuration data management and secrets management. You can use the AWS Parameters and Secrets Lambda Extension to retrieve and cache AWS Secrets Manager secrets and Parameter Store parameters in Lambda functions without using an SDK. For detailed information about using this extension, see [Use Secrets Manager secrets in Lambda functions](https://docs.aws.amazon.com/lambda/latest/dg/with-secrets-manager.html) in the *Lambda Developer Guide*.

## Using Secrets Manager secrets with Lambda
<a name="retrieving-secrets_lambda_getting-started"></a>

The Lambda Developer Guide provides comprehensive instructions for using Secrets Manager secrets in Lambda functions. To get started:

1. Follow the step-by-step tutorial in [Use Secrets Manager secrets in Lambda functions](https://docs.aws.amazon.com/lambda/latest/dg/with-secrets-manager.html), which includes:
   + Creating a Lambda function with your preferred runtime (Python, Node.js, Java)
   + Adding the AWS Parameters and Secrets Lambda Extension as a layer
   + Configuring the necessary permissions
   + Writing code to retrieve secrets from the extension
   + Testing your function

1. Learn about environment variables for configuring the extension's behavior, including cache settings and timeouts

1. Understand best practices for working with secret rotation

### Using Secrets Manager and Lambda in a VPC
<a name="retrieving-secrets_lambda_vpc"></a>

If your Lambda function runs in a VPC, you need to create a VPC endpoint so that the extension can make calls to Secrets Manager. For more information, see [Using an AWS Secrets Manager VPC endpoint](vpc-endpoint-overview.md).

## Using the AWS Parameters and Secrets Lambda Extension
<a name="retrieving-secrets_lambda_parameter-store"></a>

The extension can retrieve both Secrets Manager secrets and Parameter Store parameters. For detailed information about using Parameter Store parameters with the extension, see [Using Parameter Store parameters in Lambda functions](https://docs.aws.amazon.com/systems-manager/latest/userguide/ps-integration-lambda-extensions.html) in the *AWS Systems Manager User Guide*.

The Systems Manager documentation includes:
+ Detailed explanation of how the extension works with Parameter Store
+ Instructions for adding the extension to a Lambda function
+ Environment variables for configuring the extension
+ Sample commands for retrieving parameters
+ Complete list of extension ARNs for all supported architectures and regions

# Using the AWS Secrets Manager Agent
<a name="secrets-manager-agent"></a>

## How the Secrets Manager Agent works
<a name="agent-overview"></a>

The AWS Secrets Manager Agent is a client-side HTTP service that helps you standardize how you consume secrets from Secrets Manager across your compute environments. You can use it with the following services:
+ AWS Lambda
+ Amazon Elastic Container Service
+ Amazon Elastic Kubernetes Service
+ Amazon Elastic Compute Cloud

The Secrets Manager Agent retrieves and caches secrets in memory, allowing your applications to get secrets from localhost instead of making direct calls to Secrets Manager. The Secrets Manager Agent can only read secrets—it can't modify them.

**Important**  
The Secrets Manager Agent uses the AWS credentials from your environment to call Secrets Manager. It includes protection against Server Side Request Forgery (SSRF) to help improve secret security. The Secrets Manager Agent uses the post-quantum ML-KEM key exchange as the highest-priority key exchange by default.

## Understanding Secrets Manager Agent caching
<a name="agent-caching"></a>

The Secrets Manager Agent uses an in-memory cache that resets when the Secrets Manager Agent restarts. It periodically refreshes cached secret values based on the following:
+ The default refresh frequency (TTL) is 300 seconds
+ You can modify the TTL using a configuration file
+ The refresh occurs when you request a secret after the TTL expires

**Note**  
The Secrets Manager Agent doesn't include cache invalidation. If a secret rotates before the cache entry expires, the Secrets Manager Agent might return a stale secret value.

The Secrets Manager Agent returns secret values in the same format as the response of `GetSecretValue`. Secret values aren't encrypted in the cache.

**Topics**
+ [

## How the Secrets Manager Agent works
](#agent-overview)
+ [

## Understanding Secrets Manager Agent caching
](#agent-caching)
+ [

## Build the Secrets Manager Agent
](#secrets-manager-agent-build)
+ [

## Install the Secrets Manager Agent
](#secrets-manager-agent-install)
+ [

## Retrieve secrets with the Secrets Manager Agent
](#secrets-manager-agent-call)
+ [

## Understanding the `refreshNow` parameter
](#secrets-manager-agent-refresh)
+ [

## Configure the Secrets Manager Agent
](#secrets-manager-agent-config)
+ [

## Optional features
](#secrets-manager-agent-features)
+ [

## Logging
](#secrets-manager-agent-log)
+ [

## Security considerations
](#secrets-manager-agent-security)

## Build the Secrets Manager Agent
<a name="secrets-manager-agent-build"></a>

Before you begin, ensure you have the standard development tools and Rust tools installed for your platform.

**Note**  
Building the agent with the `fips` feature enabled on macOS currently requires the following workaround:  
Create an environment variable called `SDKROOT` which is set to the result of running `xcrun --show-sdk-path`

------
#### [ RPM-based systems ]

**To build on RPM-based systems**

1. Use the `install` script provided in the repository. 

   The script generates a random SSRF token on startup and stores it in the file `/var/run/awssmatoken`. The token is readable by the `awssmatokenreader` group that the install script creates. 

1. To allow your application to read the token file, you need to add the user account that your application runs under to the `awssmatokenreader` group. For example, you can grant permissions for your application to read the token file with the following usermod command, where *<APP\$1USER>* is the user ID under which your application runs.

   ```
   sudo usermod -aG awssmatokenreader <APP_USER>
   ```

**Install development tools**  
On RPM-based systems such as AL2023, install the Development Tools group:

   ```
   sudo yum -y groupinstall "Development Tools"
   ```

1. 

**Install Rust**  
Follow the instructions at [Install Rust](https://www.rust-lang.org/tools/install) in the *Rust documentation*:

   ```
   curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh # Follow the on-screen instructions
   . "$HOME/.cargo/env"
   ```

1. 

**Build the agent**  
Build the Secrets Manager Agent using the cargo build command:

   ```
   cargo build --release
   ```

   You will find the executable under `target/release/aws_secretsmanager_agent`.

------
#### [ Debian-based systems ]

**To build on Debian-based systems**

1. 

**Install development tools**  
On Debian-based systems such as Ubuntu, install the build-essential package:

   ```
   sudo apt install build-essential
   ```

1. 

**Install Rust**  
Follow the instructions at [Install Rust](https://www.rust-lang.org/tools/install) in the *Rust documentation*:

   ```
   curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh # Follow the on-screen instructions
   . "$HOME/.cargo/env"
   ```

1. 

**Build the agent**  
Build the Secrets Manager Agent using the cargo build command:

   ```
   cargo build --release
   ```

   You will find the executable under `target/release/aws_secretsmanager_agent`.

------
#### [ Windows ]

**To build on Windows**

1. 

**Set up development environment**  
Follow the instructions at [Set up your dev environment on Windows for Rust](https://learn.microsoft.com/en-us/windows/dev-environment/rust/setup) in the *Microsoft Windows documentation*.

1. 

**Build the agent**  
Build the Secrets Manager Agent using the cargo build command:

   ```
   cargo build --release
   ```

   You will find the executable under `target/release/aws_secretsmanager_agent.exe`.

------
#### [ Cross-compile natively ]

**To cross-compile natively**

1. 

**Install cross-compile tools**  
On distributions where the mingw-w64 package is available such as Ubuntu, install the cross-compile toolchain:

   ```
   # Install the cross compile tool chain
   sudo add-apt-repository universe
   sudo apt install -y mingw-w64
   ```

1. 

**Add Rust build targets**  
Install the Windows GNU build target:

   ```
   rustup target add x86_64-pc-windows-gnu
   ```

1. 

**Build for Windows**  
Cross-compile the agent for Windows:

   ```
   cargo build --release --target x86_64-pc-windows-gnu
   ```

   You will find the executable at `target/x86_64-pc-windows-gnu/release/aws_secretsmanager_agent.exe`.

------
#### [ Cross compile with Rust cross ]

**To cross-compile using Rust cross**

If the cross-compile tools are not available natively on the system, you can use the Rust cross project. For more information, see [https://github.com/cross-rs/cross](https://github.com/cross-rs/cross).
**Important**  
We recommend 32GB disk space for the build environment.

1. 

**Set up Docker**  
Install and configure Docker:

   ```
   # Install and start docker
   sudo yum -y install docker
   sudo systemctl start docker
   sudo systemctl enable docker # Make docker start after reboot
   ```

1. 

**Configure Docker permissions**  
Add your user to the docker group:

   ```
   # Give ourselves permission to run the docker images without sudo
   sudo usermod -aG docker $USER
   newgrp docker
   ```

1. 

**Build for Windows**  
Install cross and build the executable:

   ```
   # Install cross and cross compile the executable
   cargo install cross
   cross build --release --target x86_64-pc-windows-gnu
   ```

------

## Install the Secrets Manager Agent
<a name="secrets-manager-agent-install"></a>

Choose your compute environment from the following installation options.

------
#### [ Amazon EC2 ]

**To install the Secrets Manager Agent on Amazon EC2**

1. 

**Navigate to configuration directory**  
Change to the configuration directory:

   ```
   cd aws_secretsmanager_agent/configuration
   ```

1. 

**Run installation script**  
Run the `install` script provided in the repository.

   The script generates a random SSRF token on startup and stores it in the file `/var/run/awssmatoken`. The token is readable by the `awssmatokenreader` group that the install script creates.

1. 

**Configure application permissions**  
Add the user account that your application runs under to the `awssmatokenreader` group:

   ```
   sudo usermod -aG awssmatokenreader APP_USER
   ```

   Replace *APP\$1USER* with the user ID under which your application runs.

------
#### [ Container Sidecar ]

You can run the Secrets Manager Agent as a sidecar container alongside your application by using Docker. Then your application can retrieve secrets from the local HTTP server the Secrets Manager Agent provides. For information about Docker, see the [Docker documentation](https://docs.docker.com).

**To create a sidecar container for the Secrets Manager Agent**

1. 

**Create agent Dockerfile**  
Create a Dockerfile for the Secrets Manager Agent sidecar container:

   ```
   # Use the latest Debian image as the base
   FROM debian:latest
   
   # Set the working directory inside the container
   WORKDIR /app 
   
   # Copy the Secrets Manager Agent binary to the container
   COPY secrets-manager-agent . 
   
   # Install any necessary dependencies
   RUN apt-get update && apt-get install -y ca-certificates 
   
   # Set the entry point to run the Secrets Manager Agent binary
   ENTRYPOINT ["./secrets-manager-agent"]
   ```

1. 

**Create application Dockerfile**  
Create a Dockerfile for your client application.

1. 

**Create Docker Compose file**  
Create a Docker Compose file to run both containers with a shared network interface:
**Important**  
You must load AWS credentials and the SSRF token for the application to be able to use the Secrets Manager Agent. For Amazon EKS and Amazon ECS, see the following:  
[Manage access](https://docs.aws.amazon.com/eks/latest/userguide/cluster-auth.html) in the *Amazon EKS User Guide*
[Amazon ECS task IAM role](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-iam-roles.html) in the *Amazon ECS Developer Guide*

   ```
   version: '3'
   services:
       client-application:
       container_name: client-application
       build:
           context: .
           dockerfile: Dockerfile.client
       command: tail -f /dev/null  # Keep the container running
       
   
       secrets-manager-agent:
       container_name: secrets-manager-agent
       build:
           context: .
           dockerfile: Dockerfile.agent
       network_mode: "container:client-application"  # Attach to the client-application container's network
       depends_on:
           - client-application
   ```

1. 

**Copy agent binary**  
Copy the `secrets-manager-agent` binary to the same directory that contains your Dockerfiles and Docker Compose file.

1. 

**Build and run containers**  
Build and run the containers using Docker Compose:

   ```
   docker-compose up --build
   ```

1. 

**Next steps**  
You can now use the Secrets Manager Agent to retrieve secrets from your client container. For more information, see [Retrieve secrets with the Secrets Manager Agent](#secrets-manager-agent-call).

------
#### [ Lambda ]

You can [package the Secrets Manager Agent as a Lambda extension](https://docs.aws.amazon.com/lambda/latest/dg/packaging-layers.html). Then you can [add it to your Lambda function as a layer](https://docs.aws.amazon.com/lambda/latest/dg/adding-layers.html) and call the Secrets Manager Agent from your Lambda function to get secrets.

The following instructions show how to get a secret named *MyTest* by using the example script `secrets-manager-agent-extension.sh` in [https://github.com/aws/aws-secretsmanager-agent](https://github.com/aws/aws-secretsmanager-agent) to install the Secrets Manager Agent as a Lambda extension.

**To create a Lambda extension for the Secrets Manager Agent**

1. 

**Package the agent layer**  
From the root of the Secrets Manager Agent code package, run the following commands:

   ```
   AWS_ACCOUNT_ID=AWS_ACCOUNT_ID
   LAMBDA_ARN=LAMBDA_ARN
   
   # Build the release binary 
   cargo build --release --target=x86_64-unknown-linux-gnu
   
   # Copy the release binary into the `bin` folder
   mkdir -p ./bin
   cp ./target/x86_64-unknown-linux-gnu/release/aws_secretsmanager_agent ./bin/secrets-manager-agent
   
   # Copy the `secrets-manager-agent-extension.sh` example script into the `extensions` folder.
   mkdir -p ./extensions
   cp aws_secretsmanager_agent/examples/example-lambda-extension/secrets-manager-agent-extension.sh ./extensions
   
   # Zip the extension shell script and the binary 
   zip secrets-manager-agent-extension.zip bin/* extensions/*
   
   # Publish the layer version
   LAYER_VERSION_ARN=$(aws lambda publish-layer-version \
       --layer-name secrets-manager-agent-extension \
       --zip-file "fileb://secrets-manager-agent-extension.zip" | jq -r '.LayerVersionArn')
   ```

1. 

**Configure SSRF token**  
The default configuration of the agent will automatically set the SSRF token to the value set in the pre-set `AWS_SESSION_TOKEN` or `AWS_CONTAINER_AUTHORIZATION_TOKEN` environment variables (the latter variable for Lambda functions with SnapStart enabled). Alternatively, you can define the `AWS_TOKEN` environment variable with an arbitrary value for your Lambda function instead as this variable takes precedence over the other two. If you choose to use the `AWS_TOKEN` environment variable, you must set that environment variable with a `lambda:UpdateFunctionConfiguration` call.

1. 

**Attach layer to function**  
Attach the layer version to your Lambda function:

   ```
   # Attach the layer version to the Lambda function
   aws lambda update-function-configuration \
       --function-name $LAMBDA_ARN \
       --layers "$LAYER_VERSION_ARN"
   ```

1. 

**Update function code**  
Update your Lambda function to query `http://localhost:2773/secretsmanager/get?secretId=MyTest` with the `X-Aws-codes-Secrets-Token` header value set to the value of the SSRF token sourced from one the environment variables mentioned above to retrieve the secret. Be sure to implement retry logic in your application code to accommodate delays in initialization and registration of the Lambda extension.

1. 

**Test the function**  
Invoke the Lambda function to verify that the secret is being correctly fetched.

------

## Retrieve secrets with the Secrets Manager Agent
<a name="secrets-manager-agent-call"></a>

To retrieve a secret, call the local Secrets Manager Agent endpoint with the secret name or ARN as a query parameter. By default, the Secrets Manager Agent retrieves the `AWSCURRENT` version of the secret. To retrieve a different version, use either the versionStage or versionId parameter.

**Important**  
To help protect the Secrets Manager Agent, you must include a SSRF token header as part of each request: `X-Aws-Parameters-Secrets-Token`. The Secrets Manager Agent denies requests that don't have this header or that have an invalid SSRF token. You can customize the SSRF header name in the [Configure the Secrets Manager Agent](#secrets-manager-agent-config).

### Required permissions
<a name="agent-call-permissions"></a>

The Secrets Manager Agent uses the AWS SDK for Rust, which uses the [AWS credential provider chain](https://docs.aws.amazon.com/sdk-for-rust/latest/dg/credentials.html). The identity of these IAM credentials determines the permissions the Secrets Manager Agent has to retrieve secrets.
+ `secretsmanager:DescribeSecret`
+ `secretsmanager:GetSecretValue`

For more information about permissions, see [Permissions reference for AWS Secrets Manager](auth-and-access.md#reference_iam-permissions).

**Important**  
After the secret value is pulled into the Secrets Manager Agent, any user with access to the compute environment and SSRF token can access the secret from the Secrets Manager Agent cache. For more information, see [Security considerations](#secrets-manager-agent-security).

### Example requests
<a name="agent-call-examples"></a>

------
#### [ curl ]

**Example – Get a secret using curl**  
The following curl example shows how to get a secret from the Secrets Manager Agent. The example relies on the SSRF being present in a file, which is where it is stored by the install script.  

```
curl -v -H \\
    "X-Aws-Parameters-Secrets-Token: $(/var/run/awssmatoken)" \\
    'http://localhost:2773/secretsmanager/get?secretId=YOUR_SECRET_ID' \\
    echo
```

------
#### [ Python ]

**Example – Get a secret using Python**  
The following Python example shows how to get a secret from the Secrets Manager Agent. The example relies on the SSRF being present in a file, which is where it is stored by the install script.  

```
import requests
import json

# Function that fetches the secret from Secrets Manager Agent for the provided secret id. 
def get_secret():
    # Construct the URL for the GET request
    url = f"http://localhost:2773/secretsmanager/get?secretId=YOUR_SECRET_ID"

    # Get the SSRF token from the token file
    with open('/var/run/awssmatoken') as fp:
        token = fp.read() 

    headers = {
        "X-Aws-Parameters-Secrets-Token": token.strip()
    }

    try:
        # Send the GET request with headers
        response = requests.get(url, headers=headers)

        # Check if the request was successful
        if response.status_code == 200:
            # Return the secret value
            return response.text
        else:
            # Handle error cases
            raise Exception(f"Status code {response.status_code} - {response.text}")

    except Exception as e:
        # Handle network errors
        raise Exception(f"Error: {e}")
```

------

## Understanding the `refreshNow` parameter
<a name="secrets-manager-agent-refresh"></a>

The Secrets Manager Agent uses an in-memory cache to store secret values, which it refreshes periodically. By default, this refresh occurs when you request a secret after the Time to Live (TTL) has expired, typically every 300 seconds. However, this approach can sometimes result in stale secret values, especially if a secret rotates before the cache entry expires.

To address this limitation, the Secrets Manager Agent supports a parameter called `refreshNow` in the URL. You can use this parameter to force an immediate refresh of a secret's value, bypassing the cache and ensuring you have the most up-to-date information.

**Default behavior (without `refreshNow`)**  
+ Uses cached values until TTL expires
+ Refreshes secrets only after TTL (default 300 seconds)
+ May return stale values if secrets rotate before the cache expires

**Behavior with `refreshNow=true`**  
+ Bypasses the cache entirely
+ Retrieves the latest secret value directly from Secrets Manager
+ Updates the cache with the fresh value and resets the TTL
+ Ensures you always get the most current secret value

### Force-refresh a secret value
<a name="refreshnow-examples"></a>

**Important**  
The default value of `refreshNow` is `false`. When set to `true`, it overrides the TTL specified in the Secrets Manager Agent configuration file and makes an API call to Secrets Manager.

------
#### [ curl ]

**Example – Force-refresh a secret using curl**  
The following curl example shows how to force the Secrets Manager Agent to refresh the secret. The example relies on the SSRF being present in a file, which is where it is stored by the install script.  

```
curl -v -H \\
"X-Aws-Parameters-Secrets-Token: $(/var/run/awssmatoken)" \\
'http://localhost:2773/secretsmanager/get?secretId=YOUR_SECRET_ID&refreshNow=true' \\
echo
```

------
#### [ Python ]

**Example – Force-refresh a secret using Python**  
The following Python example shows how to get a secret from the Secrets Manager Agent. The example relies on the SSRF being present in a file, which is where it is stored by the install script.  

```
import requests
import json

# Function that fetches the secret from Secrets Manager Agent for the provided secret id. 
def get_secret():
    # Construct the URL for the GET request
    url = f"http://localhost:2773/secretsmanager/get?secretId=YOUR_SECRET_ID&refreshNow=true"

    # Get the SSRF token from the token file
    with open('/var/run/awssmatoken') as fp:
        token = fp.read() 

    headers = {
        "X-Aws-Parameters-Secrets-Token": token.strip()
    }

    try:
        # Send the GET request with headers
        response = requests.get(url, headers=headers)

        # Check if the request was successful
        if response.status_code == 200:
            # Return the secret value
            return response.text
        else:
            # Handle error cases
            raise Exception(f"Status code {response.status_code} - {response.text}")

    except Exception as e:
        # Handle network errors
        raise Exception(f"Error: {e}")
```

------

## Configure the Secrets Manager Agent
<a name="secrets-manager-agent-config"></a>

To change the configuration of the Secrets Manager Agent, create a [TOML](https://toml.io/en/) config file, and then call `./aws_secretsmanager_agent --config config.toml`.Configuration options

**`log_level`**  
The level of detail reported in logs for the Secrets Manager Agent: DEBUG, INFO, WARN, ERROR, or NONE. The default is INFO.

**`log_to_file`**  
Whether to log to a file or stdout/stderr: `true` or `false`. The default is `true`.

**`http_port`**  
The port for the local HTTP server, in the range 1024 to 65535. The default is 2773.

**`region`**  
The AWS Region to use for requests. If no Region is specified, the Secrets Manager Agent determines the Region from the SDK. For more information, see [Specify your credentials and default Region](https://docs.aws.amazon.com/sdk-for-rust/latest/dg/credentials.html) in the *AWS SDK for Rust Developer Guide*.

**`ttl_seconds`**  
The TTL in seconds for the cached items, in the range 0 to 3600. The default is 300. 0 indicates that there is no caching.

**`cache_size`**  
The maximum number of secrets that can be stored in the cache, in the range 1 to 1000. The default is 1000.

**`ssrf_headers`**  
A list of header names the Secrets Manager Agent checks for the SSRF token. The default is "X-Aws-Parameters-Secrets-Token, X-Vault-Token".

**`ssrf_env_variables`**  
A list of environment variable names the Secrets Manager Agent checks in sequential order for the SSRF token. The environment variable can contain the token or a reference to the token file as in: `AWS_TOKEN=file:///var/run/awssmatoken`. The default is "AWS\$1TOKEN, AWS\$1SESSION\$1TOKEN, AWS\$1CONTAINER\$1AUTHORIZATION\$1TOKEN".

**`path_prefix`**  
The URI prefix used to determine if the request is a path based request. The default is "/v1/".

**`max_conn`**  
The maximum number of connections from HTTP clients that the Secrets Manager Agent allows, in the range 1 to 1000. The default is 800.

## Optional features
<a name="secrets-manager-agent-features"></a>

The Secrets Manager Agent can be built with optional features by passing the `--features` flag to `cargo build`. The available features are:Build features

**`prefer-post-quantum`**  
Makes `X25519MLKEM768` the highest-priority key exchange algorithm. Otherwise, it is available but not highest-priority. `X25519MLKEM768` is a hybrid, post-quantum-secure key exchange algorithm.

**`fips`**  
Restricts the cipher suites used by the agent to only FIPS-approved ciphers.

## Logging
<a name="secrets-manager-agent-log"></a>

**Local logging**  
The Secrets Manager Agent logs errors locally to the file `logs/secrets_manager_agent.log` or to stdout/stderr depending on the `log_to_file` config variable. When your application calls the Secrets Manager Agent to get a secret, those calls appear in the local log. They do not appear in the CloudTrail logs.

**Log rotation**  
The Secrets Manager Agent creates a new log file when the file reaches 10 MB, and it stores up to five log files total.

**AWS service logging**  
The log does not go to Secrets Manager, CloudTrail, or CloudWatch. Requests to get secrets from the Secrets Manager Agent do not appear in those logs. When the Secrets Manager Agent makes a call to Secrets Manager to get a secret, that call is recorded in CloudTrail with a user agent string containing `aws-secrets-manager-agent`.

You can configure logging options in the [Configure the Secrets Manager Agent](#secrets-manager-agent-config).

## Security considerations
<a name="secrets-manager-agent-security"></a>

**Domain of trust**  
For an agent architecture, the domain of trust is where the agent endpoint and SSRF token are accessible, which is usually the entire host. The domain of trust for the Secrets Manager Agent should match the domain where the Secrets Manager credentials are available in order to maintain the same security posture. For example, on Amazon EC2 the domain of trust for the Secrets Manager Agent would be the same as the domain of the credentials when using roles for Amazon EC2.

**Important**  
Security conscious applications that are not already using an agent solution with the Secrets Manager credentials locked down to the application should consider using the language-specific AWS SDKs or caching solutions. For more information, see [Get secrets](https://docs.aws.amazon.com/secretsmanager/latest/userguide/retrieving-secrets.html).

# Get a Secrets Manager secret value using the C\$1\$1 AWS SDK
<a name="retrieving-secrets-cpp"></a>

For C\$1\$1 applications, call the SDK directly with [GetSecretValue](https://docs.aws.amazon.com/goto/SdkForCpp/secretsmanager-2017-10-17/GetSecretValue) or [BatchGetSecretValue](https://docs.aws.amazon.com/goto/SdkForCpp/secretsmanager-2017-10-17/BatchGetSecretValue).

The following code example shows how to get a Secrets Manager secret value.

**Required permissions: **`secretsmanager:GetSecretValue`

```
//! Retrieve an AWS Secrets Manager encrypted secret.
/*!
  \param secretID: The ID for the secret.
  \return bool: Function succeeded.
 */
bool AwsDoc::SecretsManager::getSecretValue(const Aws::String &secretID,
                                            const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::SecretsManager::SecretsManagerClient secretsManagerClient(clientConfiguration);

    Aws::SecretsManager::Model::GetSecretValueRequest request;
    request.SetSecretId(secretID);

    Aws::SecretsManager::Model::GetSecretValueOutcome getSecretValueOutcome = secretsManagerClient.GetSecretValue(
            request);
    if (getSecretValueOutcome.IsSuccess()) {
        std::cout << "Secret is: "
                  << getSecretValueOutcome.GetResult().GetSecretString() << std::endl;
    }
    else {
        std::cerr << "Failed with Error: " << getSecretValueOutcome.GetError()
                  << std::endl;
    }

    return getSecretValueOutcome.IsSuccess();
}
```

# Get a Secrets Manager secret value using the JavaScript AWS SDK
<a name="retrieving-secrets-javascript"></a>

For JavaScript applications, call the SDK directly with [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SecretsManager.html#getSecretValue-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SecretsManager.html#getSecretValue-property) or [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SecretsManager.html#batchGetSecretValue-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SecretsManager.html#batchGetSecretValue-property).

The following code example shows how to get a Secrets Manager secret value.

**Required permissions: **`secretsmanager:GetSecretValue`

```
import {
  GetSecretValueCommand,
  SecretsManagerClient,
} from "@aws-sdk/client-secrets-manager";

export const getSecretValue = async (secretName = "SECRET_NAME") => {
  const client = new SecretsManagerClient();
  const response = await client.send(
    new GetSecretValueCommand({
      SecretId: secretName,
    }),
  );
  console.log(response);
  // {
  //   '$metadata': {
  //     httpStatusCode: 200,
  //     requestId: '584eb612-f8b0-48c9-855e-6d246461b604',
  //     extendedRequestId: undefined,
  //     cfId: undefined,
  //     attempts: 1,
  //     totalRetryDelay: 0
  //   },
  //   ARN: 'arn:aws:secretsmanager:us-east-1:xxxxxxxxxxxx:secret:binary-secret-3873048-xxxxxx',
  //   CreatedDate: 2023-08-08T19:29:51.294Z,
  //   Name: 'binary-secret-3873048',
  //   SecretBinary: Uint8Array(11) [
  //      98, 105, 110, 97, 114,
  //     121,  32, 100, 97, 116,
  //      97
  //   ],
  //   VersionId: '712083f4-0d26-415e-8044-16735142cd6a',
  //   VersionStages: [ 'AWSCURRENT' ]
  // }

  if (response.SecretString) {
    return response.SecretString;
  }

  if (response.SecretBinary) {
    return response.SecretBinary;
  }
};
```

# Get a Secrets Manager secret value using the Kotlin AWS SDK
<a name="retrieving-secrets-kotlin"></a>

For Kotlin applications, call the SDK directly with [GetSecretValue](https://github.com/awslabs/aws-sdk-kotlin#generating-api-documentation) or [BatchGetSecretValue](https://github.com/awslabs/aws-sdk-kotlin#generating-api-documentation).

The following code example shows how to get a Secrets Manager secret value.

**Required permissions: **`secretsmanager:GetSecretValue`

```
suspend fun getValue(secretName: String?) {
    val valueRequest =
        GetSecretValueRequest {
            secretId = secretName
        }

    SecretsManagerClient.fromEnvironment { region = "us-east-1" }.use { secretsClient ->
        val response = secretsClient.getSecretValue(valueRequest)
        val secret = response.secretString
        println("The secret value is $secret")
    }
}
```

# Get a Secrets Manager secret value using the PHP AWS SDK
<a name="retrieving-secrets-php"></a>

For PHP applications, call the SDK directly with [https://docs.aws.amazon.com//aws-sdk-php/v3/api/api-secretsmanager-2017-10-17.html#getsecretvalue](https://docs.aws.amazon.com//aws-sdk-php/v3/api/api-secretsmanager-2017-10-17.html#getsecretvalue) or [https://docs.aws.amazon.com//aws-sdk-php/v3/api/api-secretsmanager-2017-10-17.html#batchGetsecretvalue](https://docs.aws.amazon.com//aws-sdk-php/v3/api/api-secretsmanager-2017-10-17.html#batchGetsecretvalue).

The following code example shows how to get a Secrets Manager secret value.

**Required permissions: **`secretsmanager:GetSecretValue`

```
<?php

  /**
    * Use this code snippet in your app.
    *
    * If you need more information about configurations or implementing the sample code, visit the AWS docs:
    * https://aws.amazon.com/developer/language/php/
    */
  
  require 'vendor/autoload.php';
  
  use Aws\SecretsManager\SecretsManagerClient;
  use Aws\Exception\AwsException;
  
  /**
    * This code expects that you have AWS credentials set up per:
    * https://<<{{DocsDomain}}>>/sdk-for-php/v3/developer-guide/guide_credentials.html
    */
  
  // Create a Secrets Manager Client
  $client = new SecretsManagerClient([
      'profile' => 'default',
      'version' => '2017-10-17',
      'region' => '<<{{MyRegionName}}>>',
  ]);
  
  $secret_name = '<<{{MySecretName}}>>';
  
  try {
      $result = $client->getSecretValue([
          'SecretId' => $secret_name,
      ]);
  } catch (AwsException $e) {
      // For a list of exceptions thrown, see
      // https://<<{{DocsDomain}}>>/secretsmanager/latest/apireference/API_GetSecretValue.html
      throw $e;
  }
  
  // Decrypts secret using the associated KMS key.
  $secret = $result['SecretString'];
  
  // Your code goes here
```

# Get a Secrets Manager secret value using the Ruby AWS SDK
<a name="retrieving-secrets-ruby"></a>

For Ruby applications, call the SDK directly with [https://docs.aws.amazon.com/sdk-for-ruby/v3/api/Aws/SecretsManager/Client.html#get_secret_value-instance_method](https://docs.aws.amazon.com/sdk-for-ruby/v3/api/Aws/SecretsManager/Client.html#get_secret_value-instance_method) or [https://docs.aws.amazon.com/sdk-for-ruby/v3/api/Aws/SecretsManager/Client.html#batch_get_secret_value-instance_method](https://docs.aws.amazon.com/sdk-for-ruby/v3/api/Aws/SecretsManager/Client.html#batch_get_secret_value-instance_method).

The following code example shows how to get a Secrets Manager secret value.

**Required permissions: **`secretsmanager:GetSecretValue`

```
  # Use this code snippet in your app.
  # If you need more information about configurations or implementing the sample code, visit the AWS docs:
  # https://aws.amazon.com/developer/language/ruby/
  
  require 'aws-sdk-secretsmanager'
  
  def get_secret
    client = Aws::SecretsManager::Client.new(region: '<<{{MyRegionName}}>>')
  
    begin
      get_secret_value_response = client.get_secret_value(secret_id: '<<{{MySecretName}}>>')
    rescue StandardError => e
      # For a list of exceptions thrown, see
      # https://<<{{DocsDomain}}>>/secretsmanager/latest/apireference/API_GetSecretValue.html
      raise e
    end
  
    secret = get_secret_value_response.secret_string
    # Your code goes here.
  end
```

# Get a secret value using the AWS CLI
<a name="retrieving-secrets_cli"></a>

**Required permissions: **`secretsmanager:GetSecretValue`

**Example Retrieve the encrypted secret value of a secret**  
The following [https://docs.aws.amazon.com//cli/latest/reference/secretsmanager/get-secret-value.html](https://docs.aws.amazon.com//cli/latest/reference/secretsmanager/get-secret-value.html) example gets the current secret value.  

```
aws secretsmanager get-secret-value \
    --secret-id MyTestSecret
```

**Example Retrieve the previous secret value**  
The following [https://docs.aws.amazon.com//cli/latest/reference/secretsmanager/get-secret-value.html](https://docs.aws.amazon.com//cli/latest/reference/secretsmanager/get-secret-value.html) example gets the previous secret value.  

```
aws secretsmanager get-secret-value \
        --secret-id MyTestSecret
        --version-stage AWSPREVIOUS
```

## Get a group of secrets in a batch using the AWS CLI
<a name="retrieving-secrets-cli-batch"></a>

**Required permissions: **
+ `secretsmanager:BatchGetSecretValue` 
+ `secretsmanager:GetSecretValue` permission for each secret you want to retrieve.
+ If you use filters, you must also have `secretsmanager:ListSecrets`. 

For an example permissions policy, see [Example: Permission to retrieve a group of secret values in a batch](auth-and-access_iam-policies.md#auth-and-access_examples_batch).

**Important**  
If you have a VPCE policy that denies permission to retrieve an individual secret in the group you are retrieving, `BatchGetSecretValue` will not return any secret values, and it will return an error.

**Example Retrieve the secret value for a group of secrets listed by name**  
The following [https://docs.aws.amazon.com//cli/latest/reference/secretsmanager/batch-get-secret-value.html](https://docs.aws.amazon.com//cli/latest/reference/secretsmanager/batch-get-secret-value.html) example gets the secret value for three secrets.  

```
aws secretsmanager batch-get-secret-value \
          --secret-id-list MySecret1 MySecret2 MySecret3
```

**Example Retrieve the secret value for a group of secrets selected by filter**  
The following [https://docs.aws.amazon.com//cli/latest/reference/secretsmanager/batch-get-secret-value.html](https://docs.aws.amazon.com//cli/latest/reference/secretsmanager/batch-get-secret-value.html) example gets the secret value for the secrets that have a tag named "Test".  

```
aws secretsmanager batch-get-secret-value \
          --filters Key="tag-key",Values="Test"
```

# Get a secret value using the AWS console
<a name="retrieving-secrets-console"></a>

**To retrieve a secret (console)**

1. Open the Secrets Manager console at [https://console.aws.amazon.com/secretsmanager/](https://console.aws.amazon.com/secretsmanager/).

1. In the list of secrets, choose the secret you want to retrieve.

1. In the **Secret value** section, choose **Retrieve secret value**.

   Secrets Manager displays the current version (`AWSCURRENT`) of the secret. To see [other versions](whats-in-a-secret.md#term_version) of the secret, such as `AWSPREVIOUS` or custom labeled versions, use the [Get a secret value using the AWS CLI](retrieving-secrets_cli.md).

# Use AWS Secrets Manager secrets in AWS Batch
<a name="integrating_BATCH"></a>

AWS Batch helps you to run batch computing workloads on the AWS Cloud. With AWS Batch, you can inject sensitive data into your jobs by storing your sensitive data in AWS Secrets Manager secrets and then referencing them in your job definition. For more information, see [Specifying sensitive data using Secrets Manager](https://docs.aws.amazon.com/batch/latest/userguide/specifying-sensitive-data-secrets.html).

# Get an AWS Secrets Manager secret in an CloudFormation resource
<a name="cfn-example_reference-secret"></a>

With CloudFormation, you can retrieve a secret to use in another CloudFormation resource. A common scenario is to first create a secret with a password generated by Secrets Manager, and then retrieve the username and password from the secret to use as credentials for a new database. For information about creating secrets with CloudFormation, see [Create AWS Secrets Manager secrets in AWS CloudFormation](cloudformation.md).

To retrieve a secret in an CloudFormation template, you use a *dynamic reference*. When you create the stack, the dynamic reference pulls the secret value into the CloudFormation resource, so you don't have to hardcode the secret information. Instead, you refer to the secret by name or ARN. You can use a dynamic reference for a secret in any resource property. You can't use a dynamic reference for a secret in resource metadata such as [https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-init.html](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-init.html) because that would make the secret value visible in the console.

A dynamic reference for a secret has the following pattern:

```
{{resolve:secretsmanager:secret-id:SecretString:json-key:version-stage:version-id}}
```

**secret-id**  
The name or ARN of the secret. To access a secret in your AWS account, you can use the secret name. To access a secret in a different AWS account, use the ARN of the secret.

**json-key** (Optional)  
The key name of the key-value pair whose value you want to retrieve. If you don't specify a `json-key`, CloudFormation retrieves the entire secret text. This segment may not include the colon character ( `:`).

**version-stage** (Optional)  
The [version](whats-in-a-secret.md#term_version) of the secret to use. Secrets Manager uses staging labels to keep track of different versions during the rotation process. If you use `version-stage` then don't specify `version-id`. If you don't specify either `version-stage` or `version-id`, then the default is the `AWSCURRENT` version. This segment may not include the colon character ( `:`).

**version-id** (Optional)  
The unique identifier of the version of the secret to use. If you specify `version-id`, then don't specify `version-stage`. If you don't specify either `version-stage` or `version-id`, then the default is the `AWSCURRENT` version. This segment may not include the colon character ( `:`).

For more information, see [Using dynamic references to specify Secrets Manager secrets](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/dynamic-references.html#dynamic-references-secretsmanager).

**Note**  
Do not create a dynamic reference using a backslash `(\)` as the final value. CloudFormation can't resolve those references, which causes a resource failure.

# Use AWS Secrets Manager secrets in GitHub jobs
<a name="retrieving-secrets_github"></a>

To use a secret in a GitHub job, you can use a GitHub action to retrieve secrets from AWS Secrets Manager and add them as masked [Environment variables](https://docs.github.com/en/actions/learn-github-actions/environment-variables) in your GitHub workflow. For more information about GitHub Actions, see [Understanding GitHub Actions](https://docs.github.com/en/actions/learn-github-actions/understanding-github-actions) in the *GitHub Docs*.

When you add a secret to your GitHub environment, it is available to all other steps in your GitHub job. Follow the guidance in [Security hardening for GitHub Actions](https://docs.github.com/en/actions/security-guides/security-hardening-for-github-actions) to help prevent secrets in your environment from being misused.

You can set the entire string in the secret value as the environment variable value, or if the string is JSON, you can parse the JSON to set individual environment variables for each JSON key-value pair. If the secret value is a binary, the action converts it to a string.

To view the environment variables created from your secrets, turn on debug logging. For more information, see [Enabling debug logging](https://docs.github.com/en/actions/monitoring-and-troubleshooting-workflows/enabling-debug-logging) in the *GitHub Docs*.

To use the environment variables created from your secrets, see [Environment variables](https://docs.github.com/en/actions/learn-github-actions/environment-variables) in the *GitHub Docs*.

## Prerequisites
<a name="retrieving-secrets_github_prereq"></a>

To use this action, you first need to configure AWS credentials and set the AWS Region in your GitHub environment by using the `configure-aws-credentials` step. Follow the instructions in [Configure AWS Credentials Action For GitHub Actions](https://github.com/aws-actions/configure-aws-credentials) to **Assume role directly using GitHub OIDC provider**. This allows you to use short-lived credentials and avoid storing additional access keys outside of Secrets Manager.

The IAM role the action assumes must have the following permissions:
+ `GetSecretValue` on the secrets you want to retrieve.
+ `ListSecrets` on all secrets.
+ (Optional) `Decrypt` on the KMS key if the secrets are encrypted with a customer managed key.

For more information, see [Authentication and access control for AWS Secrets Manager](auth-and-access.md).

## Usage
<a name="retrieving-secrets_github_usage"></a>

To use the action, add a step to your workflow that uses the following syntax.

```
- name: Step name
  uses: aws-actions/aws-secretsmanager-get-secrets@v2
  with:
    secret-ids: |
      secretId1
      ENV_VAR_NAME, secretId2
    name-transformation: (Optional) uppercase|lowercase|none
    parse-json-secrets: (Optional) true|false
```Parameters

`secret-ids`  
Secret ARNS, names, and name prefixes.  
To set the environment variable name, enter it before the secret ID, followed by a comma. For example `ENV_VAR_1, secretId` creates an environment variable named **ENV\$1VAR\$11** from the secret `secretId`. The environment variable name can consist of uppercase letters, numbers, and underscores.  
To use a prefix, enter at least three characters followed by an asterisk. For example `dev*` matches all secrets with a name beginning in **dev**. The maximum number of matching secrets that can be retrieved is 100. If you set the variable name, and the prefix matches multiple secrets, then the action fails.

`name-transformation`  
By default, the step creates each environment variable name from the secret name, transformed to include only uppercase letters, numbers, and underscores, and so that it doesn't begin with a number. For the letters in the name, you can configure the step to use lowercase letters with `lowercase` or to not change the case of the letters with `none`. The default value is `uppercase`.

`parse-json-secrets`  
(Optional) By default, the action sets the environment variable value to the entire JSON string in the secret value. Set `parse-json-secrets` to `true` to create environment variables for each key-value pair in the JSON.   
Note that if the JSON uses case-sensitive keys such as "name" and "Name", the action will have duplicate name conflicts. In this case, set `parse-json-secrets` to `false` and parse the JSON secret value separately. 

## Environment variable naming
<a name="retrieving-secrets_github_alias"></a>

The environment variables created by the action are named the same as the secrets that they come from. Environment variables have stricter naming requirements than secrets, so the action transforms secret names to meet those requirements. For example, the action transforms lowercase letters to uppercase letters. If you parse the JSON of the secret, then the environment variable name includes both the secret name and the JSON key name, for example `MYSECRET_KEYNAME`. You can configure the action to not transform lowercase letters.

If two environment variables would end up with the same name, the action fails. In this case, you must specify the names you want to use for the environment variables as *aliases*.

Examples of when the names might conflict:
+ A secret named "MySecret" and a secret named "mysecret" would both become environment variables named "MYSECRET".
+ A secret named "Secret\$1keyname" and a JSON-parsed secret named "Secret" with a key named "keyname" would both become environment variables named "SECRET\$1KEYNAME".

You can set the environment variable name by specifying an *alias*, as shown in the following example, which creates a variable named `ENV_VAR_NAME`.

```
secret-ids: |
  ENV_VAR_NAME, secretId2
```

**Blank aliases**
+ If you set `parse-json-secrets: true` and enter a blank alias, followed by a comma and then the secret ID, the action names the environment variable the same as the parsed JSON keys. The variable names do not include the secret name. 

  If the secret doesn't contain valid JSON, then the action creates one environment variable and names it the same as the secret name.
+ If you set `parse-json-secrets: false` and enter a blank alias, followed by a comma and the secret ID, the action names the environment variables as if you did not specify an alias.

The following example shows a blank alias.

```
,secret2
```

## Examples
<a name="retrieving-secrets_github_examples"></a>

**Example 1 Get secrets by name and by ARN**  
The following example creates environment variables for secrets identified by name and by ARN.  

```
- name: Get secrets by name and by ARN
  uses: aws-actions/aws-secretsmanager-get-secrets@v2
  with:
    secret-ids: |
      exampleSecretName
      arn:aws:secretsmanager:us-east-2:123456789012:secret:test1-a1b2c3
      0/test/secret
      /prod/example/secret
      SECRET_ALIAS_1,test/secret
      SECRET_ALIAS_2,arn:aws:secretsmanager:us-east-2:123456789012:secret:test2-a1b2c3
      ,secret2
```
Environment variables created:  

```
EXAMPLESECRETNAME: secretValue1
TEST1: secretValue2
_0_TEST_SECRET: secretValue3
_PROD_EXAMPLE_SECRET: secretValue4
SECRET_ALIAS_1: secretValue5
SECRET_ALIAS_2: secretValue6
SECRET2: secretValue7
```

**Example 2 Get all secrets that begin with a prefix**  
The following example creates environment variables for all secrets with names that begin with *beta*.  

```
- name: Get Secret Names by Prefix
  uses: 2
  with:
    secret-ids: |
      beta*    # Retrieves all secrets that start with 'beta'
```
Environment variables created:  

```
BETASECRETNAME: secretValue1
BETATEST: secretValue2
BETA_NEWSECRET: secretValue3
```

**Example 3 Parse JSON in secret**  
The following example creates environment variables by parsing the JSON in the secret.  

```
- name: Get Secrets by Name and by ARN
  uses: aws-actions/aws-secretsmanager-get-secrets@v2
  with:
    secret-ids: |
      test/secret
      ,secret2
    parse-json-secrets: true
```
The secret `test/secret` has the following secret value.  

```
{
  "api_user": "user",
  "api_key": "key",
  "config": {
    "active": "true"
  }
}
```
The secret `secret2` has the following secret value.  

```
{
  "myusername": "alejandro_rosalez",
  "mypassword": "EXAMPLE_PASSWORD"
}
```
Environment variables created:  

```
TEST_SECRET_API_USER: "user"
TEST_SECRET_API_KEY: "key"
TEST_SECRET_CONFIG_ACTIVE: "true"
MYUSERNAME: "alejandro_rosalez"
MYPASSWORD: "EXAMPLE_PASSWORD"
```

**Example 4 Use lowercase letters for environment variable names**  
The following example creates an environment variable with a lowercase name.  

```
- name: Get secrets
  uses: aws-actions/aws-secretsmanager-get-secrets@v2
  with:
    secret-ids: exampleSecretName
    name-transformation: lowercase
```
Environment variable created:  

```
examplesecretname: secretValue
```

# Use AWS Secrets Manager in GitLab
<a name="integrating_gitlab"></a>

AWS Secrets Manager integrates with GitLab. You can leverage Secrets Manager secrets to protect your GitLab credentials so they are no longer hardcoded in GitLab. Instead, [GitLab Runner](https://docs.gitlab.com/runner/) retrieves these secrets from Secrets Manager when your application runs a job in the GitLab CI/CD pipelines.

To use this integration, you'll create an [OpenID Connect (OIDC) identity provider in IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_oidc.html) AWS Identity and Access Management and an IAM role. This allows GitLab Runner to access your Secrets Manager secret. For more information about GitLab CI/CD and OIDC, see [GitLab documentation](https://docs.gitlab.com/ci/cloud_services/aws/).

## Considerations
<a name="gitlab-integration-considerations"></a>

If you're using a non-public GitLab instance, you cannot use this Secrets Manager integration. Instead, see [GitLab documentation for non-public instances](https://docs.gitlab.com/ci/cloud_services/aws/#configure-a-non-public-gitlab-instance).

## Prerequisites
<a name="gitlab-integration-prerequisites"></a>

To integrate Secrets Manager with GitLab, complete the following prerequisites:

1. 

**Create an AWS Secrets Manager secret**

   You'll need an Secrets Manager secret which will be retrieved in your GitLab job and removes the need to hard-code these credentials. You'll need the Secrets Manager secret ID when you [configure your GitLab pipeline](#configure-gitlab-pipeline). See [Create an AWS Secrets Manager secret](create_secret.md) for more information.

1. 

**Make GitLab your OIDC provider in the IAM console.**

   In this step, you’ll make GitLab your OIDC provider in the IAM console. For more information, see [Create an OpenID Connect (OIDC) identity provider](https://docs.aws.amazon.com//IAM/latest/UserGuide/id_roles_providers_create_oidc.html) and [GitLab documentation](https://docs.gitlab.com/ci/cloud_services/aws/).

   When creating the OIDC provider in the IAM console, use the following configurations:

   1. <a name="step2-oidc-provider"></a>Set the `provider URL` to your GitLab instance. For example, **gitlab.example.com**.

   1. <a name="step2-oidc-audience"></a>Set the `audience` or `aud` to **sts.amazonaws.com**.

1. 

**Create an IAM role and policy**

   You'll need to create an IAM role and policy. This role is assumed by GitLab with [AWS Security Token Service (STS)](https://docs.aws.amazon.com/STS/latest/APIReference/welcome.html). See [Create a role using custom trust policies](https://docs.aws.amazon.com//IAM/latest/UserGuide/id_roles_create_for-custom.html) for more information.

   1. In the IAM console, use the following settings when creating the IAM role:
      + Set `Trusted entity type` to **Web identity**.
      + Set `Group` to **your GitLab group**.
      + Set `Identity provider` to the same provider URL (the [GitLab instance](#step2-oidc-provider)) you used in step 2.
      + Set `Audience` to the same [audience](#step2-oidc-audience) you used in step 2.

   1. The following is an example of a trust policy that allows GitLab to assume roles. Your trust policy should list your AWS account, GitLab URL, and [project path](https://docs.gitlab.com/user/project/).  
****  

      ```
      {
        "Version":"2012-10-17",		 	 	 
        "Statement": [
          {
            "Effect": "Allow",
            "Action": "sts:AssumeRoleWithWebIdentity",
            "Principal": {
              "Federated": "arn:aws:iam::111122223333:oidc-provider/gitlab.example.com"
            },
            "Condition": {
              "StringEquals": {
                "gitlab.example.com:aud": [
                  "sts.amazon.com"
                ]
              },
              "StringLike": {
                "gitlab.example.com:sub": [
                  "project_path:mygroup/project-*:ref_type:branch-*:ref:main*"
                ]
              }
            }
          }
        ]
      }
      ```

   1. You'll also need to create an IAM policy to allow GitLab access to AWS Secrets Manager. You can add this policy to your trust policy. For more information, see [Create IAM policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_create-console.html).  
****  

      ```
      {
        "Version":"2012-10-17",		 	 	 
        "Statement": [
          {
            "Effect": "Allow",
            "Action": "secretsmanager:GetSecretValue",
            "Resource": "arn:aws:secretsmanager:us-east-1:111122223333:secret:your-secret"
          }
        ]
      }
      ```

## Integrating AWS Secrets Manager with GitLab
<a name="integrating-aws-secrets-manager-gitlab"></a>

After completing the prerequisites, you can configure GitLab to use Secrets Manager to protect your credentials.

### Configure GitLab pipeline to use Secrets Manager
<a name="configure-gitlab-pipeline"></a>

You'll need to update your [GitLab CI/CD configuration file](https://docs.gitlab.com/ci/yaml/yaml_optimization/) with the following information:
+ The audience of the token set to STS.
+ The Secrets Manager secret ID.
+ The IAM role you want GitLab Runner to assume when executing jobs in the GitLab pipeline.
+ The AWS Region where the secret is stored.

GitLab fetches the secret from Secrets Manager and stores the value in a temporary file. The path to this file is stored in a CI/CD variable, similar to [file type CI/CD variables](https://docs.gitlab.com/ci/variables/#use-file-type-cicd-variables).

The following is a snippet of the YAML file for a GitLab CI/CD configuration file:

```
variables:
  AWS_REGION: us-east-1
  AWS_ROLE_ARN: 'arn:aws:iam::111122223333:role/gitlab-role'
job:
  id_tokens:
    AWS_ID_TOKEN:
      aud: 'sts.amazonaws.com'
  secrets:
    DATABASE_PASSWORD:
      aws_secrets_manager:
        secret_id: "arn:aws:secretsmanager:us-east-1:111122223333:secret:secret-name"
```

For more information, see [GitLab Secrets Manager integration documentation](https://docs.gitlab.com/ci/secrets/aws_secrets_manager/).

Optionally, you can test your OIDC configuration in GitLab. See [GitLab documentation for testing OIDC configuration](https://docs.gitlab.com/ci/cloud_services/aws/#test-the-oidc-configuration) for more information.

## Troubleshooting
<a name="troubleshooting-integration"></a>

The following can help you troubleshoot common issues you might encounter when integrating Secrets Manager with GitLab.

### GitLab Pipeline issues
<a name="gitlab-pipeline-issues"></a>

If you experience GitLab pipeline issues, ensure the following:
+ Your YAML file is properly formatted. For more information, see [GitLab documentation](https://docs.gitlab.com/ee/ci/yaml/).
+ Your GitLab pipeline is assuming the correct role, has the appropriate permissions, and access to the correct AWS Secrets Manager secret.

### Additional resources
<a name="additional-resources"></a>

The following resources can help you troubleshoot issues with GitLab and AWS Secrets Manager:
+ [GitLab OIDC troubleshooting](https://docs.gitlab.com/ci/cloud_services/aws/#troubleshooting)
+ [Debugging GitLab CI/CD Pipeline](https://docs.gitlab.com/ee/ci/troubleshooting.html)
+ [Troubleshooting](ascp-eks-installation.md#troubleshooting)

# Use AWS Secrets Manager secrets in AWS IoT Greengrass
<a name="integrating-greengrass"></a>

AWS IoT Greengrass is software that extends cloud capabilities to local devices. This enables devices to collect and analyze data closer to the source of information, react autonomously to local events, and communicate securely with each other on local networks. 

AWS IoT Greengrass lets you authenticate with services and applications from AWS IoT Greengrass devices without hard-coding passwords, tokens, or other secrets. You can use AWS Secrets Manager to securely store and manage your secrets in the cloud. AWS IoT Greengrass extends Secrets Manager to AWS IoT Greengrass core devices, so your connectors and Lambda functions can use local secrets to interact with services and applications. 

To integrate a secret into a AWS IoT Greengrass group, you create a group resource that references the Secrets Manager secret. This secret resource references the cloud secret by using the associated ARN. To learn how to create, manage, and use secret resources, see [Working with Secret Resources](https://docs.aws.amazon.com/greengrass/latest/developerguide/secrets-using.html) in the AWS IoT Developer Guide. 

To deploy secrets to the AWS IoT Greengrass Core, see [Deploy secrets to the AWS IoT Greengrass core.](https://docs.aws.amazon.com/greengrass/latest/developerguide/secrets.html)

# Use AWS Secrets Manager secrets in Parameter Store
<a name="integrating_parameterstore"></a>

AWS Systems Manager Parameter Store provides secure, hierarchical storage for configuration data management and secrets management. You can store data such as passwords, database strings, and license codes as parameter values. However, Parameter Store doesn't provide automatic rotation services for stored secrets. Instead, Parameter Store enables you to store your secret in Secrets Manager, and then reference the secret as a Parameter Store parameter.

When you configure Parameter Store with Secrets Manager, the `secret-id` Parameter Store requires a forward slash (/) before the name-string. 

For more information, see [Referencing AWS Secrets Manager Secrets from Parameter Store Parameters](https://docs.aws.amazon.com/systems-manager/latest/userguide/integration-ps-secretsmanager.html) in the *AWS Systems Manager User Guide*.