Use Secrets Manager to generate random password

Use Secrets Manager to generate random password AWS_EN

Use Secrets Manager to generate random password

Secrets Manager can be used to generate random passwords.

Create an AWS Secrets Manager secret with AWS CloudFormation - AWS Secrets Manager
This example creates a secret named CloudFormationCreatedSecret- a1b2c3d4e5f6 . The secret value is the following JSON, with a 32-character password that is gen...

In this page, we will generate a random password using the above page as a reference.
The generated password information is accessed from the AWS CLI and Lambda functions.


Diagram of using Secrets Manager to generate random password

Create a secret in Secrets Manager.

This time, the password is automatically generated when the secret is created.

The generated password is retrieved from the AWS CLI and the Lambda function.
The runtime environment for Lambda functions is Python 3.8.

CloudFormation template files

The above configuration is built with CloudFormation.
The CloudFormation templates are placed at the following URL

awstut-fa/126 at main · awstut-an-r/awstut-fa
Contribute to awstut-an-r/awstut-fa development by creating an account on GitHub.

Explanation of key points of template files

Secrets Manager

    Type: AWS::SecretsManager::Secret
      Description: test secret
        ExcludeCharacters: ""
        ExcludeLowercase: false
        ExcludeNumbers: false
        ExcludePunctuation: false
        ExcludeUppercase: false
        GenerateStringKey: !Ref PasswordKey
        IncludeSpace: false
        PasswordLength: !Ref PasswordLength
        RequireEachIncludedType: true
        SecretStringTemplate: !Sub '{"${PasswordKey}": "hogehoge"}'
      KmsKeyId: alias/aws/secretsmanager
      Name: !Ref Prefix
Code language: YAML (yaml)

The GenerateSecretString property is used to configure settings related to the password to be generated.
In this case, the password will be set under the following conditions

  • Include uppercase and lowercase letters, numbers, and symbols (excluding spaces).
  • The length of the password must be 64 characters.
  • The output should be in the format “{“password”: “[password]”}”.

The format of the password is set by the GenerateStringKey and SecretStringTemplate properties.
Since the former specifies the JSON key, “password” is uniformly specified in the latter.
The JSON value (“hogehoge”) will be replaced with the password string generated later.

Lambda Function

    Type: AWS::Lambda::Function
        - !Ref Architecture
          SECRET_ARN: !Ref Secret
        ZipFile: |
          import boto3
          import json
          import os
          secret_arn = os.environ['SECRET_ARN']
          client = boto3.client('secretsmanager')
          def lambda_handler(event, context):
            response = client.get_secret_value(
            secret_dict = json.loads(response['SecretString'])
            return secret_dict['password']
      FunctionName: !Sub "${Prefix}-function"
      Handler: !Ref Handler
      Runtime: !Ref Runtime
      Role: !GetAtt FunctionRole.Arn
Code language: YAML (yaml)

The code to be executed by the Lambda function in inline format.
For more information, please refer to the following page.

The code is as follows: After creating a client object for the Secrets Manager in boto3, the get_secret_value method is executed to obtain the secret string.

This time, the password information is stored in JSON format, so it is converted to a dictionary type using json.loads, and then the password is accessed.

The following is the IAM role for this function.

    Type: AWS::IAM::Role
    DeletionPolicy: Delete
        Version: 2012-10-17
          - Effect: Allow
            Action: sts:AssumeRole
        - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
        - PolicyName: GetSecretValuePolicy
            Version: 2012-10-17
              - Effect: Allow
                  - secretsmanager:GetSecretValue
                  - !Ref Secret
Code language: YAML (yaml)

Grant permission to retrieve secret information stored in Secrets Manager.


Use CloudFormation to build this environment and check its actual behavior.

Create CloudFormation stacks and check the resources in the stacks

Create CloudFormation stacks.
For information on how to create stacks and check each stack, please refer to the following pages.

After reviewing the resources in each stack, information on the main resources created in this case is as follows

  • Secret name: fa-126
  • Lambda function: fa-126-function

Check various resources from the AWS Management Console.

Check Secrets Manager.

Detail of Secrets Manager 01.

Indeed, a secret is created.
The secret key name is “password” and the secret value is a randomly generated string.

Thus, Secrets Manager can be used to generate random passwords.

Check the Lambda function.

Detail of Lambda 01.

This one is also created successfully.

Operation Check

Accessing the Secrets Manager from the AWS CLI

Now that you are ready, retrieve the secret information stored in the Secrets Manager from the AWS CLI.

$ aws secretsmanager get-secret-value --secret-id fa-126                                                                                           
    "ARN": "arn:aws:secretsmanager:ap-northeast-1:[account-id]:secret:fa-126-b9sPdb",
    "Name": "fa-126",
    "VersionId": "02433ea8-08cd-412e-8717-26bb08eb8f64",
    "SecretString": "{\"password\":\"q8BP.(PO{X2F7D)b&w~@k{\\\"!dAQ8FYsV>iSZR7vaEjz>3r=/CtD5=A+3d_P{0NZ:\"}",
    "VersionStages": [
    "CreatedDate": "2023-04-01T07:43:25.603000+00:00"
Code language: Bash (bash)

I was indeed able to access the secret information from the AWS CLI.

Access to Secrets Manager from Lambda functions

The Lambda function is executed to retrieve the secret information stored in the Secrets Manager.
The following is the result of the execution.

Detail of Lambda 02.

The password string is returned.

Thus, the Secrets Manager can be accessed from the AWS CLI or Lambda functions to obtain secret information.


We used Secrets Manager to generate random passwords.
The generated password information was accessed via AWS CLI and Lambda functions.