AWSTemplateFormatVersion: 2010-09-09
Description: Create an Lambda Function that will be used to report the output of this stack back to Clazar.

Parameters:
  ClazarReporterFunctionName:
    Type: String
  ClazarReporterFunctionRoleName:
    Type: String

Resources:
  ClazarReporterFunctionRole:
    Type: AWS::IAM::Role
    Properties:
      RoleName: !Ref ClazarReporterFunctionRoleName
      Description: An execution role for the ClazarReporterFunction
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Principal:
              Service:
                - lambda.amazonaws.com
            Action:
              - sts:AssumeRole
      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole

  ClazarReporterFunction:
    Type: AWS::Lambda::Function
    Properties:
      FunctionName: !Ref ClazarReporterFunctionName
      Description: This lambda function will call Clazar's API with the stack's output
      Handler: index.handler
      Runtime: python3.14
      Role: !GetAtt ClazarReporterFunctionRole.Arn
      Timeout: 10
      Code:
        ZipFile: |
          import json
          import urllib3
          import cfnresponse

          SUCCESS_STATUS = {200, 201}
          http = urllib3.PoolManager()
          
          print('Entered ClazarReporterFunction')

          def handler(event, context):
              # create dict of event object if it isn't serialized
              if type(event) == 'str':
                  event = json.loads(event)
          
              endpoint = event.get("ResourceProperties").get("Endpoint")
              print('Clazar API Endpoint:', endpoint)
              
              if (event.get('RequestType') == 'Delete'):
                  print("Received delete event", event)
                  # For Delete requests, immediately send a SUCCESS response. 
                  # This does not delete the resource ARNs saved in our models. 
                  # Internal status checks would handle this error.
                  
                  cfnresponse.send(event, context, cfnresponse.SUCCESS, {"succeeded ": True})
              
              elif (event.get('RequestType') == 'Create'):
                  print("Received create event", event)
                  data = event.get('ResourceProperties')
                  response = http.request('POST',
                                            endpoint,
                                            body = json.dumps(data),
                                            headers = {'Content-Type': 'application/json'},
                                          )
                  print('Clazar API Endpoint response:', response)
                  if (response is None or response.status not in SUCCESS_STATUS):
                      cfnresponse.send(event, context, cfnresponse.FAILED, {"succeeded ": False})
                  else:
                      cfnresponse.send(event, context, cfnresponse.SUCCESS, {"succeeded ": True})
              
              # Updating the stack
              else:
                  print("Received update event", event)
                  cfnresponse.send(event, context, cfnresponse.FAILED, {"succeeded ": False})

Outputs:
  ClazarReporterFunctionArn:
    Description: ARN of the stack output reporter function
    Value: !GetAtt ClazarReporterFunction.Arn
