Menu
AWS Step Functions
Developer Guide

Creating a Task Timer

In this tutorial, you create an AWS Step Functions state machine that uses an AWS Lambda function to implement a Wait state that sends an Amazon Simple Notification Service notification. A Wait state is a state type that waits for a trigger to perform a single unit of work.

This example simulates a portion of a customer-management system that reminds a customer to get an oil change: The service technician records the time of the last visit and the system executes a timer that triggers a notification six months later.

Step 1: Create an Amazon SNS Topic

  1. Follow the instructions to create a topic in the Amazon Simple Notification Service Developer Guide.

  2. Note the ARN of your Amazon SNS Topic.

Step 2: Creating an IAM Role for Lambda

Both Lambda and Step Functions can execute code and access AWS resources (for example, data stored in Amazon S3 buckets). To maintain security, you must grant Lambda and Step Functions access to these resources.

In the Getting Started tutorial, this is done automatically for Step Functions: An IAM role is created when you create the state machine. However, Lambda requires you to assign an IAM role when you create a Lambda function in the same way Step Functions requires you to assign an IAM role when you create a state machine.

To create a role for Lambda

  1. Log in to the IAM console and choose Roles, Create role.

  2. On the Select type of trusted entity page, under AWS service, select Lambda from the list and then choose Next: Permissions.

    Note

    The role is automatically provided with a trust relationship that allows Lambda to use the role.

  3. On the Attach permissions policy page, type SNS into the filter, choose AmazonSNSFullAccess, and then choose Next: Review.

  4. On the Review page, type SNSToStepFunctions for Role Name and then choose Create role.

The IAM role appears in the list of roles.

Step 3: Creating a Lambda Function

Your Lambda function receives input: the Amazon Resource Name (ARN) of your Amazon SNS topic, the message subject, and the message body. Then, the Lambda function returns the successful scheduling of the notification.

To create the Lambda function

Important

Ensure that your Lambda function is under the same AWS account as your state machine.

  1. Log in to the Lambda console and choose Create a function.

  2. In the Blueprints section, type step-functions into the filter, and then choose the step-functions-send-to-sns blueprint.

  3. In the Basic information section, configure your Lambda function:

    1. For Name, type SendToSNS.

    2. For Role, select Choose an existing role.

    3. For Existing role, select the Lambda role that you created earlier.

      Note

      If the IAM role that you created doesn't appear in the list, the role might still need a few minutes to propagate to Lambda.

  4. The following code is displayed in the Lambda function code pane:

    from __future__ import print_function
    
    import json
    import urllib
    import boto3
    
    print('Loading message function...')
    
    
    def send_to_sns(message, context):
    
        # This function receives JSON input with three fields: the ARN of an SNS topic,
        # a string with the subject of the message, and a string with the body of the message.
        # The message is then sent to the SNS topic.
        #
        # Example:
        #   {
        #       "topic": "arn:aws:sns:us-east-1:123456789012:MySNSTopic",
        #       "subject": "This is the subject of the message.",
        #       "message": "This is the body of the message."
        #   }
    
        sns = boto3.client('sns')
        sns.publish(
            TopicArn=message['topic'],
            Subject=message['subject'],
            Message=message['body']
        )
    
        return ('Sent a message to an Amazon SNS topic.')

    This code assembles a greeting using the message field of the input data. This input data is provided by the topic, subject, and body objects passed into your function. You will add input data for this function later, when you start a new execution. The sns.publish method assembles the notification from your function.

  5. Choose Create function.

    When your Lambda function is created, note its ARN in the upper-right corner of the page. For example:

    arn:aws:lambda:us-east-1:123456789012:function:SendToSNS

Step 4: Testing the Lambda Function

Test your Lambda function to see it in operation.

To test your Lambda function

  1. On the SendToSNS page, choose Test.

  2. On the Configure test event dialog box, type SendToSNS for Event name.

  3. In the Input test event dialog box, replace the example data with the following, using the ARN of the Amazon SNS topic that you created earlier in the topic field:

    Copy
    { "topic": "arn:aws:sns:us-east-1:123456789012:OilChange", "subject": "Time for your oil change!", "body": "Dear Jane, Has it been 6 months already? It's time for your oil change." }

    The "topic", "subject", and "message" entries correspond to the fields in your Lambda function, completing the notification. You will use the same input data when running the function as a Step Functions task.

  4. Choose Create.

  5. On the SendToSNS page, Test your Lambda function using the new data.

    The results of the test are displayed at the top of the page.

