SecretsManager

Table of Contents

Client

class SecretsManager.Client

A low-level client representing AWS Secrets Manager

Amazon Web Services Secrets Manager provides a service to enable you to store, manage, and retrieve, secrets.

This guide provides descriptions of the Secrets Manager API. For more information about using this service, see the Amazon Web Services Secrets Manager User Guide .

API Version

This version of the Secrets Manager API Reference documents the Secrets Manager API version 2017-10-17.

Note

As an alternative to using the API, you can use one of the Amazon Web Services SDKs, which consist of libraries and sample code for various programming languages and platforms such as Java, Ruby, .NET, iOS, and Android. The SDKs provide a convenient way to create programmatic access to Amazon Web Services Secrets Manager. For example, the SDKs provide cryptographically signing requests, managing errors, and retrying requests automatically. For more information about the Amazon Web Services SDKs, including downloading and installing them, see Tools for Amazon Web Services .

We recommend you use the Amazon Web Services SDKs to make programmatic API calls to Secrets Manager. However, you also can use the Secrets Manager HTTP Query API to make direct calls to the Secrets Manager web service. To learn more about the Secrets Manager HTTP Query API, see Making Query Requests in the Amazon Web Services Secrets Manager User Guide .

Secrets Manager API supports GET and POST requests for all actions, and doesn't require you to use GET for some actions and POST for others. However, GET requests are subject to the limitation size of a URL. Therefore, for operations that require larger sizes, use a POST request.

Support and Feedback for Amazon Web Services Secrets Manager

We welcome your feedback. Send your comments to awssecretsmanager-feedback@amazon.com , or post your feedback and questions in the Amazon Web Services Secrets Manager Discussion Forum . For more information about the Amazon Web Services Discussion Forums, see Forums Help .

How examples are presented

The JSON that Amazon Web Services Secrets Manager expects as your request parameters and the service returns as a response to HTTP query requests contain single, long strings without line breaks or white space formatting. The JSON shown in the examples displays the code formatted with both line breaks and white space to improve readability. When example input parameters can also cause long strings extending beyond the screen, you can insert line breaks to enhance readability. You should always submit the input as a single JSON text string.

Logging API Requests

Amazon Web Services Secrets Manager supports Amazon Web Services CloudTrail, a service that records Amazon Web Services API calls for your Amazon Web Services account and delivers log files to an Amazon S3 bucket. By using information that's collected by Amazon Web Services CloudTrail, you can determine the requests successfully made to Secrets Manager, who made the request, when it was made, and so on. For more about Amazon Web Services Secrets Manager and support for Amazon Web Services CloudTrail, see Logging Amazon Web Services Secrets Manager Events with Amazon Web Services CloudTrail in the Amazon Web Services Secrets Manager User Guide . To learn more about CloudTrail, including enabling it and find your log files, see the Amazon Web Services CloudTrail User Guide .

import boto3

client = boto3.client('secretsmanager')

These are the available methods:

can_paginate(operation_name)

Check if an operation can be paginated.

Parameters
operation_name (string) -- The operation name. This is the same name as the method name on the client. For example, if the method name is create_foo, and you'd normally invoke the operation as client.create_foo(**kwargs), if the create_foo operation can be paginated, you can use the call client.get_paginator("create_foo").
Returns
True if the operation can be paginated, False otherwise.
cancel_rotate_secret(**kwargs)

Disables automatic scheduled rotation and cancels the rotation of a secret if currently in progress.

To re-enable scheduled rotation, call RotateSecret with AutomaticallyRotateAfterDays set to a value greater than 0. This immediately rotates your secret and then enables the automatic schedule.

Note

If you cancel a rotation while in progress, it can leave the VersionStage labels in an unexpected state. Depending on the step of the rotation in progress, you might need to remove the staging label AWSPENDING from the partially created version, specified by the VersionId response value. You should also evaluate the partially rotated new version to see if it should be deleted, which you can do by removing all staging labels from the new version VersionStage field.

To successfully start a rotation, the staging label AWSPENDING must be in one of the following states:

  • Not attached to any version at all
  • Attached to the same version as the staging label AWSCURRENT

If the staging label AWSPENDING attached to a different version than the version with AWSCURRENT then the attempt to rotate fails.

Minimum permissions

To run this command, you must have the following permissions:

  • secretsmanager:CancelRotateSecret
Related operations
  • To configure rotation for a secret or to manually trigger a rotation, use RotateSecret .
  • To get the rotation configuration details for a secret, use DescribeSecret .
  • To list all of the currently available secrets, use ListSecrets .
  • To list all of the versions currently associated with a secret, use ListSecretVersionIds .

See also: AWS API Documentation

Request Syntax

response = client.cancel_rotate_secret(
    SecretId='string'
)
Parameters
SecretId (string) --

[REQUIRED]

Specifies the secret to cancel a rotation request. You can specify either the Amazon Resource Name (ARN) or the friendly name of the secret.

For an ARN, we recommend that you specify a complete ARN rather than a partial ARN.

Return type
dict
Returns
Response Syntax
{
    'ARN': 'string',
    'Name': 'string',
    'VersionId': 'string'
}

Response Structure

  • (dict) --
    • ARN (string) --

      The ARN of the secret for which rotation was canceled.

    • Name (string) --

      The friendly name of the secret for which rotation was canceled.

    • VersionId (string) --

      The unique identifier of the version of the secret created during the rotation. This version might not be complete, and should be evaluated for possible deletion. At the very least, you should remove the VersionStage value AWSPENDING to enable this version to be deleted. Failing to clean up a cancelled rotation can block you from successfully starting future rotations.

Exceptions

  • SecretsManager.Client.exceptions.ResourceNotFoundException
  • SecretsManager.Client.exceptions.InvalidParameterException
  • SecretsManager.Client.exceptions.InternalServiceError
  • SecretsManager.Client.exceptions.InvalidRequestException

Examples

The following example shows how to cancel rotation for a secret. The operation sets the RotationEnabled field to false and cancels all scheduled rotations. To resume scheduled rotations, you must re-enable rotation by calling the rotate-secret operation.

response = client.cancel_rotate_secret(
    SecretId='MyTestDatabaseSecret',
)

print(response)

Expected Output:

{
    'ARN': 'arn:aws:secretsmanager:us-west-2:123456789012:secret:MyTestDatabaseSecret-a1b2c3',
    'Name': 'Name',
    'ResponseMetadata': {
        '...': '...',
    },
}
create_secret(**kwargs)

Creates a new secret. A secret in Secrets Manager consists of both the protected secret data and the important information needed to manage the secret.

Secrets Manager stores the encrypted secret data in one of a collection of "versions" associated with the secret. Each version contains a copy of the encrypted secret data. Each version is associated with one or more "staging labels" that identify where the version is in the rotation cycle. The SecretVersionsToStages field of the secret contains the mapping of staging labels to the active versions of the secret. Versions without a staging label are considered deprecated and not included in the list.

You provide the secret data to be encrypted by putting text in either the SecretString parameter or binary data in the SecretBinary parameter, but not both. If you include SecretString or SecretBinary then Secrets Manager also creates an initial secret version and automatically attaches the staging label AWSCURRENT to the new version.

Note

  • If you call an operation to encrypt or decrypt the SecretString or SecretBinary for a secret in the same account as the calling user and that secret doesn't specify a Amazon Web Services KMS encryption key, Secrets Manager uses the account's default Amazon Web Services managed customer master key (CMK) with the alias aws/secretsmanager . If this key doesn't already exist in your account then Secrets Manager creates it for you automatically. All users and roles in the same Amazon Web Services account automatically have access to use the default CMK. Note that if an Secrets Manager API call results in Amazon Web Services creating the account's Amazon Web Services-managed CMK, it can result in a one-time significant delay in returning the result.
  • If the secret resides in a different Amazon Web Services account from the credentials calling an API that requires encryption or decryption of the secret value then you must create and use a custom Amazon Web Services KMS CMK because you can't access the default CMK for the account using credentials from a different Amazon Web Services account. Store the ARN of the CMK in the secret when you create the secret or when you update it by including it in the KMSKeyId . If you call an API that must encrypt or decrypt SecretString or SecretBinary using credentials from a different account then the Amazon Web Services KMS key policy must grant cross-account access to that other account's user or role for both the kms:GenerateDataKey and kms:Decrypt operations.

Minimum permissions

To run this command, you must have the following permissions:

  • secretsmanager:CreateSecret
  • kms:GenerateDataKey - needed only if you use a customer-managed Amazon Web Services KMS key to encrypt the secret. You do not need this permission to use the account default Amazon Web Services managed CMK for Secrets Manager.
  • kms:Decrypt - needed only if you use a customer-managed Amazon Web Services KMS key to encrypt the secret. You do not need this permission to use the account default Amazon Web Services managed CMK for Secrets Manager.
  • secretsmanager:TagResource - needed only if you include the Tags parameter.
Related operations
  • To delete a secret, use DeleteSecret .
  • To modify an existing secret, use UpdateSecret .
  • To create a new version of a secret, use PutSecretValue .
  • To retrieve the encrypted secure string and secure binary values, use GetSecretValue .
  • To retrieve all other details for a secret, use DescribeSecret . This does not include the encrypted secure string and secure binary values.
  • To retrieve the list of secret versions associated with the current secret, use DescribeSecret and examine the SecretVersionsToStages response value.

See also: AWS API Documentation

Request Syntax

response = client.create_secret(
    Name='string',
    ClientRequestToken='string',
    Description='string',
    KmsKeyId='string',
    SecretBinary=b'bytes',
    SecretString='string',
    Tags=[
        {
            'Key': 'string',
            'Value': 'string'
        },
    ],
    AddReplicaRegions=[
        {
            'Region': 'string',
            'KmsKeyId': 'string'
        },
    ],
    ForceOverwriteReplicaSecret=True|False
)
Parameters
  • Name (string) --

    [REQUIRED]

    Specifies the friendly name of the new secret.

    The secret name must be ASCII letters, digits, or the following characters : /_+=.@-

    Note

    Do not end your secret name with a hyphen followed by six characters. If you do so, you risk confusion and unexpected results when searching for a secret by partial ARN. Secrets Manager automatically adds a hyphen and six random characters at the end of the ARN.

  • ClientRequestToken (string) --

    (Optional) If you include SecretString or SecretBinary , then an initial version is created as part of the secret, and this parameter specifies a unique identifier for the new version.

    Note

    If you use the Amazon Web Services CLI or one of the Amazon Web Services SDK to call this operation, then you can leave this parameter empty. The CLI or SDK generates a random UUID for you and includes it as the value for this parameter in the request. If you don't use the SDK and instead generate a raw HTTP request to the Secrets Manager service endpoint, then you must generate a ClientRequestToken yourself for the new version and include the value in the request.

    This value helps ensure idempotency. Secrets Manager uses this value to prevent the accidental creation of duplicate versions if there are failures and retries during a rotation. We recommend that you generate a UUID-type value to ensure uniqueness of your versions within the specified secret.

    • If the ClientRequestToken value isn't already associated with a version of the secret then a new version of the secret is created.
    • If a version with this value already exists and the version SecretString and SecretBinary values are the same as those in the request, then the request is ignored.
    • If a version with this value already exists and that version's SecretString and SecretBinary values are different from those in the request, then the request fails because you cannot modify an existing version. Instead, use PutSecretValue to create a new version.

    This value becomes the VersionId of the new version.

    This field is autopopulated if not provided.

  • Description (string) -- (Optional) Specifies a user-provided description of the secret.
  • KmsKeyId (string) --

    (Optional) Specifies the ARN, Key ID, or alias of the Amazon Web Services KMS customer master key (CMK) to be used to encrypt the SecretString or SecretBinary values in the versions stored in this secret.

    You can specify any of the supported ways to identify a Amazon Web Services KMS key ID. If you need to reference a CMK in a different account, you can use only the key ARN or the alias ARN.

    If you don't specify this value, then Secrets Manager defaults to using the Amazon Web Services account's default CMK (the one named aws/secretsmanager ). If a Amazon Web Services KMS CMK with that name doesn't yet exist, then Secrets Manager creates it for you automatically the first time it needs to encrypt a version's SecretString or SecretBinary fields.

    Warning

    You can use the account default CMK to encrypt and decrypt only if you call this operation using credentials from the same account that owns the secret. If the secret resides in a different account, then you must create a custom CMK and specify the ARN in this field.

  • SecretBinary (bytes) --

    (Optional) Specifies binary data that you want to encrypt and store in the new version of the secret. To use this parameter in the command-line tools, we recommend that you store your binary data in a file and then use the appropriate technique for your tool to pass the contents of the file as a parameter.

    Either SecretString or SecretBinary must have a value, but not both. They cannot both be empty.

    This parameter is not available using the Secrets Manager console. It can be accessed only by using the Amazon Web Services CLI or one of the Amazon Web Services SDKs.

  • SecretString (string) --

    (Optional) Specifies text data that you want to encrypt and store in this new version of the secret.

    Either SecretString or SecretBinary must have a value, but not both. They cannot both be empty.

    If you create a secret by using the Secrets Manager console then Secrets Manager puts the protected secret text in only the SecretString parameter. The Secrets Manager console stores the information as a JSON structure of key/value pairs that the Lambda rotation function knows how to parse.

    For storing multiple values, we recommend that you use a JSON text string argument and specify key/value pairs. For more information, see Specifying parameter values for the Amazon Web Services CLI in the Amazon Web Services CLI User Guide.

  • Tags (list) --

    (Optional) Specifies a list of user-defined tags that are attached to the secret. Each tag is a "Key" and "Value" pair of strings. This operation only appends tags to the existing list of tags. To remove tags, you must use UntagResource .

    Warning

    • Secrets Manager tag key names are case sensitive. A tag with the key "ABC" is a different tag from one with key "abc".
    • If you check tags in IAM policy Condition elements as part of your security strategy, then adding or removing a tag can change permissions. If the successful completion of this operation would result in you losing your permissions for this secret, then this operation is blocked and returns an Access Denied error.

    This parameter requires a JSON text string argument. For information on how to format a JSON parameter for the various command line tool environments, see Using JSON for Parameters in the CLI User Guide . For example:

    [{"Key":"CostCenter","Value":"12345"},{"Key":"environment","Value":"production"}]

    If your command-line tool or SDK requires quotation marks around the parameter, you should use single quotes to avoid confusion with the double quotes required in the JSON text.

    The following basic restrictions apply to tags:

    • Maximum number of tags per secret—50
    • Maximum key length—127 Unicode characters in UTF-8
    • Maximum value length—255 Unicode characters in UTF-8
    • Tag keys and values are case sensitive.
    • Do not use the aws: prefix in your tag names or values because Amazon Web Services reserves it for Amazon Web Services use. You can't edit or delete tag names or values with this prefix. Tags with this prefix do not count against your tags per secret limit.
    • If you use your tagging schema across multiple services and resources, remember other services might have restrictions on allowed characters. Generally allowed characters: letters, spaces, and numbers representable in UTF-8, plus the following special characters: + - = . _ : / @.
    • (dict) --

      A structure that contains information about a tag.

      • Key (string) --

        The key identifier, or name, of the tag.

      • Value (string) --

        The string value associated with the key of the tag.

  • AddReplicaRegions (list) --

    (Optional) Add a list of regions to replicate secrets. Secrets Manager replicates the KMSKeyID objects to the list of regions specified in the parameter.

    • (dict) --

      (Optional) Custom type consisting of a Region (required) and the KmsKeyId which can be an ARN , Key ID , or Alias .

      • Region (string) --

        Describes a single instance of Region objects.

      • KmsKeyId (string) --

        Can be an ARN , Key ID , or Alias .

  • ForceOverwriteReplicaSecret (boolean) -- (Optional) If set, the replication overwrites a secret with the same name in the destination region.
