Sometimes its necessary to generate random passwords inside a CloudFormation template for instance to secure internet facing applications running on an EC2 or ECS instance. To achieve this you have the possibility to let the user of your Cloud Formation template insert passwords as parameters during the stack creation.
In the following, I will give an example of how to generate passwords in an AWS CloudFormation Template using a Node.js Lambda Function and Custom Resources.
We create a Custom CloudFormation Resource and pass a previously created Lambda function as the ServiceToken property. Now on every CloudFormation event (e.g. Create / Update / Delete) on the SampleString resource, the Lambda function will be called. The call contains a so-called ResponseUrl where the Lambda function shall response to. If you understood this procedure the template is really easy to understand. After the creation of the Custom Resource is complete you can use the data stored inside using Fn:GetAtt.
Using the Length property in the Custom Resource you can adjust the password length.
Note: The current version of the script generates a new random password if you performing a stack update which directly involves the Custom Resource (means if you change any parameter or property attached to the Custom Resource). To avoid this you could do a workaround like storing the password in an environment variable of the lambda function and resend it on an update. But normally updates on a custom resource this simple should not happen.
Inside the AWS Console go to CloudFormation and deploy the example-template.yml. After the stack creation is complete navigate to the Outputs tab and look for the generated password.
AWS Console CloudFormation
Rudimentary based on https://github.com/sophos/cloudformation-random-string example implemented in python.