如何通过CloudFormation为SSM参数存储自动生成字符串值?
SSM参数存储生成随机字符串的CloudFormation实现
AWS::SSM::Parameter没有像AWS::SecretsManager::Secret那样内置的GenerateSecretString属性,无法直接通过自身配置生成随机值。要实现这个需求,你可以通过CloudFormation自定义资源结合Lambda函数来完成,具体方案如下:
实现步骤
- 创建一个Lambda函数,负责生成符合要求的随机字符串
- 通过CloudFormation自定义资源调用该Lambda函数,获取生成的随机值
- 将随机值传递给
AWS::SSM::Parameter的Value属性
示例CloudFormation模板
Resources: # 生成随机字符串的Lambda函数 RandomStringGenerator: Type: AWS::Lambda::Function Properties: Runtime: python3.12 Handler: index.lambda_handler Code: ZipFile: | import json import random import string import cfnresponse def lambda_handler(event, context): try: # 自定义随机字符串的字符集和长度 char_pool = string.ascii_letters + string.digits + "!@#$%^&*" random_value = ''.join(random.choice(char_pool) for _ in range(20)) if event['RequestType'] in ['Create', 'Update']: cfnresponse.send(event, context, cfnresponse.SUCCESS, {'RandomValue': random_value}) else: cfnresponse.send(event, context, cfnresponse.SUCCESS, {}) except Exception as e: cfnresponse.send(event, context, cfnresponse.FAILED, {'Error': str(e)}) Role: !GetAtt LambdaExecutionRole.Arn # Lambda执行角色,赋予必要的日志权限 LambdaExecutionRole: Type: AWS::IAM::Role Properties: AssumeRolePolicyDocument: Version: '2012-10-17' Statement: - Effect: Allow Principal: Service: lambda.amazonaws.com Action: sts:AssumeRole Policies: - PolicyName: LambdaLogAccess PolicyDocument: Version: '2012-10-17' Statement: - Effect: Allow Action: - logs:CreateLogGroup - logs:CreateLogStream - logs:PutLogEvents Resource: arn:aws:logs:*:*:* # 自定义资源,调用Lambda获取随机值 RandomValueResource: Type: AWS::CloudFormation::CustomResource Properties: ServiceToken: !GetAtt RandomStringGenerator.Arn # 目标SSM参数,使用生成的随机值 MySecureSSMParam: Type: AWS::SSM::Parameter Properties: Name: /my-app/secure-random-param Type: SecureString Value: !GetAtt RandomValueResource.RandomValue
说明
- 你可以修改Lambda代码中的
char_pool和长度参数,调整随机字符串的复杂度和长度 - 如果需要更复杂的生成规则(比如符合特定密码策略),可以在Lambda函数中添加对应的校验逻辑
- 自定义资源会在栈创建或更新时重新生成随机值,若需要固定值,可调整Lambda的逻辑(比如仅在创建时生成)
内容的提问来源于stack exchange,提问作者Joey Yi Zhao
相关产品推荐
相关产品推荐

