Create a Lambda Function

Explanation of the CloudFormation template

  • AWSTemplateFormatVersion: The version of the AWS CloudFormation template format used (2010-09-09).

  • Description: A brief description of the template.

  • Resources: This section defines the resources to create in the CloudFormation stack.

  • LambdaRole: An AWS::IAM::Role resource that defines a role named lambda-role for the Lambda function and attaches the managed policy AWSLambdaExecute (permissions to write logs to Amazon CloudWatch Logs and to read/write objects in Amazon S3).

  • LambdaFunctionDemo: An AWS::Lambda::Function resource that creates the Lambda function named CfnLambdaDemo with runtime python3.14, handler index.handler, 512 MB of memory, a 90-second timeout, and the role above.

  • Outputs: This section defines the output values of the CloudFormation template.

  • LambdaRoleArn: An output value that provides the ARN (Amazon Resource Name) of LambdaRole.

  • LambdaFunctionName: An output value that provides the name of the Lambda function (CfnLambdaDemo).

  • This template creates an IAM role and a Lambda function, and provides output values to use in the next steps or in system configuration.

Deploy the CloudFormation stack

  1. In the VS Code terminal, move to the day-1 folder:

    cd ~/CloudFormation-series/day-1
    

AWS CloudFormation

  1. View the content of lambda.yaml, the template that creates the Lambda function:

    cat lambda.yaml
    

AWS CloudFormation

  1. Create the stack with the following command:

    aws cloudformation create-stack \
     --stack-name cfn-lambda-demo \
     --template-body file://lambda.yaml \
     --capabilities CAPABILITY_NAMED_IAM
    

AWS CloudFormation

  1. Wait for the stack to be created. The wait command returns when the stack reaches the CREATE_COMPLETE status:

    aws cloudformation wait stack-create-complete --stack-name cfn-lambda-demo
    aws cloudformation describe-stacks --stack-name cfn-lambda-demo --query "Stacks[0].StackStatus" --output text
    

AWS CloudFormation

  1. Open the CloudFormation console.
    • Select the cfn-lambda-demo stack.
    • View the Events tab.

AWS CloudFormation

  1. Check the Resources tab, which contains two resources: LambdaFunctionDemo and LambdaRole.

AWS CloudFormation

  1. Check the Outputs tab.

AWS CloudFormation

  1. Open Lambda, where you will see that the CfnLambdaDemo function has been created.

AWS CloudFormation

  1. Choose the CfnLambdaDemo function.
    • Choose the Test tab.

AWS CloudFormation

  1. Choose Create new event.
    • Enter an Event name (for example demo-event).
    • Choose Save.

AWS CloudFormation

  1. Choose Test.
    • The result contains the message Hello lambda cloudformation.
    • You can view the Log output.

AWS CloudFormation