Return type

dict

Returns

Response Syntax

{
    'ARN': 'string',
    'Name': 'string',
    'VersionId': 'string',
    'ReplicationStatus': [
        {
            'Region': 'string',
            'KmsKeyId': 'string',
            'Status': 'InSync'|'Failed'|'InProgress',
            'StatusMessage': 'string',
            'LastAccessedDate': datetime(2015, 1, 1)
        },
    ]
}

Response Structure

  • (dict) --

    • ARN (string) --

      The Amazon Resource Name (ARN) of the secret that you just created.

      Note

      Secrets Manager automatically adds several random characters to the name at the end of the ARN when you initially create a secret. This affects only the ARN and not the actual friendly name. This ensures that if you create a new secret with the same name as an old secret that you previously deleted, then users with access to the old secret don't automatically get access to the new secret because the ARNs are different.

    • Name (string) --

      The friendly name of the secret that you just created.

    • VersionId (string) --

      The unique identifier associated with the version of the secret you just created.

    • ReplicationStatus (list) --

      Describes a list of replication status objects as InProgress , Failed or InSync .

      • (dict) --

        A replication object consisting of a RegionReplicationStatus object and includes a Region, KMSKeyId, status, and status message.

        • Region (string) --

          The Region where replication occurs.

        • KmsKeyId (string) --

          Can be an ARN , Key ID , or Alias .

        • Status (string) --

          The status can be InProgress , Failed , or InSync .

        • StatusMessage (string) --

          Status message such as "Secret with this name already exists in this region ".

        • LastAccessedDate (datetime) --

          The date that you last accessed the secret in the Region.

Exceptions

  • SecretsManager.Client.exceptions.InvalidParameterException
  • SecretsManager.Client.exceptions.InvalidRequestException
  • SecretsManager.Client.exceptions.LimitExceededException
  • SecretsManager.Client.exceptions.EncryptionFailure
  • SecretsManager.Client.exceptions.ResourceExistsException
  • SecretsManager.Client.exceptions.ResourceNotFoundException
  • SecretsManager.Client.exceptions.MalformedPolicyDocumentException
  • SecretsManager.Client.exceptions.InternalServiceError
  • SecretsManager.Client.exceptions.PreconditionNotMetException

Examples

The following example shows how to create a secret. The credentials stored in the encrypted secret value are retrieved from a file on disk named mycreds.json.

response = client.create_secret(
    ClientRequestToken='EXAMPLE1-90ab-cdef-fedc-ba987SECRET1',
    Description='My test database secret created with the CLI',
    Name='MyTestDatabaseSecret',
    SecretString='{"username":"david","password":"BnQw!XDWgaEeT9XGTT29"}',
)

print(response)

Expected Output:

{
    'ARN': 'arn:aws:secretsmanager:us-west-2:123456789012:secret:MyTestDatabaseSecret-a1b2c3',
    'Name': 'MyTestDatabaseSecret',
    'VersionId': 'EXAMPLE1-90ab-cdef-fedc-ba987SECRET1',
    'ResponseMetadata': {
        '...': '...',
    },
}
delete_resource_policy(**kwargs)

Deletes the resource-based permission policy attached to the secret.

Minimum permissions

To run this command, you must have the following permissions:

  • secretsmanager:DeleteResourcePolicy
Related operations
  • To attach a resource policy to a secret, use PutResourcePolicy .
  • To retrieve the current resource-based policy attached to a secret, use GetResourcePolicy .
  • To list all of the currently available secrets, use ListSecrets .

See also: AWS API Documentation

Request Syntax

response = client.delete_resource_policy(
    SecretId='string'
)
Parameters
SecretId (string) --

[REQUIRED]

Specifies the secret that you want to delete the attached resource-based policy for. You can specify either the Amazon Resource Name (ARN) or the friendly name of the secret.

For an ARN, we recommend that you specify a complete ARN rather than a partial ARN.

Return type
dict
Returns
Response Syntax
{
    'ARN': 'string',
    'Name': 'string'
}

Response Structure

  • (dict) --
    • ARN (string) --

      The ARN of the secret that the resource-based policy was deleted for.

    • Name (string) --

      The friendly name of the secret that the resource-based policy was deleted for.

Exceptions

  • SecretsManager.Client.exceptions.ResourceNotFoundException
  • SecretsManager.Client.exceptions.InternalServiceError
  • SecretsManager.Client.exceptions.InvalidRequestException
  • SecretsManager.Client.exceptions.InvalidParameterException

Examples

The following example shows how to delete the resource-based policy that is attached to a secret.

response = client.delete_resource_policy(
    SecretId='MyTestDatabaseSecret',
)

print(response)

Expected Output:

{
    'ARN': 'arn:aws:secretsmanager:us-west-2:123456789012:secret:MyTestDatabaseMasterSecret-a1b2c3',
    'Name': 'MyTestDatabaseSecret',
    'ResponseMetadata': {
        '...': '...',
    },
}
delete_secret(**kwargs)

Deletes an entire secret and all of the versions. You can optionally include a recovery window during which you can restore the secret. If you don't specify a recovery window value, the operation defaults to 30 days. Secrets Manager attaches a DeletionDate stamp to the secret that specifies the end of the recovery window. At the end of the recovery window, Secrets Manager deletes the secret permanently.

At any time before recovery window ends, you can use RestoreSecret to remove the DeletionDate and cancel the deletion of the secret.

You cannot access the encrypted secret information in any secret scheduled for deletion. If you need to access that information, you must cancel the deletion with RestoreSecret and then retrieve the information.

Note

  • There is no explicit operation to delete a version of a secret. Instead, remove all staging labels from the VersionStage field of a version. That marks the version as deprecated and allows Secrets Manager to delete it as needed. Versions without any staging labels do not show up in ListSecretVersionIds unless you specify IncludeDeprecated .
  • The permanent secret deletion at the end of the waiting period is performed as a background task with low priority. There is no guarantee of a specific time after the recovery window for the actual delete operation to occur.

Minimum permissions

To run this command, you must have the following permissions:

  • secretsmanager:DeleteSecret
Related operations
  • To create a secret, use CreateSecret .
  • To cancel deletion of a version of a secret before the recovery window has expired, use RestoreSecret .

See also: AWS API Documentation

Request Syntax

response = client.delete_secret(
    SecretId='string',
    RecoveryWindowInDays=123,
    ForceDeleteWithoutRecovery=True|False
)
Parameters
  • SecretId (string) --

    [REQUIRED]

    Specifies the secret to delete. You can specify either the Amazon Resource Name (ARN) or the friendly name of the secret.

    For an ARN, we recommend that you specify a complete ARN rather than a partial ARN.

  • RecoveryWindowInDays (integer) --

    (Optional) Specifies the number of days that Secrets Manager waits before Secrets Manager can delete the secret. You can't use both this parameter and the ForceDeleteWithoutRecovery parameter in the same API call.

    This value can range from 7 to 30 days with a default value of 30.

  • ForceDeleteWithoutRecovery (boolean) --

    (Optional) Specifies that the secret is to be deleted without any recovery window. You can't use both this parameter and the RecoveryWindowInDays parameter in the same API call.

    An asynchronous background process performs the actual deletion, so there can be a short delay before the operation completes. If you write code to delete and then immediately recreate a secret with the same name, ensure that your code includes appropriate back off and retry logic.

    Warning

    Use this parameter with caution. This parameter causes the operation to skip the normal waiting period before the permanent deletion that Amazon Web Services would normally impose with the RecoveryWindowInDays parameter. If you delete a secret with the ForceDeleteWithouRecovery parameter, then you have no opportunity to recover the secret. You lose the secret permanently.

    Warning

    If you use this parameter and include a previously deleted or nonexistent secret, the operation does not return the error ResourceNotFoundException in order to correctly handle retries.

Return type

dict

Returns

Response Syntax

{
    'ARN': 'string',
    'Name': 'string',
    'DeletionDate': datetime(2015, 1, 1)
}

Response Structure

  • (dict) --

    • ARN (string) --

      The ARN of the secret that is now scheduled for deletion.

    • Name (string) --

      The friendly name of the secret currently scheduled for deletion.

    • DeletionDate (datetime) --

      The date and time after which this secret can be deleted by Secrets Manager and can no longer be restored. This value is the date and time of the delete request plus the number of days specified in RecoveryWindowInDays .

Exceptions

  • SecretsManager.Client.exceptions.ResourceNotFoundException
  • SecretsManager.Client.exceptions.InvalidParameterException
  • SecretsManager.Client.exceptions.InvalidRequestException
  • SecretsManager.Client.exceptions.InternalServiceError

Examples

The following example shows how to delete a secret. The secret stays in your account in a deprecated and inaccessible state until the recovery window ends. After the date and time in the DeletionDate response field has passed, you can no longer recover this secret with restore-secret.

response = client.delete_secret(
    RecoveryWindowInDays=7,
    SecretId='MyTestDatabaseSecret1',
)

print(response)

Expected Output:

{
    'ARN': 'arn:aws:secretsmanager:us-west-2:123456789012:secret:MyTestDatabaseSecret-a1b2c3',
    'DeletionDate': datetime(2018, 4, 18, 21, 2, 29, 2, 108, 0),
    'Name': 'MyTestDatabaseSecret',
    'ResponseMetadata': {
        '...': '...',
    },
}
describe_secret(**kwargs)

Retrieves the details of a secret. It does not include the encrypted fields. Secrets Manager only returns fields populated with a value in the response.

Minimum permissions

To run this command, you must have the following permissions:

  • secretsmanager:DescribeSecret
Related operations
  • To create a secret, use CreateSecret .
  • To modify a secret, use UpdateSecret .
  • To retrieve the encrypted secret information in a version of the secret, use GetSecretValue .
  • To list all of the secrets in the Amazon Web Services account, use ListSecrets .

See also: AWS API Documentation

Request Syntax

response = client.describe_secret(
    SecretId='string'
)
Parameters
SecretId (string) --

[REQUIRED]

The identifier of the secret whose details you want to retrieve. You can specify either the Amazon Resource Name (ARN) or the friendly name of the secret.

For an ARN, we recommend that you specify a complete ARN rather than a partial ARN.

Return type
dict
Returns
Response Syntax
{
    'ARN': 'string',
    'Name': 'string',
    'Description': 'string',
    'KmsKeyId': 'string',
    'RotationEnabled': True|False,
    'RotationLambdaARN': 'string',
    'RotationRules': {
        'AutomaticallyAfterDays': 123
    },
    'LastRotatedDate': datetime(2015, 1, 1),
    'LastChangedDate': datetime(2015, 1, 1),
    'LastAccessedDate': datetime(2015, 1, 1),
    'DeletedDate': datetime(2015, 1, 1),
    'Tags': [
        {
            'Key': 'string',
            'Value': 'string'
        },
    ],
    'VersionIdsToStages': {
        'string': [
            'string',
        ]
    },
    'OwningService': 'string',
    'CreatedDate': datetime(2015, 1, 1),
    'PrimaryRegion': 'string',
    'ReplicationStatus': [
        {
            'Region': 'string',
            'KmsKeyId': 'string',
            'Status': 'InSync'|'Failed'|'InProgress',
            'StatusMessage': 'string',
            'LastAccessedDate': datetime(2015, 1, 1)
        },
    ]
}

