0

Let's say I have a scheduled function declared in a SAM template.yaml

  myScheduledFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: ./bin
      Handler: myScheduledFunction
      Policies:
        - AWSLambdaBasicExecutionRole
      Events:
        CloudwatchEvents:
          Type: Schedule
          Properties:
            Schedule: rate(1 minute)
            Enabled: true

and then I have another function that enable/disable the scheduled rule

myFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: ./bin
      Handler: myFunction
      Environment:
        Variables:
          RULE_NAME: !Ref MyRuleName
      Policies:
        - AWSLambdaBasicExecutionRole
        - EventBridgePutEventsPolicy:
            EventBusName: default
      Events:
        SomeEvent: ...

Now, how can I reference the rule name in environment variable RULE_NAME: !Ref MyRuleName? It is possible to do it in SAM? Maybe using something like !GetAtt myScheduledFunction.RuleName? I couldn't find anything regarding this and I know that there is a way to do it in Cloudformation, but I would know if it is possible in SAM as well, thanks.

Matteo
  • 2,256
  • 26
  • 42

1 Answers1

1

I don't think this is possible to retrieve with the template as written. A work around would be to create the CloudWatch rule as a top-level resource instead of creating it in the Events property.

For example:

myScheduledFunction:
  Type: AWS::Serverless::Function
  Properties:
    CodeUri: ./bin
    Handler: myScheduledFunction
    Policies:
      - AWSLambdaBasicExecutionRole

myRule:
  Type: AWS::Events::Rule
  Properties: 
    Description: "ScheduledRule"
    ScheduleExpression: "rate(1 minutes)"
    State: "ENABLED"
    Targets: 
      - Arn: 
          Fn::GetAtt: 
            - "myScheduledFunction"
            - "Arn"
PermissionForEventsToInvokeLambda: 
  Type: AWS::Lambda::Permission
  Properties: 
    FunctionName: 
      Ref: "myScheduledFunction"
    Action: "lambda:InvokeFunction"
    Principal: "events.amazonaws.com"
    SourceArn: 
      Fn::GetAtt: 
        - "myRule"
        - "Arn"

myFunction:
  Type: AWS::Serverless::Function
  Properties:
    CodeUri: ./bin
    Handler: myFunction
    Environment:
      Variables:
        RULE_NAME: !Ref myRule
    Policies:
      - AWSLambdaBasicExecutionRole
      - EventBridgePutEventsPolicy:
          EventBusName: default
    Events:
      SomeEvent: ...

This code snippet for the rule/permission was taken from the Cloudwatch Rule cloudformation documentation.

JD D
  • 7,398
  • 2
  • 34
  • 53