Auto aprovisionamiento y desa aprovisionamiento de lambdas aws

Auto aprovisionamiento y desa aprovisionamiento de lambdas automáticamente.

Unos de los principales problemas que se tiene con lambdas aprovisionadas es su alto costo el cual podría llegar a ser demasiado alto.

El el post anterior les mostré como se proporcionaba con ApplicationAutoScaling de amazon

Provisioned Concurrency for Lambda Functions
Aprovisiona funciones lambdas con políticas de escalado según la concurrencia en aws.

hay una sesión de AWS::ApplicationAutoScaling::ScalableTarget el cual se llama  ScheduledActions, el cual nos permite ejecutar acciones automáticas cada cierto tiempo y modificar nuestro aprovisionamiento, por ejemplo un aprovisionamiento como una desaprovechamiento después de cierta hora.

  ..............
  
   ScheduledActions:                                  
        - ScalableTargetAction:
            MinCapacity: 5
            MaxCapacity: 5
          Schedule: 'cron(0 30 17 * * ?)'
          #Schedule: rate(10 minutes)
          ScheduledActionName: scale-out
          Timezone: "America/Bogota"
        - ScalableTargetAction:
            MinCapacity: 0
            MaxCapacity: 0
          Schedule: 'cron(0 50 7 * * ?)'
          #Schedule: rate(5 minutes)
          ScheduledActionName: scale-in
          Timezone: "America/Bogota"
          
  ..................

pueden consultar la información oficial en https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-applicationautoscaling-scalabletarget-scheduledaction.html

Ejemplo de template Cloudformation:

AWSTemplateFormatVersion: '2010-09-09'
Transform: 'AWS::Serverless-2016-10-31'
Description: Escalin api 


Parameters: 
  LambdaFunction:
    Type: String
    Default: "CreateOrder"
  


Resources:
  lambdaByScalableTarget:
    Type: AWS::ApplicationAutoScaling::ScalableTarget
    Condition: CognitoLambdaTriggerActivateAutoscaling
    Properties:
      MaxCapacity: 0
      MinCapacity: 0
      ResourceId: !Sub function:${LambdaFunction}:production # You need to specify an alis or version here
      RoleARN: !Sub arn:aws:iam::${AWS::AccountId}:role/aws-service-role/lambda.application-autoscaling.amazonaws.com/AWSServiceRoleForApplicationAutoScaling_LambdaConcurrency
      ScalableDimension: lambda:function:ProvisionedConcurrency
      ServiceNamespace: lambda
      ScheduledActions:                                  
        - ScalableTargetAction:
            MinCapacity: 5
            MaxCapacity: 5
          Schedule: 'cron(0 30 17 * * ?)'
          #Schedule: rate(10 minutes)
          ScheduledActionName: scale-out
          Timezone: "America/Bogota"
        - ScalableTargetAction:
            MinCapacity: 0
            MaxCapacity: 0
          Schedule: 'cron(0 50 7 * * ?)'
          #Schedule: rate(5 minutes)
          ScheduledActionName: scale-in
          Timezone: "America/Bogota"
      SuspendedState:
        DynamicScalingInSuspended: false
        DynamicScalingOutSuspended: false
        ScheduledScalingSuspended: false

  lambdaTargetTrackingScalingPolicy:
    Type: AWS::ApplicationAutoScaling::ScalingPolicy
    Properties:
      PolicyName: utilization
      PolicyType: TargetTrackingScaling
      ScalingTargetId: !Ref TriggerByScalableTarget
      TargetTrackingScalingPolicyConfiguration:
        TargetValue: 0.7
        PredefinedMetricSpecification:
          PredefinedMetricType: LambdaProvisionedConcurrencyUtilization

para ver las actividades que se han ejecutado en las lambda

aws application-autoscaling describe-scaling-activities \
--service-namespace lambda \
--scalable-dimension lambda:function:ProvisionedConcurrency \
--resource-id function:CreateOrder:prod
{
    "ScalingActivities": [
        {
            "ActivityId": "6d2bf4ed-6eb5-4218-b4bb-f81fe6d7446e",
            "ServiceNamespace": "lambda",
            "ResourceId": "function:CreateOrder:prod",
            "ScalableDimension": "lambda:function:ProvisionedConcurrency",
            "Description": "Setting desired concurrency to 0.",
            "Cause": "maximum capacity was set to 0",
            "StartTime": 1596374119.716,
            "EndTime": 1596374155.789,
            "StatusCode": "Successful",
            "StatusMessage": "Successfully set desired concurrency to 0. Change successfully fulfilled by lambda."
        },
        {
            "ActivityId": "2ea46a62-2dbe-4576-aa42-0675b6448f0a",
            "ServiceNamespace": "lambda",
            "ResourceId": "function:CreateOrder:prod",
            "ScalableDimension": "lambda:function:ProvisionedConcurrency",
            "Description": "Setting min capacity to 0 and max capacity to 0",
            "Cause": "scheduled action name scale-in was triggered",
            "StartTime": 1596374119.415,
            "EndTime": 1596374119.431,
            "StatusCode": "Successful",
            "StatusMessage": "Successfully set min capacity to 0 and max capacity to 0"
        },
----------------------------
output

happy code .

Referencia:

Scheduling AWS Lambda Provisioned Concurrency for recurring peak usage | Amazon Web Services
This post is contributed by Jerome Van Der Linden, AWS Solutions Architect Concurrency of an AWS Lambda function is the number of requests it can handle at any given time. This metric is the average number of requests per second multiplied by the average duration in seconds. For example, if a Lambda…
AWS::AutoScaling::ScheduledAction - AWS CloudFormation
Use the AWS CloudFormation AWS::AutoScaling::ScheduledAction resource for AutoScaling.