Response Structure

  • (dict) --
    • ARN (string) --

      The ARN of the secret.

    • Name (string) --

      The user-provided friendly name of the secret.

    • Description (string) --

      The user-provided description of the secret.

    • KmsKeyId (string) --

      The ARN or alias of the Amazon Web Services KMS customer master key (CMK) that's used to encrypt the SecretString or SecretBinary fields in each version of the secret. If you don't provide a key, then Secrets Manager defaults to encrypting the secret fields with the default Amazon Web Services KMS CMK (the one named awssecretsmanager ) for this account.

    • RotationEnabled (boolean) --

      Specifies whether automatic rotation is enabled for this secret.

      To enable rotation, use RotateSecret with AutomaticallyRotateAfterDays set to a value greater than 0. To disable rotation, use CancelRotateSecret .

    • RotationLambdaARN (string) --

      The ARN of a Lambda function that's invoked by Secrets Manager to rotate the secret either automatically per the schedule or manually by a call to RotateSecret .

    • RotationRules (dict) --

      A structure with the rotation configuration for this secret. This field is only populated if rotation is configured.

      • AutomaticallyAfterDays (integer) --

        Specifies the number of days between automatic scheduled rotations of the secret.

        Secrets Manager schedules the next rotation when the previous one is complete. Secrets Manager schedules the date by adding the rotation interval (number of days) to the actual date of the last rotation. The service chooses the hour within that 24-hour date window randomly. The minute is also chosen somewhat randomly, but weighted towards the top of the hour and influenced by a variety of factors that help distribute load.

    • LastRotatedDate (datetime) --

      The last date and time that the rotation process for this secret was invoked.

      The most recent date and time that the Secrets Manager rotation process successfully completed. If the secret doesn't rotate, Secrets Manager returns a null value.

    • LastChangedDate (datetime) --

      The last date and time that this secret was modified in any way.

    • LastAccessedDate (datetime) --

      The last date that this secret was accessed. This value is truncated to midnight of the date and therefore shows only the date, not the time.

    • DeletedDate (datetime) --

      This value exists if the secret is scheduled for deletion. Some time after the specified date and time, Secrets Manager deletes the secret and all of its versions.

      If a secret is scheduled for deletion, then its details, including the encrypted secret information, is not accessible. To cancel a scheduled deletion and restore access, use RestoreSecret .

    • Tags (list) --

      The list of user-defined tags that are associated with the secret. To add tags to a secret, use TagResource . To remove tags, use UntagResource .

      • (dict) --

        A structure that contains information about a tag.

        • Key (string) --

          The key identifier, or name, of the tag.

        • Value (string) --

          The string value associated with the key of the tag.

    • VersionIdsToStages (dict) --

      A list of all of the currently assigned VersionStage staging labels and the VersionId that each is attached to. Staging labels are used to keep track of the different versions during the rotation process.

      Note

      A version that does not have any staging labels attached is considered deprecated and subject to deletion. Such versions are not included in this list.

      • (string) --
        • (list) --
          • (string) --
    • OwningService (string) --

      Returns the name of the service that created this secret.

    • CreatedDate (datetime) --

      The date you created the secret.

    • PrimaryRegion (string) --

      Specifies the primary region for secret replication.

    • ReplicationStatus (list) --

      Describes a list of replication status objects as InProgress , Failed or InSync .``P``

      • (dict) --

        A replication object consisting of a RegionReplicationStatus object and includes a Region, KMSKeyId, status, and status message.

        • Region (string) --

          The Region where replication occurs.

        • KmsKeyId (string) --

          Can be an ARN , Key ID , or Alias .

        • Status (string) --

          The status can be InProgress , Failed , or InSync .

        • StatusMessage (string) --

          Status message such as "Secret with this name already exists in this region ".

        • LastAccessedDate (datetime) --

          The date that you last accessed the secret in the Region.

Exceptions

  • SecretsManager.Client.exceptions.ResourceNotFoundException
  • SecretsManager.Client.exceptions.InternalServiceError
  • SecretsManager.Client.exceptions.InvalidParameterException

Examples

The following example shows how to get the details about a secret.

response = client.describe_secret(
    SecretId='MyTestDatabaseSecret',
)

print(response)

Expected Output:

{
    'ARN': 'arn:aws:secretsmanager:us-west-2:123456789012:secret:MyTestDatabaseSecret-a1b2c3',
    'Description': 'My test database secret',
    'KmsKeyId': 'arn:aws:kms:us-west-2:123456789012:key/EXAMPLE1-90ab-cdef-fedc-ba987KMSKEY1',
    'LastAccessedDate': datetime(2018, 4, 17, 0, 0, 0, 1, 107, 0),
    'LastChangedDate': 1523477145.729,
    'LastRotatedDate': 1525747253.72,
    'Name': 'MyTestDatabaseSecret',
    'RotationEnabled': True,
    'RotationLambdaARN': 'arn:aws:lambda:us-west-2:123456789012:function:MyTestRotationLambda',
    'RotationRules': {
        'AutomaticallyAfterDays': 30,
    },
    'Tags': [
        {
            'Key': 'SecondTag',
            'Value': 'AnotherValue',
        },
        {
            'Key': 'FirstTag',
            'Value': 'SomeValue',
        },
    ],
    'VersionIdsToStages': {
        'EXAMPLE1-90ab-cdef-fedc-ba987EXAMPLE': [
            'AWSPREVIOUS',
        ],
        'EXAMPLE2-90ab-cdef-fedc-ba987EXAMPLE': [
            'AWSCURRENT',
        ],
    },
    'ResponseMetadata': {
        '...': '...',
    },
}
get_paginator(operation_name)

Create a paginator for an operation.

Parameters
operation_name (string) -- The operation name. This is the same name as the method name on the client. For example, if the method name is create_foo, and you'd normally invoke the operation as client.create_foo(**kwargs), if the create_foo operation can be paginated, you can use the call client.get_paginator("create_foo").
Raises OperationNotPageableError
Raised if the operation is not pageable. You can use the client.can_paginate method to check if an operation is pageable.
Return type
L{botocore.paginate.Paginator}
Returns
A paginator object.
get_random_password(**kwargs)

Generates a random password of the specified complexity. This operation is intended for use in the Lambda rotation function. Per best practice, we recommend that you specify the maximum length and include every character type that the system you are generating a password for can support.

Minimum permissions

To run this command, you must have the following permissions:

  • secretsmanager:GetRandomPassword

See also: AWS API Documentation

Request Syntax

response = client.get_random_password(
    PasswordLength=123,
    ExcludeCharacters='string',
    ExcludeNumbers=True|False,
    ExcludePunctuation=True|False,
    ExcludeUppercase=True|False,
    ExcludeLowercase=True|False,
    IncludeSpace=True|False,
    RequireEachIncludedType=True|False
)
Parameters
  • PasswordLength (integer) -- The desired length of the generated password. The default value if you do not include this parameter is 32 characters.
  • ExcludeCharacters (string) -- A string that includes characters that should not be included in the generated password. The default is that all characters from the included sets can be used.
  • ExcludeNumbers (boolean) -- Specifies that the generated password should not include digits. The default if you do not include this switch parameter is that digits can be included.
  • ExcludePunctuation (boolean) --

    Specifies that the generated password should not include punctuation characters. The default if you do not include this switch parameter is that punctuation characters can be included.

    The following are the punctuation characters that can be included in the generated password if you don't explicitly exclude them with ExcludeCharacters or ExcludePunctuation :

    ! " # $ % & ' ( ) * + , - . / : ; < = > ? @ [ \ ] ^ _ ` { | } ~
  • ExcludeUppercase (boolean) -- Specifies that the generated password should not include uppercase letters. The default if you do not include this switch parameter is that uppercase letters can be included.
  • ExcludeLowercase (boolean) -- Specifies that the generated password should not include lowercase letters. The default if you do not include this switch parameter is that lowercase letters can be included.
  • IncludeSpace (boolean) -- Specifies that the generated password can include the space character. The default if you do not include this switch parameter is that the space character is not included.
  • RequireEachIncludedType (boolean) -- A boolean value that specifies whether the generated password must include at least one of every allowed character type. The default value is True and the operation requires at least one of every character type.
Return type

dict

Returns

Response Syntax

{
    'RandomPassword': 'string'
}

Response Structure

  • (dict) --

    • RandomPassword (string) --

      A string with the generated password.

Exceptions

  • SecretsManager.Client.exceptions.InvalidParameterException
  • SecretsManager.Client.exceptions.InvalidRequestException
  • SecretsManager.Client.exceptions.InternalServiceError

Examples

The following example shows how to request a randomly generated password. This example includes the optional flags to require spaces and at least one character of each included type. It specifies a length of 20 characters.

response = client.get_random_password(
    IncludeSpace=True,
    PasswordLength=20,
    RequireEachIncludedType=True,
)

print(response)

Expected Output:

{
    'RandomPassword': 'N+Z43a,>vx7j O8^*<8i3',
    'ResponseMetadata': {
        '...': '...',
    },
}
get_resource_policy(**kwargs)

Retrieves the JSON text of the resource-based policy document attached to the specified secret. The JSON request string input and response output displays formatted code with white space and line breaks for better readability. Submit your input as a single line JSON string.

Minimum permissions

To run this command, you must have the following permissions:

  • secretsmanager:GetResourcePolicy
Related operations
  • To attach a resource policy to a secret, use PutResourcePolicy .
  • To delete the resource-based policy attached to a secret, use DeleteResourcePolicy .
  • To list all of the currently available secrets, use ListSecrets .

See also: AWS API Documentation

Request Syntax

response = client.get_resource_policy(
    SecretId='string'
)
Parameters
SecretId (string) --

[REQUIRED]

Specifies the secret that you want to retrieve the attached resource-based policy for. You can specify either the Amazon Resource Name (ARN) or the friendly name of the secret.

For an ARN, we recommend that you specify a complete ARN rather than a partial ARN.

Return type
dict
Returns
Response Syntax
{
    'ARN': 'string',
    'Name': 'string',
    'ResourcePolicy': 'string'
}

Response Structure

  • (dict) --
    • ARN (string) --

      The ARN of the secret that the resource-based policy was retrieved for.

    • Name (string) --

      The friendly name of the secret that the resource-based policy was retrieved for.

    • ResourcePolicy (string) --

      A JSON-formatted string that describes the permissions that are associated with the attached secret. These permissions are combined with any permissions that are associated with the user or role that attempts to access this secret. The combined permissions specify who can access the secret and what actions they can perform. For more information, see Authentication and Access Control for Amazon Web Services Secrets Manager in the Amazon Web Services Secrets Manager User Guide .

Exceptions

  • SecretsManager.Client.exceptions.ResourceNotFoundException
  • SecretsManager.Client.exceptions.InternalServiceError
  • SecretsManager.Client.exceptions.InvalidRequestException
  • SecretsManager.Client.exceptions.InvalidParameterException

Examples

The following example shows how to retrieve the resource-based policy that is attached to a secret.

response = client.get_resource_policy(
    SecretId='MyTestDatabaseSecret',
)

print(response)

Expected Output:

{
    'ARN': 'arn:aws:secretsmanager:us-west-2:123456789012:secret:MyTestDatabaseSecret-a1b2c3',
    'Name': 'MyTestDatabaseSecret',
    'ResourcePolicy': '{\n"Version":"2012-10-17",\n"Statement":[{\n"Effect":"Allow",\n"Principal":{\n"AWS":"arn:aws:iam::123456789012:root"\n},\n"Action":"secretsmanager:GetSecretValue",\n"Resource":"*"\n}]\n}',
    'ResponseMetadata': {
        '...': '...',
    },
}
get_secret_value(**kwargs)

Retrieves the contents of the encrypted fields SecretString or SecretBinary from the specified version of a secret, whichever contains content.

Minimum permissions

To run this command, you must have the following permissions:

  • secretsmanager:GetSecretValue
  • kms:Decrypt - required only if you use a customer-managed Amazon Web Services KMS key to encrypt the secret. You do not need this permission to use the account's default Amazon Web Services managed CMK for Secrets Manager.
Related operations
  • To create a new version of the secret with different encrypted information, use PutSecretValue .
  • To retrieve the non-encrypted details for the secret, use DescribeSecret .

See also: AWS API Documentation

Request Syntax

response = client.get_secret_value(
    SecretId='string',
    VersionId='string',
    VersionStage='string'
)
Parameters
  • SecretId (string) --

    [REQUIRED]

    Specifies the secret containing the version that you want to retrieve. You can specify either the Amazon Resource Name (ARN) or the friendly name of the secret.

    For an ARN, we recommend that you specify a complete ARN rather than a partial ARN.

  • VersionId (string) --

    Specifies the unique identifier of the version of the secret that you want to retrieve. If you specify both this parameter and VersionStage , the two parameters must refer to the same secret version. If you don't specify either a VersionStage or VersionId then the default is to perform the operation on the version with the VersionStage value of AWSCURRENT .

    This value is typically a UUID-type value with 32 hexadecimal digits.

  • VersionStage (string) --

    Specifies the secret version that you want to retrieve by the staging label attached to the version.

    Staging labels are used to keep track of different versions during the rotation process. If you specify both this parameter and VersionId , the two parameters must refer to the same secret version . If you don't specify either a VersionStage or VersionId , then the default is to perform the operation on the version with the VersionStage value of AWSCURRENT .

Return type

dict

Returns

Response Syntax

{
    'ARN': 'string',
    'Name': 'string',
    'VersionId': 'string',
    'SecretBinary': b'bytes',
    'SecretString': 'string',
    'VersionStages': [
        'string',
    ],
    'CreatedDate': datetime(2015, 1, 1)
}

