---
AWSTemplateFormatVersion: '2010-09-09'

Description: >
  From the blog post, Visualize your Amazon Lookout for Metrics Anomaly Results, this script will
  create the Lambda Function and its Alert.

Parameters:

  LambdaLayerPandasArn:
    Description: >
      Retrieve the latest pandas layer ARN from https://github.com/keithrozario/Klayers/tree/master/deployments/python3.8.
      Select your region and then choose the latest pandas ARN. You must use the ARN from the same region as your deployment.
    Type: String

Metadata:

  AWS::CloudFormation::Interface:

    ParameterGroups:
    
      - Label: 
          default: "AWS Lambda Layer Configuration"
        Parameters:
          - LambdaLayerPandasArn

    ParameterLabels:

      LambdaLayerPandasArn: 
        default: "The pandas ARN to be included as a Lambda Layer:"
 
Resources:

  L4MLambdaExecutionRole: 
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument: 
        Version: '2012-10-17'
        Statement: 
          - Effect: Allow
            Principal: 
              Service: lambda.amazonaws.com
            Action: sts:AssumeRole
      Path: /
      ManagedPolicyArns:
        - 'arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole'
      Policies: 
        - PolicyName: L4MLambdaAccess
          PolicyDocument: 
            Version: '2012-10-17'
            Statement:
              - Effect: Allow
                Action: lookoutmetrics:DescribeMetricSet
                Resource: 
                  - !ImportValue L4MLiveDetectorArn
                  - !ImportValue L4MDetectorMetricSetArn
              - Effect: Allow
                Action:
                  - s3:ListBucket
                  - s3:GetBucketLocation
                Resource:
                  - Fn::Sub:
                    - 'arn:aws:s3:::${BucketName}'
                    - BucketName: !ImportValue L4MS3BucketName
              - Effect: Allow
                Action:
                  - s3:PutObject
                  - s3:GetObject
                Resource:
                  - Fn::Sub:
                    - 'arn:aws:s3:::${BucketName}/anomalyResults/dimensionContributions/*'
                    - BucketName: !ImportValue L4MS3BucketName
                  - Fn::Sub: 
                    - 'arn:aws:s3:::${BucketName}/anomalyResults/metricValue_AnomalyScore/*'
                    - BucketName: !ImportValue L4MS3BucketName
                  
  L4MLambdaFunction:
    Type: AWS::Lambda::Function
    Properties:
      Handler: 'L4MVersion3/lambda_function.lambda_handler'
      Role: !GetAtt L4MLambdaExecutionRole.Arn
      PackageType: Zip
      Code:
        S3Bucket: !ImportValue L4MS3BucketName
        S3Key: 'lambda-code/L4MVersion3.zip'
      Layers:
        - !Ref LambdaLayerPandasArn
      Runtime: python3.8
      MemorySize: 512
      Timeout: 5
      TracingConfig:
        Mode: Active

  L4MDetectorLambdaAlertRole: 
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument: 
        Version: '2012-10-17'
        Statement: 
          - Effect: Allow
            Principal: 
              Service: lookoutmetrics.amazonaws.com
            Action: sts:AssumeRole
      Path: /
      Policies: 
        - PolicyName: AllowLambdaInvocation
          PolicyDocument: 
            Version: '2012-10-17'
            Statement: 
              - Effect: Allow
                Action: lambda:InvokeFunction
                Resource: !GetAtt L4MLambdaFunction.Arn

  L4MDetectorLambdaAlert:
    Type: AWS::LookoutMetrics::Alert
    Properties:
      Action: 
        LambdaConfiguration: 
          LambdaArn: !GetAtt L4MLambdaFunction.Arn
          RoleArn: !GetAtt L4MDetectorLambdaAlertRole.Arn
      AlertDescription: 'Detector Lambda Alert'
      AlertSensitivityThreshold: 70
      AnomalyDetectorArn: !ImportValue L4MLiveDetectorArn