Step 5: Creating a State Machine

Use the Step Functions console to create a state machine with a Task state. Add a reference to your Lambda function in the Task state. The Lambda function is invoked when an execution of the state machine reaches the Task state.

To create the state machine

  1. Log in to the Step Functions console, and then choose Get Started.

  2. On the Create a state machine page, Name your state machine, for example TaskTimer.

    Note

    State machine names must be 1-80 characters in length, must be unique for your account and region, and must not contain any of the following:

    • Whitespace

    • Whitespace characters (? *)

    • Bracket characters (< > { } [ ])

    • Special characters (: ; , \ | ^ ~ $ # % & ` ")

    • Control characters (\\u0000 - \\u001f or \\u007f - \\u009f).

  3. Choose the Task timer blueprint.

  4. In the Code pane, add the ARN of the Lambda function that you created earlier to the Resource field, for example:

    Copy
    { "Comment": "A Task Timer example of the Amazon States Language scheduling a task", "StartAt": "Wait for Timestamp", "States": { "Wait for Timestamp": { "Type": "Wait", "TimestampPath": "$.trigger_date", "Next": "Send SNS Message" }, "Send SNS Message": { "Type": "Task", "Resource": "arn:aws:lambda:us-east-1:123456789012:function:SendToSNS", "Retry" : [ { "ErrorEquals": [ "States.ALL" ], "IntervalSeconds": 1, "MaxAttempts": 3, "BackoffRate": 2.0 } ], "End": true } } }

    This is a description of your state machine using the Amazon States Language. It defines a Wait state named Wait for Timestamp. For more information, see State Machine Structure.

    Note

    TimestampPath requires the use of timestamps.

    Timestamps (for example, 2016-08-18T17:33:00Z) must conform to RFC3339 profile ISO 8601, with further restrictions:

    • An uppercase T must separate the date and time portions.

    • An uppercase Z must denote that a numeric time zone offset isn't present.

    To specify time in seconds, you can use SecondsPath instead (for example, 24 hours = 86,400 seconds, 7 days = 604,800 seconds, and so on). For more information, see Wait.

  5. Use the graph in the Visual Workflow pane to check that your Amazon States Language code describes your state machine correctly.

    If you don't see the graph, choose 
       refresh
    in the Visual Workflow pane.

  6. Choose Create State Machine.

    On the IAM role for your state machine executions dialog box, Step Functions creates and selects an IAM role automatically.

    Note

    If you delete the IAM role that Step Functions creates, Step Functions can't recreate it later. Similarly, if you modify the role (for example, by removing Step Functions from the principals in the IAM policy), Step Functions can't restore its original settings later. For more information about creating an IAM role manually, see Creating IAM Roles for AWS Step Functions.

  7. Choose OK.

    The state machine is created and an acknowledgement page is displayed.

Step 6: Starting a New Execution

After you create your state machine, you can start an execution.

To start a new execution

  1. On the TaskTimer page, choose New execution.

    The New execution page is displayed.

  2. (Optional) To help identify your execution, you can enter an ID for it. To specify the ID, use the Enter your execution id here text box. If you don't enter an ID, Step Functions generates a unique ID automatically.

  3. In the execution input area, replace the example data with the following:

    Copy
    { "topic": "arn:aws:sns:us-east-1:123456789012:OilChange", "subject": "Time for your oil change!", "body": "Dear Jane, Has it been 6 months already? It's time for your oil change.", "trigger_date": "2017-07-25T20:47:07+00:00" }

    Note

    trigger_date specifies the date and time (in RFC3339 format) at which the timer causes the notification to be sent.

  4. Choose Start Execution.

    A new execution of your state machine starts, and a new page showing your running execution is displayed.

  5. In the Execution Details section, choose Info to view the Execution Status and the Started and Closed timestamps.

  6. To view the results of your execution, choose Output.