Response Structure

  • (dict) --

    • ARN (string) --

      The ARN of the secret.

    • Name (string) --

      The friendly name of the secret.

    • VersionId (string) --

      The unique identifier of this version of the secret.

    • SecretBinary (bytes) --

      The decrypted part of the protected secret information that was originally provided as binary data in the form of a byte array. The response parameter represents the binary data as a base64-encoded string.

      This parameter is not used if the secret is created by the Secrets Manager console.

      If you store custom information in this field of the secret, then you must code your Lambda rotation function to parse and interpret whatever you store in the SecretString or SecretBinary fields.

    • SecretString (string) --

      The decrypted part of the protected secret information that was originally provided as a string.

      If you create this secret by using the Secrets Manager console then only the SecretString parameter contains data. Secrets Manager stores the information as a JSON structure of key/value pairs that the Lambda rotation function knows how to parse.

      If you store custom information in the secret by using the CreateSecret , UpdateSecret , or PutSecretValue API operations instead of the Secrets Manager console, or by using the Other secret type in the console, then you must code your Lambda rotation function to parse and interpret those values.

    • VersionStages (list) --

      A list of all of the staging labels currently attached to this version of the secret.

      • (string) --
    • CreatedDate (datetime) --

      The date and time that this version of the secret was created.

Exceptions

  • SecretsManager.Client.exceptions.ResourceNotFoundException
  • SecretsManager.Client.exceptions.InvalidParameterException
  • SecretsManager.Client.exceptions.InvalidRequestException
  • SecretsManager.Client.exceptions.DecryptionFailure
  • SecretsManager.Client.exceptions.InternalServiceError

Examples

The following example shows how to retrieve the secret string value from the version of the secret that has the AWSPREVIOUS staging label attached. If you want to retrieve the AWSCURRENT version of the secret, then you can omit the VersionStage parameter because it defaults to AWSCURRENT.

response = client.get_secret_value(
    SecretId='MyTestDatabaseSecret',
    VersionStage='AWSPREVIOUS',
)

print(response)

Expected Output:

{
    'ARN': 'arn:aws:secretsmanager:us-west-2:123456789012:secret:MyTestDatabaseSecret-a1b2c3',
    'CreatedDate': 1523477145.713,
    'Name': 'MyTestDatabaseSecret',
    'SecretString': '{\n  "username":"david",\n  "password":"BnQw&XDWgaEeT9XGTT29"\n}\n',
    'VersionId': 'EXAMPLE1-90ab-cdef-fedc-ba987SECRET1',
    'VersionStages': [
        'AWSPREVIOUS',
    ],
    'ResponseMetadata': {
        '...': '...',
    },
}
get_waiter(waiter_name)

Returns an object that can wait for some condition.

Parameters
waiter_name (str) -- The name of the waiter to get. See the waiters section of the service docs for a list of available waiters.
Returns
The specified waiter object.
Return type
botocore.waiter.Waiter
list_secret_version_ids(**kwargs)

Lists all of the versions attached to the specified secret. The output does not include the SecretString or SecretBinary fields. By default, the list includes only versions that have at least one staging label in VersionStage attached.

Note

Always check the NextToken response parameter when calling any of the List* operations. These operations can occasionally return an empty or shorter than expected list of results even when there more results become available. When this happens, the NextToken response parameter contains a value to pass to the next call to the same API to request the next part of the list.

Minimum permissions

To run this command, you must have the following permissions:

  • secretsmanager:ListSecretVersionIds
Related operations
  • To list the secrets in an account, use ListSecrets .

See also: AWS API Documentation

Request Syntax

