Search code examples
javaamazon-web-servicesaws-lambdacronserverless

How to enable/disable the cron of AWS LambdaB from LambdaA


I have a Lambda (LoadFile) that is triggered on an S3 event. This happens once or twice a year.

After the file is loaded, at midnight, the loaded data needs to be activated. There is a lambda (ActivateData) that does that. There is an cron event that will run this lambda at midnight. The event is 'disabled' at creation.

How can the LoadFile lambda 'enable' the cron event for ActivateData lambda once it has loaded the data?

For bonus points how can the ActivateData lambda disable it's own cron event?

I'm specifically interested in doing this in Java.

The SAM template specifies the ActivateData lambda with the following:

  Events:
    ActivateFileDataEvent:
      Type: Schedule
      Properties:
        Schedule: cron(0 0 * * ? *)
        Description: Activates an already loaded file
        Enabled: false

Solution

  • As with most things it is really simple once you figure it out.

    In the SAM:

    • store the name of the event to enable as an environment variable in the Load File Lambda
    • give that lambda the requisite permissions in the policies section.

    Then this piece of code did the trick. The ActivateData lambda will have to be disabled once it has run so that it does not run again every night at midnight.

    AmazonEventBridge eventBridge = AmazonEventBridgeClientBuilder.defaultClient();
    EnableRuleRequest request = new EnableRuleRequest();
    request.setName(System.getenv("ACTIVATE_EVENT_NAME"));
    try {
      EnableRuleResult result = eventBridge.enableRule(request);
    } catch (Throwable t){
      log.error("Something went wrong, event is still disabled.",t);
    }