In CloudFormation, how do I target a Lambda alias in Events::Rule

Viewed 1024

I'm trying to trigger a Lambda:alias (the alias is key here) on a schedule. The following code errors out with

"SampleLambdaLiveAlias is not valid. Reason: Provided Arn is not in correct format. (Service: AmazonCloudWatchEvents; Status Code: 400; Error Code: ValidationException;"

How do I properly target the lambda:alias in CloudFormation? I've tried !Ref, !Sub and just the logical name.

My custom-resource approach to retrieving the latest lambda version appears to be a necessary evil of setting up the "live" alias because AWS maintains old lambda versions, even after you delete the lambda and stack AND a valid version is required for a new alias. If anyone knows a more elegant approach to that problem, please see: how-to-use-sam-deploy-to-get-a-lambda-with-autopublishalias-and-additional-alises

SampleLambdaFunction:
    Type: AWS::Serverless::Function
    Properties:
        FunctionName: SampleLambda
        AutoPublishAlias: staging
        CodeUri: src/
        Handler: SampleLambda.handler
        MemorySize: 512
        Runtime: nodejs12.x
        Role: !GetAtt SampleLambdaRole.Arn
SampleLambdaLiveAlias:
    Type: AWS::Lambda::Alias
    Properties:
        FunctionName: !Ref SampleLambdaFunction
        FunctionVersion: !GetAtt SampleLambdaGetMaxVersionFunction.version
        Name: live
SampleLambdaFunctionScheduledEvent:
    Type: AWS::Events::Rule
    Properties:
        State: ENABLED
        ScheduleExpression: rate(1 minute) # same as cron(0/1 * * * ? *)
        Description: Run SampleLambdaFunction once every 5 minutes.
        Targets:
        - Id: EventSampleLambda
            Arn: SampleLambdaLiveAlias
1 Answers

Your error is in the last line of the piece of configuration you shared. In order to get the resource ARN you need to use Ref intrinsic function such as, !Ref SampleLambdaLiveAlias:

SampleLambdaFunctionScheduledEvent:
    Type: AWS::Events::Rule
    Properties:
        State: ENABLED
        ScheduleExpression: rate(1 minute) # same as cron(0/1 * * * ? *)
        Description: Run SampleLambdaFunction once every 5 minutes.
        Targets:
        - Id: EventSampleLambda
            Arn: !Ref SampleLambdaLiveAlias

Be aware that Ref intrinsic function may return different things for different types of resources. For Lambda alias it returns the ARN, just what you need.

You can check the official documentation for more detail.

Related