response = client.list_secret_version_ids(
    SecretId='string',
    MaxResults=123,
    NextToken='string',
    IncludeDeprecated=True|False
)
Parameters
  • SecretId (string) --

    [REQUIRED]

    The identifier for the secret containing the versions you want to list. You can specify either the Amazon Resource Name (ARN) or the friendly name of the secret.

    For an ARN, we recommend that you specify a complete ARN rather than a partial ARN.

  • MaxResults (integer) -- (Optional) Limits the number of results you want to include in the response. If you don't include this parameter, it defaults to a value that's specific to the operation. If additional items exist beyond the maximum you specify, the NextToken response element is present and has a value (isn't null). Include that value as the NextToken request parameter in the next call to the operation to get the next part of the results. Note that Secrets Manager might return fewer results than the maximum even when there are more results available. You should check NextToken after every operation to ensure that you receive all of the results.
  • NextToken (string) -- (Optional) Use this parameter in a request if you receive a NextToken response in a previous request indicating there's more output available. In a subsequent call, set it to the value of the previous call NextToken response to indicate where the output should continue from.
  • IncludeDeprecated (boolean) -- (Optional) Specifies that you want the results to include versions that do not have any staging labels attached to them. Such versions are considered deprecated and are subject to deletion by Secrets Manager as needed.
Return type

dict

Returns

Response Syntax

{
    'Versions': [
        {
            'VersionId': 'string',
            'VersionStages': [
                'string',
            ],
            'LastAccessedDate': datetime(2015, 1, 1),
            'CreatedDate': datetime(2015, 1, 1),
            'KmsKeyIds': [
                'string',
            ]
        },
    ],
    'NextToken': 'string',
    'ARN': 'string',
    'Name': 'string'
}

Response Structure

  • (dict) --

    • Versions (list) --

      The list of the currently available versions of the specified secret.

      • (dict) --

        A structure that contains information about one version of a secret.

        • VersionId (string) --

          The unique version identifier of this version of the secret.

        • VersionStages (list) --

          An array of staging labels that are currently associated with this version of the secret.

          • (string) --
        • LastAccessedDate (datetime) --

          The date that this version of the secret was last accessed. Note that the resolution of this field is at the date level and does not include the time.

        • CreatedDate (datetime) --

          The date and time this version of the secret was created.

        • KmsKeyIds (list) --

          The KMS keys used to encrypt the secret version.

          • (string) --
    • NextToken (string) --

      If present in the response, this value indicates that there's more output available than included in the current response. This can occur even when the response includes no values at all, such as when you ask for a filtered view of a very long list. Use this value in the NextToken request parameter in a subsequent call to the operation to continue processing and get the next part of the output. You should repeat this until the NextToken response element comes back empty (as null ).

    • ARN (string) --

      The Amazon Resource Name (ARN) for the secret.

      Note

      Secrets Manager automatically adds several random characters to the name at the end of the ARN when you initially create a secret. This affects only the ARN and not the actual friendly name. This ensures that if you create a new secret with the same name as an old secret that you previously deleted, then users with access to the old secret don't automatically get access to the new secret because the ARNs are different.

    • Name (string) --

      The friendly name of the secret.

Exceptions

  • SecretsManager.Client.exceptions.InvalidNextTokenException
  • SecretsManager.Client.exceptions.ResourceNotFoundException
  • SecretsManager.Client.exceptions.InternalServiceError
  • SecretsManager.Client.exceptions.InvalidParameterException

Examples

The following example shows how to retrieve a list of all of the versions of a secret, including those without any staging labels.

response = client.list_secret_version_ids(
    IncludeDeprecated=True,
    SecretId='MyTestDatabaseSecret',
)

print(response)

Expected Output:

{
    'ARN': 'arn:aws:secretsmanager:us-west-2:123456789012:secret:MyTestDatabaseSecret-a1b2c3',
    'Name': 'MyTestDatabaseSecret',
    'Versions': [
        {
            'CreatedDate': 1523477145.713,
            'VersionId': 'EXAMPLE1-90ab-cdef-fedc-ba987EXAMPLE',
            'VersionStages': [
                'AWSPREVIOUS',
            ],
        },
        {
            'CreatedDate': 1523486221.391,
            'VersionId': 'EXAMPLE2-90ab-cdef-fedc-ba987EXAMPLE',
            'VersionStages': [
                'AWSCURRENT',
            ],
        },
        {
            'CreatedDate': 1511974462.36,
            'VersionId': 'EXAMPLE3-90ab-cdef-fedc-ba987EXAMPLE;',
        },
    ],
    'ResponseMetadata': {
        '...': '...',
    },
}
list_secrets(**kwargs)

Lists all of the secrets that are stored by Secrets Manager in the Amazon Web Services account. To list the versions currently stored for a specific secret, use ListSecretVersionIds . The encrypted fields SecretString and SecretBinary are not included in the output. To get that information, call the GetSecretValue operation.

Note

Always check the NextToken response parameter when calling any of the List* operations. These operations can occasionally return an empty or shorter than expected list of results even when there more results become available. When this happens, the NextToken response parameter contains a value to pass to the next call to the same API to request the next part of the list.

Minimum permissions

To run this command, you must have the following permissions:

  • secretsmanager:ListSecrets
Related operations
  • To list the versions attached to a secret, use ListSecretVersionIds .

See also: AWS API Documentation

Request Syntax

response = client.list_secrets(
    MaxResults=123,
    NextToken='string',
    Filters=[
        {
            'Key': 'description'|'name'|'tag-key'|'tag-value'|'primary-region'|'all',
            'Values': [
                'string',
            ]
        },
    ],
    SortOrder='asc'|'desc'
)
Parameters
  • MaxResults (integer) -- (Optional) Limits the number of results you want to include in the response. If you don't include this parameter, it defaults to a value that's specific to the operation. If additional items exist beyond the maximum you specify, the NextToken response element is present and has a value (isn't null). Include that value as the NextToken request parameter in the next call to the operation to get the next part of the results. Note that Secrets Manager might return fewer results than the maximum even when there are more results available. You should check NextToken after every operation to ensure that you receive all of the results.
  • NextToken (string) -- (Optional) Use this parameter in a request if you receive a NextToken response in a previous request indicating there's more output available. In a subsequent call, set it to the value of the previous call NextToken response to indicate where the output should continue from.
  • Filters (list) --

    Lists the secret request filters.

    • (dict) --

      Allows you to add filters when you use the search function in Secrets Manager.

      • Key (string) --

        Filters your list of secrets by a specific key.

      • Values (list) --

        Filters your list of secrets by a specific value.

        You can prefix your search value with an exclamation mark (! ) in order to perform negation filters.

        • (string) --
  • SortOrder (string) -- Lists secrets in the requested order.
Return type

dict

Returns

Response Syntax

{
    'SecretList': [
        {
            'ARN': 'string',
            'Name': 'string',
            'Description': 'string',
            'KmsKeyId': 'string',
            'RotationEnabled': True|False,
            'RotationLambdaARN': 'string',
            'RotationRules': {
                'AutomaticallyAfterDays': 123
            },
            'LastRotatedDate': datetime(2015, 1, 1),
            'LastChangedDate': datetime(2015, 1, 1),
            'LastAccessedDate': datetime(2015, 1, 1),
            'DeletedDate': datetime(2015, 1, 1),
            'Tags': [
                {
                    'Key': 'string',
                    'Value': 'string'
                },
            ],
            'SecretVersionsToStages': {
                'string': [
                    'string',
                ]
            },
            'OwningService': 'string',
            'CreatedDate': datetime(2015, 1, 1),
            'PrimaryRegion': 'string'
        },
    ],
    'NextToken': 'string'
}

Response Structure

  • (dict) --

    • SecretList (list) --

      A list of the secrets in the account.

      • (dict) --

        A structure that contains the details about a secret. It does not include the encrypted SecretString and SecretBinary values. To get those values, use the GetSecretValue operation.

        • ARN (string) --

          The Amazon Resource Name (ARN) of the secret.

          For more information about ARNs in Secrets Manager, see Policy Resources in the Amazon Web Services Secrets Manager User Guide .

        • Name (string) --

          The friendly name of the secret. You can use forward slashes in the name to represent a path hierarchy. For example, /prod/databases/dbserver1 could represent the secret for a server named dbserver1 in the folder databases in the folder prod .

        • Description (string) --

          The user-provided description of the secret.

        • KmsKeyId (string) --

          The ARN or alias of the Amazon Web Services KMS customer master key (CMK) used to encrypt the SecretString and SecretBinary fields in each version of the secret. If you don't provide a key, then Secrets Manager defaults to encrypting the secret fields with the default KMS CMK, the key named awssecretsmanager , for this account.

        • RotationEnabled (boolean) --

          Indicates whether automatic, scheduled rotation is enabled for this secret.

        • RotationLambdaARN (string) --

          The ARN of an Amazon Web Services Lambda function invoked by Secrets Manager to rotate and expire the secret either automatically per the schedule or manually by a call to RotateSecret .

        • RotationRules (dict) --

          A structure that defines the rotation configuration for the secret.

          • AutomaticallyAfterDays (integer) --

            Specifies the number of days between automatic scheduled rotations of the secret.

            Secrets Manager schedules the next rotation when the previous one is complete. Secrets Manager schedules the date by adding the rotation interval (number of days) to the actual date of the last rotation. The service chooses the hour within that 24-hour date window randomly. The minute is also chosen somewhat randomly, but weighted towards the top of the hour and influenced by a variety of factors that help distribute load.

        • LastRotatedDate (datetime) --

          The most recent date and time that the Secrets Manager rotation process was successfully completed. This value is null if the secret hasn't ever rotated.

        • LastChangedDate (datetime) --

          The last date and time that this secret was modified in any way.

        • LastAccessedDate (datetime) --

          The last date that this secret was accessed. This value is truncated to midnight of the date and therefore shows only the date, not the time.

        • DeletedDate (datetime) --

          The date and time the deletion of the secret occurred. Not present on active secrets. The secret can be recovered until the number of days in the recovery window has passed, as specified in the RecoveryWindowInDays parameter of the DeleteSecret operation.

        • Tags (list) --

          The list of user-defined tags associated with the secret. To add tags to a secret, use TagResource . To remove tags, use UntagResource .

          • (dict) --

            A structure that contains information about a tag.

            • Key (string) --

              The key identifier, or name, of the tag.

            • Value (string) --

              The string value associated with the key of the tag.

        • SecretVersionsToStages (dict) --

          A list of all of the currently assigned SecretVersionStage staging labels and the SecretVersionId attached to each one. Staging labels are used to keep track of the different versions during the rotation process.

          Note

          A version that does not have any SecretVersionStage is considered deprecated and subject to deletion. Such versions are not included in this list.

          • (string) --
            • (list) --
              • (string) --
        • OwningService (string) --

          Returns the name of the service that created the secret.

        • CreatedDate (datetime) --

          The date and time when a secret was created.

        • PrimaryRegion (string) --

          The Region where Secrets Manager originated the secret.

    • NextToken (string) --

      If present in the response, this value indicates that there's more output available than included in the current response. This can occur even when the response includes no values at all, such as when you ask for a filtered view of a very long list. Use this value in the NextToken request parameter in a subsequent call to the operation to continue processing and get the next part of the output. You should repeat this until the NextToken response element comes back empty (as null ).

Exceptions

  • SecretsManager.Client.exceptions.InvalidParameterException
  • SecretsManager.Client.exceptions.InvalidNextTokenException
  • SecretsManager.Client.exceptions.InternalServiceError

Examples

The following example shows how to list all of the secrets in your account.

response = client.list_secrets(
)

print(response)

Expected Output:

{
    'SecretList': [
        {
            'ARN': 'arn:aws:secretsmanager:us-west-2:123456789012:secret:MyTestDatabaseSecret-a1b2c3',
            'Description': 'My test database secret',
            'LastChangedDate': 1523477145.729,
            'Name': 'MyTestDatabaseSecret',
            'SecretVersionsToStages': {
                'EXAMPLE1-90ab-cdef-fedc-ba987EXAMPLE': [
                    'AWSCURRENT',
                ],
            },
        },
        {
            'ARN': 'arn:aws:secretsmanager:us-west-2:123456789012:secret:MyTestDatabaseSecret1-d4e5f6',
            'Description': 'Another secret created for a different database',
            'LastChangedDate': 1523482025.685,
            'Name': 'MyTestDatabaseSecret1',
            'SecretVersionsToStages': {
                'EXAMPLE2-90ab-cdef-fedc-ba987EXAMPLE': [
                    'AWSCURRENT',
                ],
            },
        },
    ],
    'ResponseMetadata': {
        '...': '...',
    },
}
put_resource_policy(**kwargs)

Attaches the contents of the specified resource-based permission policy to a secret. A resource-based policy is optional. Alternatively, you can use IAM identity-based policies that specify the secret's Amazon Resource Name (ARN) in the policy statement's Resources element. You can also use a combination of both identity-based and resource-based policies. The affected users and roles receive the permissions that are permitted by all of the relevant policies. For more information, see Using Resource-Based Policies for Amazon Web Services Secrets Manager . For the complete description of the Amazon Web Services policy syntax and grammar, see IAM JSON Policy Reference in the IAM User Guide .

Minimum permissions

To run this command, you must have the following permissions:

  • secretsmanager:PutResourcePolicy
Related operations
  • To retrieve the resource policy attached to a secret, use GetResourcePolicy .
  • To delete the resource-based policy attached to a secret, use DeleteResourcePolicy .
  • To list all of the currently available secrets, use ListSecrets .

See also: AWS API Documentation

Request Syntax

response = client.put_resource_policy(
    SecretId='string',
    ResourcePolicy='string',
    BlockPublicPolicy=True|False
)
Parameters
  • SecretId (string) --

    [REQUIRED]

    Specifies the secret that you want to attach the resource-based policy. You can specify either the ARN or the friendly name of the secret.

    For an ARN, we recommend that you specify a complete ARN rather than a partial ARN.

  • ResourcePolicy (string) --

    [REQUIRED]

    A JSON-formatted string constructed according to the grammar and syntax for an Amazon Web Services resource-based policy. The policy in the string identifies who can access or manage this secret and its versions. For information on how to format a JSON parameter for the various command line tool environments, see Using JSON for Parameters in the CLI User Guide .

  • BlockPublicPolicy (boolean) -- (Optional) If you set the parameter, BlockPublicPolicy to true, then you block resource-based policies that allow broad access to the secret.
Return type

dict

Returns

Response Syntax

{
    'ARN': 'string',
    'Name': 'string'
}

Response Structure

  • (dict) --

    • ARN (string) --

      The ARN of the secret retrieved by the resource-based policy.

    • Name (string) --

      The friendly name of the secret retrieved by the resource-based policy.

Exceptions

  • SecretsManager.Client.exceptions.MalformedPolicyDocumentException
  • SecretsManager.Client.exceptions.ResourceNotFoundException
  • SecretsManager.Client.exceptions.InvalidParameterException
  • SecretsManager.Client.exceptions.InternalServiceError
  • SecretsManager.Client.exceptions.InvalidRequestException
  • SecretsManager.Client.exceptions.PublicPolicyException

Examples

The following example shows how to add a resource-based policy to a secret.

response = client.put_resource_policy(
    ResourcePolicy='{\n"Version":"2012-10-17",\n"Statement":[{\n"Effect":"Allow",\n"Principal":{\n"AWS":"arn:aws:iam::123456789012:root"\n},\n"Action":"secretsmanager:GetSecretValue",\n"Resource":"*"\n}]\n}',
    SecretId='MyTestDatabaseSecret',
)

print(response)

Expected Output:

{
    'ARN': 'arn:aws:secretsmanager:us-west-2:123456789012:secret:MyTestDatabaseSecret-a1b2c3',
    'Name': 'MyTestDatabaseSecret',
    'ResponseMetadata': {
        '...': '...',
    },
}
put_secret_value(**kwargs)

Stores a new encrypted secret value in the specified secret. To do this, the operation creates a new version and attaches it to the secret. The version can contain a new SecretString value or a new SecretBinary value. You can also specify the staging labels that are initially attached to the new version.

We recommend you avoid calling PutSecretValue at a sustained rate of more than once every 10 minutes. When you update the secret value, Secrets Manager creates a new version of the secret. Secrets Manager removes outdated versions when there are more than 100, but it does not remove versions created less than 24 hours ago. If you call PutSecretValue more than once every 10 minutes, you create more versions than Secrets Manager removes, and you will reach the quota for secret versions.

  • If this operation creates the first version for the secret then Secrets Manager automatically attaches the staging label AWSCURRENT to the new version.
  • If you do not specify a value for VersionStages then Secrets Manager automatically moves the staging label AWSCURRENT to this new version.
  • If this operation moves the staging label AWSCURRENT from another version to this version, then Secrets Manager also automatically moves the staging label AWSPREVIOUS to the version that AWSCURRENT was removed from.
  • This operation is idempotent. If a version with a VersionId with the same value as the ClientRequestToken parameter already exists and you specify the same secret data, the operation succeeds but does nothing. However, if the secret data is different, then the operation fails because you cannot modify an existing version; you can only create new ones.

Note

  • If you call an operation to encrypt or decrypt the SecretString or SecretBinary for a secret in the same account as the calling user and that secret doesn't specify a Amazon Web Services KMS encryption key, Secrets Manager uses the account's default Amazon Web Services managed customer master key (CMK) with the alias aws/secretsmanager . If this key doesn't already exist in your account then Secrets Manager creates it for you automatically. All users and roles in the same Amazon Web Services account automatically have access to use the default CMK. Note that if an Secrets Manager API call results in Amazon Web Services creating the account's Amazon Web Services-managed CMK, it can result in a one-time significant delay in returning the result.
  • If the secret resides in a different Amazon Web Services account from the credentials calling an API that requires encryption or decryption of the secret value then you must create and use a custom Amazon Web Services KMS CMK because you can't access the default CMK for the account using credentials from a different Amazon Web Services account. Store the ARN of the CMK in the secret when you create the secret or when you update it by including it in the KMSKeyId . If you call an API that must encrypt or decrypt SecretString or SecretBinary using credentials from a different account then the Amazon Web Services KMS key policy must grant cross-account access to that other account's user or role for both the kms:GenerateDataKey and kms:Decrypt operations.

Minimum permissions

To run this command, you must have the following permissions:

  • secretsmanager:PutSecretValue
  • kms:GenerateDataKey - needed only if you use a customer-managed Amazon Web Services KMS key to encrypt the secret. You do not need this permission to use the account's default Amazon Web Services managed CMK for Secrets Manager.
Related operations
  • To retrieve the encrypted value you store in the version of a secret, use GetSecretValue .
  • To create a secret, use CreateSecret .
  • To get the details for a secret, use DescribeSecret .
  • To list the versions attached to a secret, use ListSecretVersionIds .

See also: AWS API Documentation

Request Syntax

response = client.put_secret_value(
    SecretId='string',
    ClientRequestToken='string',
    SecretBinary=b'bytes',
    SecretString='string',
    VersionStages=[
        'string',
    ]
)
Parameters
  • SecretId (string) --

    [REQUIRED]

    Specifies the secret to which you want to add a new version. You can specify either the Amazon Resource Name (ARN) or the friendly name of the secret. The secret must already exist.

    For an ARN, we recommend that you specify a complete ARN rather than a partial ARN.

  • ClientRequestToken (string) --

    (Optional) Specifies a unique identifier for the new version of the secret.

    Note

    If you use the Amazon Web Services CLI or one of the Amazon Web Services SDK to call this operation, then you can leave this parameter empty. The CLI or SDK generates a random UUID for you and includes that in the request. If you don't use the SDK and instead generate a raw HTTP request to the Secrets Manager service endpoint, then you must generate a ClientRequestToken yourself for new versions and include that value in the request.

    This value helps ensure idempotency. Secrets Manager uses this value to prevent the accidental creation of duplicate versions if there are failures and retries during the Lambda rotation function's processing. We recommend that you generate a UUID-type value to ensure uniqueness within the specified secret.

    • If the ClientRequestToken value isn't already associated with a version of the secret then a new version of the secret is created.
    • If a version with this value already exists and that version's SecretString or SecretBinary values are the same as those in the request then the request is ignored (the operation is idempotent).
    • If a version with this value already exists and the version of the SecretString and SecretBinary values are different from those in the request then the request fails because you cannot modify an existing secret version. You can only create new versions to store new secret values.

    This value becomes the VersionId of the new version.

    This field is autopopulated if not provided.

  • SecretBinary (bytes) --

    (Optional) Specifies binary data that you want to encrypt and store in the new version of the secret. To use this parameter in the command-line tools, we recommend that you store your binary data in a file and then use the appropriate technique for your tool to pass the contents of the file as a parameter. Either SecretBinary or SecretString must have a value, but not both. They cannot both be empty.

    This parameter is not accessible if the secret using the Secrets Manager console.

  • SecretString (string) --

    (Optional) Specifies text data that you want to encrypt and store in this new version of the secret. Either SecretString or SecretBinary must have a value, but not both. They cannot both be empty.

    If you create this secret by using the Secrets Manager console then Secrets Manager puts the protected secret text in only the SecretString parameter. The Secrets Manager console stores the information as a JSON structure of key/value pairs that the default Lambda rotation function knows how to parse.

    For storing multiple values, we recommend that you use a JSON text string argument and specify key/value pairs. For more information, see Specifying parameter values for the Amazon Web Services CLI in the Amazon Web Services CLI User Guide.

  • VersionStages (list) --

    (Optional) Specifies a list of staging labels that are attached to this version of the secret. These staging labels are used to track the versions through the rotation process by the Lambda rotation function.

    A staging label must be unique to a single version of the secret. If you specify a staging label that's already associated with a different version of the same secret then that staging label is automatically removed from the other version and attached to this version.

    If you do not specify a value for VersionStages then Secrets Manager automatically moves the staging label AWSCURRENT to this new version.

    • (string) --
Return type

dict

Returns

Response Syntax

{
    'ARN': 'string',
    'Name': 'string',
    'VersionId': 'string',
    'VersionStages': [
        'string',
    ]
}

Response Structure

  • (dict) --

    • ARN (string) --

      The Amazon Resource Name (ARN) for the secret for which you just created a version.

    • Name (string) --

      The friendly name of the secret for which you just created or updated a version.

    • VersionId (string) --

      The unique identifier of the version of the secret you just created or updated.

    • VersionStages (list) --

      The list of staging labels that are currently attached to this version of the secret. Staging labels are used to track a version as it progresses through the secret rotation process.

      • (string) --

Exceptions

  • SecretsManager.Client.exceptions.InvalidParameterException
  • SecretsManager.Client.exceptions.InvalidRequestException
  • SecretsManager.Client.exceptions.LimitExceededException
  • SecretsManager.Client.exceptions.EncryptionFailure
  • SecretsManager.Client.exceptions.ResourceExistsException
  • SecretsManager.Client.exceptions.ResourceNotFoundException
  • SecretsManager.Client.exceptions.InternalServiceError

Examples

The following example shows how to create a new version of the secret. Alternatively, you can use the update-secret command.

response = client.put_secret_value(
    ClientRequestToken='EXAMPLE2-90ab-cdef-fedc-ba987EXAMPLE',
    SecretId='MyTestDatabaseSecret',
    SecretString='{"username":"david","password":"BnQw!XDWgaEeT9XGTT29"}',
)

print(response)

Expected Output:

{
    'ARN': 'arn:aws:secretsmanager:us-west-2:123456789012:secret:MyTestDatabaseSecret-a1b2c3',
    'Name': 'MyTestDatabaseSecret',
    'VersionId': 'EXAMPLE2-90ab-cdef-fedc-ba987EXAMPLE',
    'VersionStages': [
        'AWSCURRENT',
    ],
    'ResponseMetadata': {
        '...': '...',
    },
}
remove_regions_from_replication(**kwargs)

Remove regions from replication.

See also: AWS API Documentation

Request Syntax

response = client.remove_regions_from_replication(
    SecretId='string',
    RemoveReplicaRegions=[
        'string',
    ]
)
Parameters
  • SecretId (string) --

    [REQUIRED]

    Remove a secret by SecretId from replica Regions.

  • RemoveReplicaRegions (list) --

    [REQUIRED]

    Remove replication from specific Regions.

    • (string) --
Return type

dict

Returns

Response Syntax

{
    'ARN': 'string',
    'ReplicationStatus': [
        {
            'Region': 'string',
            'KmsKeyId': 'string',
            'Status': 'InSync'|'Failed'|'InProgress',
            'StatusMessage': 'string',
            'LastAccessedDate': datetime(2015, 1, 1)
        },
    ]
}

Response Structure

  • (dict) --

    • ARN (string) --

      The secret ARN removed from replication regions.

    • ReplicationStatus (list) --

      Describes the remaining replication status after you remove regions from the replication list.

      • (dict) --

        A replication object consisting of a RegionReplicationStatus object and includes a Region, KMSKeyId, status, and status message.

        • Region (string) --

          The Region where replication occurs.

        • KmsKeyId (string) --

          Can be an ARN , Key ID , or Alias .

        • Status (string) --

          The status can be InProgress , Failed , or InSync .

        • StatusMessage (string) --

          Status message such as "Secret with this name already exists in this region ".

        • LastAccessedDate (datetime) --

          The date that you last accessed the secret in the Region.

Exceptions

  • SecretsManager.Client.exceptions.ResourceNotFoundException
  • SecretsManager.Client.exceptions.InvalidRequestException
  • SecretsManager.Client.exceptions.InvalidParameterException
  • SecretsManager.Client.exceptions.InternalServiceError
replicate_secret_to_regions(**kwargs)

Converts an existing secret to a multi-Region secret and begins replication the secret to a list of new regions.

See also: AWS API Documentation

Request Syntax

response = client.replicate_secret_to_regions(
    SecretId='string',
    AddReplicaRegions=[
        {
            'Region': 'string',
            'KmsKeyId': 'string'
        },
    ],
    ForceOverwriteReplicaSecret=True|False
)
Parameters
  • SecretId (string) --

    [REQUIRED]

    Use the Secret Id to replicate a secret to regions.

  • AddReplicaRegions (list) --

    [REQUIRED]

    Add Regions to replicate the secret.

    • (dict) --

      (Optional) Custom type consisting of a Region (required) and the KmsKeyId which can be an ARN , Key ID , or Alias .

      • Region (string) --

        Describes a single instance of Region objects.

      • KmsKeyId (string) --

        Can be an ARN , Key ID , or Alias .

  • ForceOverwriteReplicaSecret (boolean) -- (Optional) If set, Secrets Manager replication overwrites a secret with the same name in the destination region.
Return type

dict

Returns

Response Syntax

{
    'ARN': 'string',
    'ReplicationStatus': [
        {
            'Region': 'string',
            'KmsKeyId': 'string',
            'Status': 'InSync'|'Failed'|'InProgress',
            'StatusMessage': 'string',
            'LastAccessedDate': datetime(2015, 1, 1)
        },
    ]
}

Response Structure

  • (dict) --

    • ARN (string) --

      Replicate a secret based on the ReplicaRegionType > consisting of a Region(required) and a KMSKeyId (optional) which can be the ARN, KeyID, or Alias.

    • ReplicationStatus (list) --

      Describes the secret replication status as PENDING , SUCCESS or FAIL .

      • (dict) --

        A replication object consisting of a RegionReplicationStatus object and includes a Region, KMSKeyId, status, and status message.

        • Region (string) --

          The Region where replication occurs.

        • KmsKeyId (string) --

          Can be an ARN , Key ID , or Alias .

        • Status (string) --

          The status can be InProgress , Failed , or InSync .

        • StatusMessage (string) --

          Status message such as "Secret with this name already exists in this region ".

        • LastAccessedDate (datetime) --

          The date that you last accessed the secret in the Region.

Exceptions

  • SecretsManager.Client.exceptions.ResourceNotFoundException
  • SecretsManager.Client.exceptions.InvalidRequestException
  • SecretsManager.Client.exceptions.InvalidParameterException
  • SecretsManager.Client.exceptions.InternalServiceError
restore_secret(**kwargs)

Cancels the scheduled deletion of a secret by removing the DeletedDate time stamp. This makes the secret accessible to query once again.

Minimum permissions

To run this command, you must have the following permissions:

  • secretsmanager:RestoreSecret
Related operations
  • To delete a secret, use DeleteSecret .

See also: AWS API Documentation

Request Syntax

response = client.restore_secret(
    SecretId='string'
)
Parameters
SecretId (string) --

[REQUIRED]

Specifies the secret that you want to restore from a previously scheduled deletion. You can specify either the Amazon Resource Name (ARN) or the friendly name of the secret.

For an ARN, we recommend that you specify a complete ARN rather than a partial ARN.

Return type
dict
Returns
Response Syntax
{
    'ARN': 'string',
    'Name': 'string'
}

Response Structure

  • (dict) --
    • ARN (string) --

      The ARN of the secret that was restored.

    • Name (string) --

      The friendly name of the secret that was restored.

Exceptions

  • SecretsManager.Client.exceptions.ResourceNotFoundException
  • SecretsManager.Client.exceptions.InvalidParameterException
  • SecretsManager.Client.exceptions.InvalidRequestException
  • SecretsManager.Client.exceptions.InternalServiceError

Examples

The following example shows how to restore a secret that you previously scheduled for deletion.

response = client.restore_secret(
    SecretId='MyTestDatabaseSecret',
)

print(response)

Expected Output:

{
    'ARN': 'arn:aws:secretsmanager:us-west-2:123456789012:secret:MyTestDatabaseSecret-a1b2c3',
    'Name': 'MyTestDatabaseSecret',
    'ResponseMetadata': {
        '...': '...',
    },
}
rotate_secret(**kwargs)

Configures and starts the asynchronous process of rotating this secret. If you include the configuration parameters, the operation sets those values for the secret and then immediately starts a rotation. If you do not include the configuration parameters, the operation starts a rotation with the values already stored in the secret. After the rotation completes, the protected service and its clients all use the new version of the secret.

This required configuration information includes the ARN of an Amazon Web Services Lambda function and optionally, the time between scheduled rotations. The Lambda rotation function creates a new version of the secret and creates or updates the credentials on the protected service to match. After testing the new credentials, the function marks the new secret with the staging label AWSCURRENT so that your clients all immediately begin to use the new version. For more information about rotating secrets and how to configure a Lambda function to rotate the secrets for your protected service, see Rotating Secrets in Amazon Web Services Secrets Manager in the Amazon Web Services Secrets Manager User Guide .

Secrets Manager schedules the next rotation when the previous one completes. Secrets Manager schedules the date by adding the rotation interval (number of days) to the actual date of the last rotation. The service chooses the hour within that 24-hour date window randomly. The minute is also chosen somewhat randomly, but weighted towards the top of the hour and influenced by a variety of factors that help distribute load.

The rotation function must end with the versions of the secret in one of two states:

  • The AWSPENDING and AWSCURRENT staging labels are attached to the same version of the secret, or
  • The AWSPENDING staging label is not attached to any version of the secret.

If the AWSPENDING staging label is present but not attached to the same version as AWSCURRENT then any later invocation of RotateSecret assumes that a previous rotation request is still in progress and returns an error.

Minimum permissions

To run this command, you must have the following permissions:

  • secretsmanager:RotateSecret
  • lambda:InvokeFunction (on the function specified in the secret's metadata)
Related operations
  • To list the secrets in your account, use ListSecrets .
  • To get the details for a version of a secret, use DescribeSecret .
  • To create a new version of a secret, use CreateSecret .
  • To attach staging labels to or remove staging labels from a version of a secret, use UpdateSecretVersionStage .

See also: AWS API Documentation

Request Syntax

response = client.rotate_secret(
    SecretId='string',
    ClientRequestToken='string',
    RotationLambdaARN='string',
    RotationRules={
        'AutomaticallyAfterDays': 123
    }
)
Parameters
  • SecretId (string) --

    [REQUIRED]

    Specifies the secret that you want to rotate. You can specify either the Amazon Resource Name (ARN) or the friendly name of the secret.

    For an ARN, we recommend that you specify a complete ARN rather than a partial ARN.

  • ClientRequestToken (string) --

    (Optional) Specifies a unique identifier for the new version of the secret that helps ensure idempotency.

    If you use the Amazon Web Services CLI or one of the Amazon Web Services SDK to call this operation, then you can leave this parameter empty. The CLI or SDK generates a random UUID for you and includes that in the request for this parameter. If you don't use the SDK and instead generate a raw HTTP request to the Secrets Manager service endpoint, then you must generate a ClientRequestToken yourself for new versions and include that value in the request.

    You only need to specify your own value if you implement your own retry logic and want to ensure that a given secret is not created twice. We recommend that you generate a UUID-type value to ensure uniqueness within the specified secret.

    Secrets Manager uses this value to prevent the accidental creation of duplicate versions if there are failures and retries during the function's processing. This value becomes the VersionId of the new version.

    This field is autopopulated if not provided.

  • RotationLambdaARN (string) -- (Optional) Specifies the ARN of the Lambda function that can rotate the secret.
  • RotationRules (dict) --

    A structure that defines the rotation configuration for this secret.

    • AutomaticallyAfterDays (integer) --

      Specifies the number of days between automatic scheduled rotations of the secret.

      Secrets Manager schedules the next rotation when the previous one is complete. Secrets Manager schedules the date by adding the rotation interval (number of days) to the actual date of the last rotation. The service chooses the hour within that 24-hour date window randomly. The minute is also chosen somewhat randomly, but weighted towards the top of the hour and influenced by a variety of factors that help distribute load.

Return type

dict

Returns

Response Syntax

{
    'ARN': 'string',
    'Name': 'string',
    'VersionId': 'string'
}

Response Structure

  • (dict) --

    • ARN (string) --

      The ARN of the secret.

    • Name (string) --

      The friendly name of the secret.

    • VersionId (string) --

      The ID of the new version of the secret created by the rotation started by this request.

Exceptions

  • SecretsManager.Client.exceptions.ResourceNotFoundException
  • SecretsManager.Client.exceptions.InvalidParameterException
  • SecretsManager.Client.exceptions.InternalServiceError
  • SecretsManager.Client.exceptions.InvalidRequestException

Examples

The following example configures rotation for a secret by providing the ARN of a Lambda rotation function (which must already exist) and the number of days between rotation. The first rotation happens immediately upon completion of this command. The rotation function runs asynchronously in the background.

response = client.rotate_secret(
    RotationLambdaARN='arn:aws:lambda:us-west-2:123456789012:function:MyTestDatabaseRotationLambda',
    RotationRules={
        'AutomaticallyAfterDays': 30,
    },
    SecretId='MyTestDatabaseSecret',
)

print(response)

Expected Output:

{
    'ARN': 'arn:aws:secretsmanager:us-west-2:123456789012:secret:MyTestDatabaseSecret-a1b2c3',
    'Name': 'MyTestDatabaseSecret',
    'VersionId': 'EXAMPLE2-90ab-cdef-fedc-ba987SECRET2',
    'ResponseMetadata': {
        '...': '...',
    },
}
stop_replication_to_replica(**kwargs)

Removes the secret from replication and promotes the secret to a regional secret in the replica Region.

See also: AWS API Documentation

Request Syntax

response = client.stop_replication_to_replica(
    SecretId='string'
)
Parameters
SecretId (string) --

[REQUIRED]

Response to StopReplicationToReplica of a secret, based on the SecretId .

Return type
dict
Returns
Response Syntax
{
    'ARN': 'string'
}

Response Structure

  • (dict) --
    • ARN (string) --

      Response StopReplicationToReplica of a secret, based on the ARN, .

Exceptions

  • SecretsManager.Client.exceptions.ResourceNotFoundException
  • SecretsManager.Client.exceptions.InvalidRequestException
  • SecretsManager.Client.exceptions.InvalidParameterException
  • SecretsManager.Client.exceptions.InternalServiceError
tag_resource(**kwargs)

Attaches one or more tags, each consisting of a key name and a value, to the specified secret. Tags are part of the secret's overall metadata, and are not associated with any specific version of the secret. This operation only appends tags to the existing list of tags. To remove tags, you must use UntagResource .

The following basic restrictions apply to tags:

  • Maximum number of tags per secret—50
  • Maximum key length—127 Unicode characters in UTF-8
  • Maximum value length—255 Unicode characters in UTF-8
  • Tag keys and values are case sensitive.
  • Do not use the aws: prefix in your tag names or values because Amazon Web Services reserves it for Amazon Web Services use. You can't edit or delete tag names or values with this prefix. Tags with this prefix do not count against your tags per secret limit.
  • If you use your tagging schema across multiple services and resources, remember other services might have restrictions on allowed characters. Generally allowed characters: letters, spaces, and numbers representable in UTF-8, plus the following special characters: + - = . _ : / @.

Warning

If you use tags as part of your security strategy, then adding or removing a tag can change permissions. If successfully completing this operation would result in you losing your permissions for this secret, then the operation is blocked and returns an Access Denied error.

Minimum permissions

To run this command, you must have the following permissions:

  • secretsmanager:TagResource
Related operations
  • To remove one or more tags from the collection attached to a secret, use UntagResource .
  • To view the list of tags attached to a secret, use DescribeSecret .

See also: AWS API Documentation

Request Syntax

response = client.tag_resource(
    SecretId='string',
    Tags=[
        {
            'Key': 'string',
            'Value': 'string'
        },
    ]
)
Parameters
  • SecretId (string) --

    [REQUIRED]

    The identifier for the secret that you want to attach tags to. You can specify either the Amazon Resource Name (ARN) or the friendly name of the secret.

    For an ARN, we recommend that you specify a complete ARN rather than a partial ARN.

  • Tags (list) --

    [REQUIRED]

    The tags to attach to the secret. Each element in the list consists of a Key and a Value .

    This parameter to the API requires a JSON text string argument.

    For storing multiple values, we recommend that you use a JSON text string argument and specify key/value pairs. For more information, see Specifying parameter values for the Amazon Web Services CLI in the Amazon Web Services CLI User Guide.

    • (dict) --

      A structure that contains information about a tag.

      • Key (string) --

        The key identifier, or name, of the tag.

      • Value (string) --

        The string value associated with the key of the tag.

Returns

None

Exceptions

  • SecretsManager.Client.exceptions.ResourceNotFoundException
  • SecretsManager.Client.exceptions.InvalidRequestException
  • SecretsManager.Client.exceptions.InvalidParameterException
  • SecretsManager.Client.exceptions.InternalServiceError

Examples

The following example shows how to attach two tags each with a Key and Value to a secret. There is no output from this API. To see the result, use the DescribeSecret operation.

response = client.tag_resource(
    SecretId='MyExampleSecret',
    Tags=[
        {
            'Key': 'FirstTag',
            'Value': 'SomeValue',
        },
        {
            'Key': 'SecondTag',
            'Value': 'AnotherValue',
        },
    ],
)

print(response)

Expected Output:

{
    'ResponseMetadata': {
        '...': '...',
    },
}
untag_resource(**kwargs)

Removes one or more tags from the specified secret.

This operation is idempotent. If a requested tag is not attached to the secret, no error is returned and the secret metadata is unchanged.

Warning

If you use tags as part of your security strategy, then removing a tag can change permissions. If successfully completing this operation would result in you losing your permissions for this secret, then the operation is blocked and returns an Access Denied error.

Minimum permissions

To run this command, you must have the following permissions:

  • secretsmanager:UntagResource
Related operations
  • To add one or more tags to the collection attached to a secret, use TagResource .
  • To view the list of tags attached to a secret, use DescribeSecret .

See also: AWS API Documentation

Request Syntax

response = client.untag_resource(
    SecretId='string',
    TagKeys=[
        'string',
    ]
)
Parameters
  • SecretId (string) --

    [REQUIRED]

    The identifier for the secret that you want to remove tags from. You can specify either the Amazon Resource Name (ARN) or the friendly name of the secret.

    For an ARN, we recommend that you specify a complete ARN rather than a partial ARN.

  • TagKeys (list) --

    [REQUIRED]

    A list of tag key names to remove from the secret. You don't specify the value. Both the key and its associated value are removed.

    This parameter to the API requires a JSON text string argument.

    For storing multiple values, we recommend that you use a JSON text string argument and specify key/value pairs. For more information, see Specifying parameter values for the Amazon Web Services CLI in the Amazon Web Services CLI User Guide.

    • (string) --
Returns

None

Exceptions

  • SecretsManager.Client.exceptions.ResourceNotFoundException
  • SecretsManager.Client.exceptions.InvalidRequestException
  • SecretsManager.Client.exceptions.InvalidParameterException
  • SecretsManager.Client.exceptions.InternalServiceError

Examples

The following example shows how to remove two tags from a secret's metadata. For each, both the tag and the associated value are removed. There is no output from this API. To see the result, use the DescribeSecret operation.

response = client.untag_resource(
    SecretId='MyTestDatabaseSecret',
    TagKeys=[
        'FirstTag',
        'SecondTag',
    ],
)

print(response)

Expected Output:

{
    'ResponseMetadata': {
        '...': '...',
    },
}
update_secret(**kwargs)

Modifies many of the details of the specified secret.

To change the secret value, you can also use PutSecretValue .

To change the rotation configuration of a secret, use RotateSecret instead.

We recommend you avoid calling UpdateSecret at a sustained rate of more than once every 10 minutes. When you call UpdateSecret to update the secret value, Secrets Manager creates a new version of the secret. Secrets Manager removes outdated versions when there are more than 100, but it does not remove versions created less than 24 hours ago. If you update the secret value more than once every 10 minutes, you create more versions than Secrets Manager removes, and you will reach the quota for secret versions.

Note

The Secrets Manager console uses only the SecretString parameter and therefore limits you to encrypting and storing only a text string. To encrypt and store binary data as part of the version of a secret, you must use either the Amazon Web Services CLI or one of the Amazon Web Services SDKs.

  • If a version with a VersionId with the same value as the ClientRequestToken parameter already exists, the operation results in an error. You cannot modify an existing version, you can only create a new version.
  • If you include SecretString or SecretBinary to create a new secret version, Secrets Manager automatically attaches the staging label AWSCURRENT to the new version.

Note

  • If you call an operation to encrypt or decrypt the SecretString or SecretBinary for a secret in the same account as the calling user and that secret doesn't specify a Amazon Web Services KMS encryption key, Secrets Manager uses the account's default Amazon Web Services managed customer master key (CMK) with the alias aws/secretsmanager . If this key doesn't already exist in your account then Secrets Manager creates it for you automatically. All users and roles in the same Amazon Web Services account automatically have access to use the default CMK. Note that if an Secrets Manager API call results in Amazon Web Services creating the account's Amazon Web Services-managed CMK, it can result in a one-time significant delay in returning the result.
  • If the secret resides in a different Amazon Web Services account from the credentials calling an API that requires encryption or decryption of the secret value then you must create and use a custom Amazon Web Services KMS CMK because you can't access the default CMK for the account using credentials from a different Amazon Web Services account. Store the ARN of the CMK in the secret when you create the secret or when you update it by including it in the KMSKeyId . If you call an API that must encrypt or decrypt SecretString or SecretBinary using credentials from a different account then the Amazon Web Services KMS key policy must grant cross-account access to that other account's user or role for both the kms:GenerateDataKey and kms:Decrypt operations.

Minimum permissions

To run this command, you must have the following permissions:

  • secretsmanager:UpdateSecret
  • kms:GenerateDataKey - needed only if you use a custom Amazon Web Services KMS key to encrypt the secret. You do not need this permission to use the account's Amazon Web Services managed CMK for Secrets Manager.
  • kms:Decrypt - needed only if you use a custom Amazon Web Services KMS key to encrypt the secret. You do not need this permission to use the account's Amazon Web Services managed CMK for Secrets Manager.
Related operations
  • To create a new secret, use CreateSecret .
  • To add only a new version to an existing secret, use PutSecretValue .
  • To get the details for a secret, use DescribeSecret .
  • To list the versions contained in a secret, use ListSecretVersionIds .

See also: AWS API Documentation

Request Syntax

response = client.update_secret(
    SecretId='string',
    ClientRequestToken='string',
    Description='string',
    KmsKeyId='string',
    SecretBinary=b'bytes',
    SecretString='string'
)
Parameters
  • SecretId (string) --

    [REQUIRED]

    Specifies the secret that you want to modify or to which you want to add a new version. You can specify either the Amazon Resource Name (ARN) or the friendly name of the secret.

    For an ARN, we recommend that you specify a complete ARN rather than a partial ARN.

  • ClientRequestToken (string) --

    (Optional) If you want to add a new version to the secret, this parameter specifies a unique identifier for the new version that helps ensure idempotency.

    If you use the Amazon Web Services CLI or one of the Amazon Web Services SDK to call this operation, then you can leave this parameter empty. The CLI or SDK generates a random UUID for you and includes that in the request. If you don't use the SDK and instead generate a raw HTTP request to the Secrets Manager service endpoint, then you must generate a ClientRequestToken yourself for new versions and include that value in the request.

    You typically only need to interact with this value if you implement your own retry logic and want to ensure that a given secret is not created twice. We recommend that you generate a UUID-type value to ensure uniqueness within the specified secret.

    Secrets Manager uses this value to prevent the accidental creation of duplicate versions if there are failures and retries during the Lambda rotation function's processing.

    • If the ClientRequestToken value isn't already associated with a version of the secret then a new version of the secret is created.
    • If a version with this value already exists and that version's SecretString and SecretBinary values are the same as those in the request then the request is ignored (the operation is idempotent).
    • If a version with this value already exists and that version's SecretString and SecretBinary values are different from the request then an error occurs because you cannot modify an existing secret value.

    This value becomes the VersionId of the new version.

    This field is autopopulated if not provided.

  • Description (string) -- (Optional) Specifies an updated user-provided description of the secret.
  • KmsKeyId (string) --

    (Optional) Specifies an updated ARN or alias of the Amazon Web Services KMS customer master key (CMK) that Secrets Manager uses to encrypt the protected text in new versions of this secret as well as any existing versions of this secret that have the staging labels AWSCURRENT, AWSPENDING, or AWSPREVIOUS. For more information about staging labels, see Staging Labels in the Amazon Web Services Secrets Manager User Guide .

    Warning

    You can only use the account's default CMK to encrypt and decrypt if you call this operation using credentials from the same account that owns the secret. If the secret is in a different account, then you must create a custom CMK and provide the ARN of that CMK in this field. The user making the call must have permissions to both the secret and the CMK in their respective accounts.

  • SecretBinary (bytes) --

    (Optional) Specifies updated binary data that you want to encrypt and store in the new version of the secret. To use this parameter in the command-line tools, we recommend that you store your binary data in a file and then use the appropriate technique for your tool to pass the contents of the file as a parameter. Either SecretBinary or SecretString must have a value, but not both. They cannot both be empty.

    This parameter is not accessible using the Secrets Manager console.

  • SecretString (string) --

    (Optional) Specifies updated text data that you want to encrypt and store in this new version of the secret. Either SecretBinary or SecretString must have a value, but not both. They cannot both be empty.

    If you create this secret by using the Secrets Manager console then Secrets Manager puts the protected secret text in only the SecretString parameter. The Secrets Manager console stores the information as a JSON structure of key/value pairs that the default Lambda rotation function knows how to parse.

    For storing multiple values, we recommend that you use a JSON text string argument and specify key/value pairs. For more information, see Specifying parameter values for the Amazon Web Services CLI in the Amazon Web Services CLI User Guide.

Return type

dict

Returns

Response Syntax

{
    'ARN': 'string',
    'Name': 'string',
    'VersionId': 'string'
}

Response Structure

  • (dict) --

    • ARN (string) --

      The ARN of the secret that was updated.

      Note

      Secrets Manager automatically adds several random characters to the name at the end of the ARN when you initially create a secret. This affects only the ARN and not the actual friendly name. This ensures that if you create a new secret with the same name as an old secret that you previously deleted, then users with access to the old secret don't automatically get access to the new secret because the ARNs are different.

    • Name (string) --

      The friendly name of the secret that was updated.

    • VersionId (string) --

      If a new version of the secret was created by this operation, then VersionId contains the unique identifier of the new version.

Exceptions

  • SecretsManager.Client.exceptions.InvalidParameterException
  • SecretsManager.Client.exceptions.InvalidRequestException
  • SecretsManager.Client.exceptions.LimitExceededException
  • SecretsManager.Client.exceptions.EncryptionFailure
  • SecretsManager.Client.exceptions.ResourceExistsException
  • SecretsManager.Client.exceptions.ResourceNotFoundException
  • SecretsManager.Client.exceptions.MalformedPolicyDocumentException
  • SecretsManager.Client.exceptions.InternalServiceError
  • SecretsManager.Client.exceptions.PreconditionNotMetException

Examples

The following example shows how to modify the description of a secret.

response = client.update_secret(
    ClientRequestToken='EXAMPLE1-90ab-cdef-fedc-ba987EXAMPLE',
    Description='This is a new description for the secret.',
    SecretId='MyTestDatabaseSecret',
)

print(response)

Expected Output:

{
    'ARN': 'arn:aws:secretsmanager:us-west-2:123456789012:secret:MyTestDatabaseSecret-a1b2c3',
    'Name': 'MyTestDatabaseSecret',
    'ResponseMetadata': {
        '...': '...',
    },
}

This example shows how to update the KMS customer managed key (CMK) used to encrypt the secret value. The KMS CMK must be in the same region as the secret.

response = client.update_secret(
    KmsKeyId='arn:aws:kms:us-west-2:123456789012:key/EXAMPLE2-90ab-cdef-fedc-ba987EXAMPLE',
    SecretId='MyTestDatabaseSecret',
)

print(response)

Expected Output:

{
    'ARN': 'arn:aws:secretsmanager:us-west-2:123456789012:secret:MyTestDatabaseSecret-a1b2c3',
    'Name': 'MyTestDatabaseSecret',
    'ResponseMetadata': {
        '...': '...',
    },
}

The following example shows how to create a new version of the secret by updating the SecretString field. Alternatively, you can use the put-secret-value operation.

response = client.update_secret(
    SecretId='MyTestDatabaseSecret',
    SecretString='{JSON STRING WITH CREDENTIALS}',
)

print(response)

Expected Output:

{
    'ARN': 'aws:arn:secretsmanager:us-west-2:123456789012:secret:MyTestDatabaseSecret-a1b2c3',
    'Name': 'MyTestDatabaseSecret',
    'VersionId': 'EXAMPLE1-90ab-cdef-fedc-ba987EXAMPLE',
    'ResponseMetadata': {
        '...': '...',
    },
}
update_secret_version_stage(**kwargs)

Modifies the staging labels attached to a version of a secret. Staging labels are used to track a version as it progresses through the secret rotation process. You can attach a staging label to only one version of a secret at a time. If a staging label to be added is already attached to another version, then it is moved--removed from the other version first and then attached to this one. For more information about staging labels, see Staging Labels in the Amazon Web Services Secrets Manager User Guide .

The staging labels that you specify in the VersionStage parameter are added to the existing list of staging labels--they don't replace it.

You can move the AWSCURRENT staging label to this version by including it in this call.

Note

Whenever you move AWSCURRENT , Secrets Manager automatically moves the label AWSPREVIOUS to the version that AWSCURRENT was removed from.

If this action results in the last label being removed from a version, then the version is considered to be 'deprecated' and can be deleted by Secrets Manager.

Minimum permissions

To run this command, you must have the following permissions:

  • secretsmanager:UpdateSecretVersionStage
Related operations
  • To get the list of staging labels that are currently associated with a version of a secret, use `` DescribeSecret `` and examine the SecretVersionsToStages response value.

See also: AWS API Documentation

Request Syntax

response = client.update_secret_version_stage(
    SecretId='string',
    VersionStage='string',
    RemoveFromVersionId='string',
    MoveToVersionId='string'
)
Parameters
  • SecretId (string) --

    [REQUIRED]

    Specifies the secret with the version with the list of staging labels you want to modify. You can specify either the Amazon Resource Name (ARN) or the friendly name of the secret.

    For an ARN, we recommend that you specify a complete ARN rather than a partial ARN.

  • VersionStage (string) --

    [REQUIRED]

    The staging label to add to this version.

  • RemoveFromVersionId (string) -- Specifies the secret version ID of the version that the staging label is to be removed from. If the staging label you are trying to attach to one version is already attached to a different version, then you must include this parameter and specify the version that the label is to be removed from. If the label is attached and you either do not specify this parameter, or the version ID does not match, then the operation fails.
  • MoveToVersionId (string) --

    (Optional) The secret version ID that you want to add the staging label. If you want to remove a label from a version, then do not specify this parameter.

    If the staging label is already attached to a different version of the secret, then you must also specify the RemoveFromVersionId parameter.

Return type

dict

Returns

Response Syntax

{
    'ARN': 'string',
    'Name': 'string'
}

Response Structure

  • (dict) --

    • ARN (string) --

      The ARN of the secret with the modified staging label.

    • Name (string) --

      The friendly name of the secret with the modified staging label.

Exceptions

  • SecretsManager.Client.exceptions.ResourceNotFoundException
  • SecretsManager.Client.exceptions.InvalidParameterException
  • SecretsManager.Client.exceptions.InvalidRequestException
  • SecretsManager.Client.exceptions.LimitExceededException
  • SecretsManager.Client.exceptions.InternalServiceError

Examples

The following example shows you how to add a staging label to a version of a secret. You can review the results by running the operation ListSecretVersionIds and viewing the VersionStages response field for the affected version.

response = client.update_secret_version_stage(
    MoveToVersionId='EXAMPLE1-90ab-cdef-fedc-ba987SECRET1',
    SecretId='MyTestDatabaseSecret',
    VersionStage='STAGINGLABEL1',
)

print(response)

Expected Output:

{
    'ARN': 'arn:aws:secretsmanager:us-west-2:123456789012:secret:MyTestDatabaseSecret-a1b2c3',
    'Name': 'MyTestDatabaseSecret',
    'ResponseMetadata': {
        '...': '...',
    },
}

The following example shows you how to delete a staging label that is attached to a version of a secret. You can review the results by running the operation ListSecretVersionIds and viewing the VersionStages response field for the affected version.

response = client.update_secret_version_stage(
    RemoveFromVersionId='EXAMPLE1-90ab-cdef-fedc-ba987SECRET1',
    SecretId='MyTestDatabaseSecret',
    VersionStage='STAGINGLABEL1',
)

print(response)

Expected Output:

{
    'ARN': 'arn:aws:secretsmanager:us-west-2:123456789012:secret:MyTestDatabaseSecret-a1b2c3',
    'Name': 'MyTestDatabaseSecret',
    'ResponseMetadata': {
        '...': '...',
    },
}

The following example shows you how to move a staging label that is attached to one version of a secret to a different version. You can review the results by running the operation ListSecretVersionIds and viewing the VersionStages response field for the affected version.

response = client.update_secret_version_stage(
    MoveToVersionId='EXAMPLE2-90ab-cdef-fedc-ba987SECRET2',
    RemoveFromVersionId='EXAMPLE1-90ab-cdef-fedc-ba987SECRET1',
    SecretId='MyTestDatabaseSecret',
    VersionStage='AWSCURRENT',
)

print(response)

Expected Output:

{
    'ARN': 'arn:aws:secretsmanager:us-west-2:123456789012:secret:MyTestDatabaseSecret-a1b2c3',
    'Name': 'MyTestDatabaseSecret',
    'ResponseMetadata': {
        '...': '...',
    },
}
validate_resource_policy(**kwargs)

Validates that the resource policy does not grant a wide range of IAM principals access to your secret. The JSON request string input and response output displays formatted code with white space and line breaks for better readability. Submit your input as a single line JSON string. A resource-based policy is optional for secrets.

The API performs three checks when validating the secret:

  • Sends a call to Zelkova , an automated reasoning engine, to ensure your Resource Policy does not allow broad access to your secret.
  • Checks for correct syntax in a policy.
  • Verifies the policy does not lock out a caller.
Minimum Permissions

You must have the permissions required to access the following APIs:

  • secretsmanager:PutResourcePolicy
  • secretsmanager:ValidateResourcePolicy

See also: AWS API Documentation

Request Syntax

response = client.validate_resource_policy(
    SecretId='string',
    ResourcePolicy='string'
)
Parameters
  • SecretId (string) --

    (Optional) The identifier of the secret with the resource-based policy you want to validate. You can specify either the Amazon Resource Name (ARN) or the friendly name of the secret.

    For an ARN, we recommend that you specify a complete ARN rather than a partial ARN.

  • ResourcePolicy (string) --

    [REQUIRED]

    A JSON-formatted string constructed according to the grammar and syntax for an Amazon Web Services resource-based policy. The policy in the string identifies who can access or manage this secret and its versions. For information on how to format a JSON parameter for the various command line tool environments, see Using JSON for Parameters in the CLI User Guide .publi

Return type

dict

Returns

Response Syntax

{
    'PolicyValidationPassed': True|False,
    'ValidationErrors': [
        {
            'CheckName': 'string',
            'ErrorMessage': 'string'
        },
    ]
}

Response Structure

  • (dict) --

    • PolicyValidationPassed (boolean) --

      Returns a message stating that your Reource Policy passed validation.

    • ValidationErrors (list) --

      Returns an error message if your policy doesn't pass validatation.

      • (dict) --

        Displays errors that occurred during validation of the resource policy.

        • CheckName (string) --

          Checks the name of the policy.

        • ErrorMessage (string) --

          Displays error messages if validation encounters problems during validation of the resource policy.

Exceptions

  • SecretsManager.Client.exceptions.MalformedPolicyDocumentException
  • SecretsManager.Client.exceptions.ResourceNotFoundException
  • SecretsManager.Client.exceptions.InvalidParameterException
  • SecretsManager.Client.exceptions.InternalServiceError
  • SecretsManager.Client.exceptions.InvalidRequestException

Paginators

The available paginators are:

class SecretsManager.Paginator.ListSecrets
paginator = client.get_paginator('list_secrets')
paginate(**kwargs)

Creates an iterator that will paginate through responses from SecretsManager.Client.list_secrets().

See also: AWS API Documentation

Request Syntax

response_iterator = paginator.paginate(
    Filters=[
        {
            'Key': 'description'|'name'|'tag-key'|'tag-value'|'primary-region'|'all',
            'Values': [
                'string',
            ]
        },
    ],
    SortOrder='asc'|'desc',
    PaginationConfig={
        'MaxItems': 123,
        'PageSize': 123,
        'StartingToken': 'string'
    }
)
Parameters
  • Filters (list) --

    Lists the secret request filters.

    • (dict) --

      Allows you to add filters when you use the search function in Secrets Manager.

      • Key (string) --

        Filters your list of secrets by a specific key.

      • Values (list) --

        Filters your list of secrets by a specific value.

        You can prefix your search value with an exclamation mark (! ) in order to perform negation filters.

        • (string) --
  • SortOrder (string) -- Lists secrets in the requested order.
  • PaginationConfig (dict) --

    A dictionary that provides parameters to control pagination.

    • MaxItems (integer) --

      The total number of items to return. If the total number of items available is more than the value specified in max-items then a NextToken will be provided in the output that you can use to resume pagination.

    • PageSize (integer) --

      The size of each page.

    • StartingToken (string) --

      A token to specify where to start paginating. This is the NextToken from a previous response.

Return type

dict

Returns

Response Syntax

{
    'SecretList': [
        {
            'ARN': 'string',
            'Name': 'string',
            'Description': 'string',
            'KmsKeyId': 'string',
            'RotationEnabled': True|False,
            'RotationLambdaARN': 'string',
            'RotationRules': {
                'AutomaticallyAfterDays': 123
            },
            'LastRotatedDate': datetime(2015, 1, 1),
            'LastChangedDate': datetime(2015, 1, 1),
            'LastAccessedDate': datetime(2015, 1, 1),
            'DeletedDate': datetime(2015, 1, 1),
            'Tags': [
                {
                    'Key': 'string',
                    'Value': 'string'
                },
            ],
            'SecretVersionsToStages': {
                'string': [
                    'string',
                ]
            },
            'OwningService': 'string',
            'CreatedDate': datetime(2015, 1, 1),
            'PrimaryRegion': 'string'
        },
    ],

}

Response Structure

  • (dict) --

    • SecretList (list) --

      A list of the secrets in the account.

      • (dict) --

        A structure that contains the details about a secret. It does not include the encrypted SecretString and SecretBinary values. To get those values, use the GetSecretValue operation.

        • ARN (string) --

          The Amazon Resource Name (ARN) of the secret.

          For more information about ARNs in Secrets Manager, see Policy Resources in the Amazon Web Services Secrets Manager User Guide .

        • Name (string) --

          The friendly name of the secret. You can use forward slashes in the name to represent a path hierarchy. For example, /prod/databases/dbserver1 could represent the secret for a server named dbserver1 in the folder databases in the folder prod .

        • Description (string) --

          The user-provided description of the secret.

        • KmsKeyId (string) --

          The ARN or alias of the Amazon Web Services KMS customer master key (CMK) used to encrypt the SecretString and SecretBinary fields in each version of the secret. If you don't provide a key, then Secrets Manager defaults to encrypting the secret fields with the default KMS CMK, the key named awssecretsmanager , for this account.

        • RotationEnabled (boolean) --

          Indicates whether automatic, scheduled rotation is enabled for this secret.

        • RotationLambdaARN (string) --

          The ARN of an Amazon Web Services Lambda function invoked by Secrets Manager to rotate and expire the secret either automatically per the schedule or manually by a call to RotateSecret .

        • RotationRules (dict) --

          A structure that defines the rotation configuration for the secret.

          • AutomaticallyAfterDays (integer) --

            Specifies the number of days between automatic scheduled rotations of the secret.

            Secrets Manager schedules the next rotation when the previous one is complete. Secrets Manager schedules the date by adding the rotation interval (number of days) to the actual date of the last rotation. The service chooses the hour within that 24-hour date window randomly. The minute is also chosen somewhat randomly, but weighted towards the top of the hour and influenced by a variety of factors that help distribute load.

        • LastRotatedDate (datetime) --

          The most recent date and time that the Secrets Manager rotation process was successfully completed. This value is null if the secret hasn't ever rotated.

        • LastChangedDate (datetime) --

          The last date and time that this secret was modified in any way.

        • LastAccessedDate (datetime) --

          The last date that this secret was accessed. This value is truncated to midnight of the date and therefore shows only the date, not the time.

        • DeletedDate (datetime) --

          The date and time the deletion of the secret occurred. Not present on active secrets. The secret can be recovered until the number of days in the recovery window has passed, as specified in the RecoveryWindowInDays parameter of the DeleteSecret operation.

        • Tags (list) --

          The list of user-defined tags associated with the secret. To add tags to a secret, use TagResource . To remove tags, use UntagResource .

          • (dict) --

            A structure that contains information about a tag.

            • Key (string) --

              The key identifier, or name, of the tag.

            • Value (string) --

              The string value associated with the key of the tag.

        • SecretVersionsToStages (dict) --

          A list of all of the currently assigned SecretVersionStage staging labels and the SecretVersionId attached to each one. Staging labels are used to keep track of the different versions during the rotation process.

          Note

          A version that does not have any SecretVersionStage is considered deprecated and subject to deletion. Such versions are not included in this list.

          • (string) --
            • (list) --
              • (string) --
        • OwningService (string) --

          Returns the name of the service that created the secret.

        • CreatedDate (datetime) --

          The date and time when a secret was created.

        • PrimaryRegion (string) --

          The Region where Secrets Manager originated the secret.