Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0613· OpenAIAi2 WildChat-4.8M (AI2)

I'm writing Amazon CloudFormation code to create one Lambda function with EventBridge…

  1. User

    I'm writing Amazon CloudFormation code to create one Lambda function with EventBridge trigger. This trigger can timely start this Lambda function automatically. Please provide sample code

  2. Assistant

    Sure! Here's a sample CloudFormation code that creates a Lambda function and an EventBridge rule to trigger the function every minute:

    Resources:
      MyLambdaFunction:
        Type: AWS::Lambda::Function
        Properties:
          Code:
            ZipFile: |
              const response = {
                statusCode: 200,
                body: JSON.stringify('Hello from Lambda!')
              };
              callback(null, response);
          Handler: index.handler
          Role: !GetAtt MyLambdaFunctionRole.Arn
          Runtime: nodejs14.x
    
      MyLambdaFunctionRole:
        Type: AWS::IAM::Role
        Properties:
          AssumeRolePolicyDocument:
            Version: '2012-10-17'
            Statement:
              - Effect: Allow
                Principal:
                  Service:
                    - lambda.amazonaws.com
                Action: sts:AssumeRole
          Policies:
            - PolicyName: MyLambdaFunctionPolicy
              PolicyDocument:
                Version: '2012-10-17'
                Statement:
                  - Effect: Allow
                    Action:
                      - logs:CreateLogGroup
                      - logs:CreateLogStream
                      - logs:PutLogEvents
                    Resource: !Sub 'arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/lambda/${MyLambdaFunction}'
      
      MyEventBridgeRule:
        Type: AWS::Events::Rule
        Properties:
          EventPattern:
            source:
              - aws.cloudformation
            detail-type:
              - 'CloudFormation Stack Event'
            detail:
              stackName:
                - !Ref AWS::StackName
            detail:
              resourceType:
                - 'AWS::Lambda::Function'
            detail:
              resourceStatus:
                - 'CREATE_COMPLETE'
            detail:
              resourceName:
                - !Ref MyLambdaFunction
          State: ENABLED
          Targets:
            - Arn: !GetAtt MyLambdaFunction.Arn
              Id: 'Target0'
    

    The code creates a Lambda function (MyLambdaFunction) with an IAM role (MyLambdaFunctionRole) that grants necessary permissions for the function to run and log to CloudWatch Logs.

    Additionally, an EventBridge rule (MyEventBridgeRule) is created with an event pattern that matches stack events for the created Lambda function's CREATE_COMPLETE status. This rule triggers the Lambda function through its associated ARN.

    Please note that you may need to adjust the code based on your specific requirements.

  3. User

    Please convert it to Yaml format

  4. Assistant

    Here's the same code, converted to YAML format:

    Resources:
      MyLambdaFunction:
        Type: "AWS::Lambda::Function"
        Properties:
          Code:
            ZipFile: |
              const response = {
                statusCode: 200,
                body: JSON.stringify('Hello from Lambda!')
              };
              callback(null, response);
          Handler: index.handler
          Role: !GetAtt MyLambdaFunctionRole.Arn
          Runtime: nodejs14.x
    
      MyLambdaFunctionRole:
        Type: "AWS::IAM::Role"
        Properties:
          AssumeRolePolicyDocument:
            Version: '2012-10-17'
            Statement:
              - Effect: Allow
                Principal:
                  Service:
                    - "lambda.amazonaws.com"
                Action: "sts:AssumeRole"
          Policies:
            - PolicyName: "MyLambdaFunctionPolicy"
              PolicyDocument:
                Version: '2012-10-17'
                Statement:
                  - Effect: Allow
                    Action:
                      - "logs:CreateLogGroup"
                      - "logs:CreateLogStream"
                      - "logs:PutLogEvents"
                    Resource: !Sub "arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/lambda/${MyLambdaFunction}"
      
      MyEventBridgeRule:
        Type: "AWS::Events::Rule"
        Properties:
          EventPattern:
            source:
              - "aws.cloudformation"
            detail-type:
              - "CloudFormation Stack Event"
            detail:
              stackName:
                - !Ref "AWS::StackName"
            detail:
              resourceType:
                - "AWS::Lambda::Function"
            detail:
              resourceStatus:
                - "CREATE_COMPLETE"
            detail:
              resourceName:
                - !Ref "MyLambdaFunction"
          State: "ENABLED"
          Targets:
            - Arn: !GetAtt MyLambdaFunction.Arn
              Id: "Target0"
    

    The code is now in YAML format, with the resources defined under the Resources section.

  5. User

    Can you understand below code? AWSTemplateFormatVersion: '2010-09-09' Transform: AWS::Serverless-2016-10-31 Description: An AWS Lambda application that calls the Lambda API for Performance Insights metrics in Amazon Aurora. Parameters: TargetMetricNamespace: Type: String Default: /AuroraMonitoringGrafana/PerformanceInsightMetrics Description: Target Amazon CloudWatch namespace where you want to public custom metrics Resources: function: Type: AWS::Serverless::Function Properties: Handler: lambda_function.lambda_handler Runtime: python3.8 CodeUri: s3://aurora-monitoring-grafana-pi-494d34597b3a4e8c/280c1b143b842055b23932598b88bee4 Description: Publish Custom Cloudwatch Metrics for Performance Insights Timeout: 900 Environment: Variables: TargetMetricNamespace: Ref: TargetMetricNamespace Policies: - AWSLambdaBasicExecutionRole - AWSLambda_ReadOnlyAccess - AmazonRDSPerformanceInsightsReadOnly - CloudWatchAgentServerPolicy Tracing: Active Events: Schedule: Type: ScheduleV2 Properties: ScheduleExpression: rate(15 minutes) Name: TestScheduleV2Function Description: Test schedule event State: ENABLED

  6. Assistant

    Yes, I can understand the code you provided. It is written in YAML format and describes a CloudFormation template. Here's a breakdown of its components:

    • AWSTemplateFormatVersion: Specifies the version of the AWS CloudFormation template format.
    • Transform: Specifies the CloudFormation transform to apply. In this case, it is AWS::Serverless-2016-10-31, which enables the use of AWS Serverless Application Model (SAM) syntax.
    • Description: Provides a description of the CloudFormation template.
    • Parameters: Defines input parameters that can be configured when creating a stack from this template.
    • Resources: Defines the AWS resources that are created or managed by this CloudFormation template.

    In the Resources section, there is a single resource named function. It is of type AWS::Serverless::Function, representing an AWS Lambda function. The properties of this function resource are specified, including its handler, runtime, code location, description, timeout, environment variables, policies, tracing configuration, and an event trigger.

    • The Events section configures a scheduled trigger for the Lambda function using the Schedule event type. It will trigger the function with a schedule expression of "rate(15 minutes)".
    • The Properties section under Schedule defines additional properties for the scheduled event, such as its name, description, and state.

    It's important to note that this CloudFormation template relies on the AWS Serverless Application Model (SAM) syntax (Transform: AWS::Serverless-2016-10-31) for some of its resource definitions and syntax.

  7. User

    There is event scheduler with type 'ScheduleV2'. I don't want to use the ScheduleV2, is there any other method to do the same thing?

  8. Assistant

    Yes, if you don't want to use the ScheduleV2 type for scheduling the Lambda function, you can use the EventBridge rule to trigger the function at a specified cron expression. Here's an updated version of the code that uses the EventBridge rule instead:

    Resources:
      function:
        Type: AWS::Serverless::Function
        Properties:
          Handler: lambda_function.lambda_handler
          Runtime: python3.8
          CodeUri: s3://aurora-monitoring-grafana-pi-494d34597b3a4e8c/280c1b143b842055b23932598b88bee4
          Description: Publish Custom CloudWatch Metrics for Performance Insights
          Timeout: 900
          Environment:
            Variables:
              TargetMetricNamespace: !Ref TargetMetricNamespace
          Policies:
            - AWSLambdaBasicExecutionRole
            - AWSLambda_ReadOnlyAccess
            - AmazonRDSPerformanceInsightsReadOnly
            - CloudWatchAgentServerPolicy
          Tracing: Active
    
      ScheduledRule:
        Type: AWS::Events::Rule
        Properties:
          ScheduleExpression: "cron(0/15 * * * ? *)"  # Replace with your desired cron expression
          Targets:
            - Arn: !GetAtt function.Arn
              Id: "Target0"
    

    In this updated code, the Events section is removed from the Lambda function resource. Instead, a separate ScheduledRule resource of type AWS::Events::Rule is added. This allows you to define the schedule using a cron expression in the ScheduleExpression property. In this example, it is set to trigger the function every 15 minutes (cron(0/15 * * * ? *)).

    The Targets section of the ScheduledRule specifies the Lambda function as the target, using its ARN obtained with !GetAtt function.Arn.

    Remember to replace the ScheduleExpression with your desired cron expression that matches your desired schedule.