Use Secrets Manager to generate random password

TOC

Use Secrets Manager to generate random password

Secrets Manager can be used to generate random passwords.

https://docs.aws.amazon.com/secretsmanager/latest/userguide/cfn-example_secret.html

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.

Environment

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

https://github.com/awstut-an-r/awstut-fa/tree/main/126

Explanation of key points of template files

Secrets Manager

Resources:
  Secret:
    Type: AWS::SecretsManager::Secret
    Properties:
      Description: test secret
      GenerateSecretString:
        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

Resources:
  Function:
    Type: AWS::Lambda::Function
    Properties:
      Architectures:
        - !Ref Architecture
      Environment:
        Variables:
          SECRET_ARN: !Ref Secret
      Code:
        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(
              SecretId=secret_arn
            )
            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.

あわせて読みたい
3 parterns to create Lambda with CloudFormation (S3/Inline/Container) 【Creating Lambda with CloudFormation】 When creating a Lambda with CloudFormation, there are three main patterns as follows. Uploading the code to an S3 buc...

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.

Resources:
  FunctionRole:
    Type: AWS::IAM::Role
    DeletionPolicy: Delete
    Properties:
      AssumeRolePolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Action: sts:AssumeRole
            Principal:
              Service:
                - lambda.amazonaws.com
      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
      Policies:
        - PolicyName: GetSecretValuePolicy
          PolicyDocument:
            Version: 2012-10-17
            Statement:
              - Effect: Allow
                Action:
                  - secretsmanager:GetSecretValue
                Resource:
                  - !Ref Secret
Code language: YAML (yaml)

Grant permission to retrieve secret information stored in Secrets Manager.

Architecting

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.

あわせて読みたい
CloudFormation’s nested stack 【How to build an environment with a nested CloudFormation stack】 Examine nested stacks in CloudFormation. CloudFormation allows you to nest stacks. Nested ...

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": [
        "AWSCURRENT"
    ],
    "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.

Summary

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

TOC