• 沒有找到結果。

Create a Lambda Function to Iterate a Count

在文檔中 AWS Step Functions (頁 132-160)

Step 1: Create a Lambda Function

Your Lambda function receives event data and returns a greeting message.

Important

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

1. Open the Lambda console and choose Create function.

2. On the Create function page, choose Author from scratch.

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

a. For Function name, enter HelloFunction.

b. For Runtime, choose Node.js 14.x.

c. In Change default execution role, choose Create a new role with basic Lambda permissions.

d. Choose Create function.

e. After your Lambda function is created, copy the function's Amazon Resource Name (ARN) displayed in the upper-right corner of the page. To copy the ARN, click . The following is an example ARN:

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

4. Copy the following code for the Lambda function into the Code source section of the HelloFunction page.

exports.handler = (event, context, callback) => { callback(null, "Hello from " + event.who + "!");

};

This code assembles a greeting using the who field of the input data, which is provided by the event object passed into your function. You add input data for this function later, when you start a new execution (p. 123). The callback method returns the assembled greeting from your function.

5. Choose Deploy.

Step 2: Test the Lambda Function

Test your Lambda function to see it in operation.

1. Choose Test.

2. In the Configure test event dialog box, enter HelloEvent in the Event name box.

3. Replace the example data with the following.

{

"who": "AWS Step Functions"

}

The "who" entry corresponds to the event.who field in your Lambda function, completing the greeting. You will input the same input data when you run your state machine.

4. Choose Create.

5. On the HelloFunction page, choose Test to test your Lambda function using the new data.

The results of the test are displayed in the Execution results tab.

Step 3: Create a State Machine

6. Choose the Execution results tab to see the output.

Step 3: Create a State Machine

Use the Step Functions console to create a state machine that invokes the Lambda function that you created earlier in Step 1 (p. 121).

1. Open the Step Functions console and choose Create a state machine.

Important

Ensure that your state machine is under the same AWS account and Region as the Lambda function you created earlier.

2. On the Choose authoring method page, choose Design your workflow visually.

3. For Type, retain the default selection, that is, Standard.

4. Choose Next. This will open Workflow Studio.

5. From the states browser on the left, choose the Actions panel.

• Drag and drop the AWS Lambda Invoke API into the empty state labelled Drag first state here.

6. In the Inspector panel on the right, configure the Lambda function and its name:

a. Choose Configuration, and then edit the State name, if required.

b. In the API Parameters section, choose the Lambda function that you created earlier (p. 121) in the Function name dropdown list.

c. Retain the default selection in the Payload dropdown list.

7. Choose Next.

8. On the Review generated code page, review the state machine's Amazon States Language (ASL) definition, which is automatically generated based on your selections in the Actions and Inspector panel.

9. Choose Next.

10. Enter a Name for your state machine, for example, LambdaStateMachine.

NoteState machine, execution, and activity names must be 1–80 characters in length, must be unique for your account and AWS Region, and must not contain any of the following:

• Whitespace

• Wildcard characters (? *)

• Bracket characters (< > { } [ ])

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

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

Step Functions allows you to create state machine, execution, and activity names that contain non-ASCII characters. These non-ASCII names don't work with Amazon CloudWatch.

Step 4: Start a New Execution

To ensure that you can track CloudWatch metrics, choose a name that uses only ASCII characters.

11. In Execution role, under the Permissions section, choose Create new role.

12. Choose Create state machine.

Step 4: Start a New Execution

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

1. On the LambdaStateMachine page, choose Start execution.

The Start execution dialog box is displayed.

2. (Optional) To identify your execution, you can specify a name for it in the Name box. By default, Step Functions generates a unique execution name automatically.

NoteStep Functions allows you to create state machine, execution, and activity names that contain non-ASCII characters. These non-ASCII names don't work with Amazon CloudWatch.

To ensure that you can track CloudWatch metrics, choose a name that uses only ASCII characters.

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

{ "who" : "AWS Step Functions"

}

"who" is the key name that your Lambda function uses to get the name of the person to greet.

4. Choose Start Execution.

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

5. To view the results of your execution, choose the Execution output tab.

Creating an Activity State Machine Using Step Functions

This tutorial shows you how to create an activity-based state machine using Java and AWS Step Functions. Activities allow you to control worker code that runs somewhere else from your state machine. For an overview, see Activities (p. 33) in How Step Functions works (p. 19).

To complete this tutorial, you need the following:

• The SDK for Java. The example activity in this tutorial is a Java application that uses the AWS SDK for Java to communicate with AWS.

• AWS credentials in the environment or in the standard AWS configuration file. For more information, see Set Up Your AWS Credentials in the AWS SDK for Java Developer Guide.

Topics

Step 1: Create an Activity

• Step 1: Create an Activity (p. 124)

• Step 2: Create a State Machine (p. 124)

• Step 3: Implement a Worker (p. 125)

• Step 4: Start an Execution (p. 127)

• Step 5: Run and Stop the Worker (p. 127)

Step 1: Create an Activity

You must make Step Functions aware of the activity whose worker (a program) you want to create. Step Functions responds with an Amazon Resource Name(ARN) that establishes an identity for the activity.

Use this identity to coordinate the information passed between your state machine and worker.

Important

Ensure that your activity task is under the same AWS account as your state machine.

1. In the Step Functions console, in the navigation pane on the left, choose Activities.

2. Choose Create activity.

3. Enter an Activity Name, for example, get-greeting, and then choose Create Activity.

4. When your activity task is created, make a note of its ARN, as shown in the following example.

arn:aws:states:us-east-1:123456789012:activity:get-greeting

Step 2: Create a State Machine

Create a state machine that determines when your activity is invoked and when your worker should perform its primary work, collect its results, and return them.

1. In the Step Functions console, in the navigation pane on the left, choose State machines.

2. On the State machines page, choose Create state machine, and then choose Author with code snippets. For Type, choose Standard, and then enter a name for your state machine (for example, ActivityStateMachine).

NoteState machine, execution, and activity names must be 1–80 characters in length, must be unique for your account and AWS Region, and must not contain any of the following:

• Whitespace

• Wildcard characters (? *)

• Bracket characters (< > { } [ ])

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

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

Step Functions allows you to create state machine, execution, and activity names that contain non-ASCII characters. These non-ASCII names don't work with Amazon CloudWatch.

To ensure that you can track CloudWatch metrics, choose a name that uses only ASCII characters.

Under State machine definition, enter the following code, and include the ARN of the activity task that you created earlier (p. 124) in the Resource field, as shown in the following example.

{

Step 3: Implement a Worker

"Comment": "An example using a Task state.", "StartAt": "getGreeting",

"Version": "1.0", "TimeoutSeconds": 300, "States":

{

"getGreeting": { "Type": "Task",

"Resource": "arn:aws:states:us-east-1:123456789012:activity:get-greeting", "End": true

} }}

This is a description of your state machine using the Amazon States Language. It defines a single Task state named getGreeting. For more information, see State Machine Structure (p. 24).

3. 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 in the Visual Workflow pane.

4. Choose Next.

5. Create or enter an IAM role:

• To create an IAM role for Step Functions, select Create an IAM role for me, and enter a Name for your role.

• If you have previously created an IAM role (p. 504) with the correct permissions for your state machine, select Choose an existing IAM role. Select a role from the list, or provide an ARN for that role.

NoteIf 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.

6. Choose Create state machine.

Step 3: Implement a Worker

Create a worker. A worker is a program that is responsible for:

• Polling Step Functions for activities using the GetActivityTask API action.

• Performing the work of the activity using your code, (for example, the getGreeting() method in the following code).

• Returning the results using the SendTaskSuccess, SendTaskFailure, and SendTaskHeartbeat API actions.

Step 3: Implement a Worker

NoteFor a more complete example of an activity worker, see Example Activity Worker in Ruby (p. 34).

This example provides an implementation based on best practices, which you can use as a reference for your activity worker. The code implements a consumer-producer pattern with a configurable number of threads for pollers and activity workers.

To implement the worker

1. Create a file named GreeterActivities.java.

2. Add the following code to it.

import com.amazonaws.ClientConfiguration;

public String getGreeting(String who) throws Exception { return "{\"Hello\": \"" + who + "\"}";

}

public static void main(final String[] args) throws Exception { GreeterActivities greeterActivities = new GreeterActivities();

ClientConfiguration clientConfiguration = new ClientConfiguration();

clientConfiguration.setSocketTimeout((int)TimeUnit.SECONDS.toMillis(70));

AWSStepFunctions client = AWSStepFunctionsClientBuilder.standard() .withRegion(Regions.US_EAST_1)

.withCredentials(new EnvironmentVariableCredentialsProvider()) .withClientConfiguration(clientConfiguration)

Step 4: Start an Execution

Thread.sleep(1000);

} } } }

NoteThe EnvironmentVariableCredentialsProvider class in this example assumes that the AWS_ACCESS_KEY_ID (or AWS_ACCESS_KEY) and AWS_SECRET_KEY (or AWS_SECRET_ACCESS_KEY) environment variables are set. For more information about providing the required credentials to the factory, see AWSCredentialsProvider in the AWS SDK for Java API Reference and Set Up AWS Credentials and Region for Development in the AWS SDK for Java Developer Guide.

By default the AWS SDK will wait up to 50 seconds to receive data from the server for any operation. The GetActivityTask operation is a long-poll operation that will wait up to 60 seconds for the next available task. To prevent receiving a SocketTimeoutException error, set SocketTimeout to 70 seconds.

3. In the parameter list of the GetActivityTaskRequest().withActivityArn() constructor, replace the ACTIVITY_ARN value with the ARN of the activity task that you created

earlier (p. 124).

Step 4: Start an Execution

When you start the execution of the state machine, your worker polls Step Functions for activities, performs its work (using the input that you provide), and returns its results.

1. On the ActivityStateMachine page, choose Start execution.

The New execution page is displayed.

2. (Optional) To identify your execution, you can specify a name for it in the Name box. By default, Step Functions generates a unique execution name automatically.

NoteStep Functions allows you to create state machine, execution, and activity names that contain non-ASCII characters. These non-ASCII names don't work with Amazon CloudWatch.

To ensure that you can track CloudWatch metrics, choose a name that uses only ASCII characters.

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

{

"who" : "AWS Step Functions"

}

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. In the Execution Details section, expand the Output section to view the output of your workflow.

Step 5: Run and Stop the Worker

To have the worker poll your state machine for activities, you must run the worker.

Handling Error Conditions Using a State Machine

1. On the command line, navigate to the directory in which you created GreeterActivities.java.

2. To use the AWS SDK, add the full path of the lib and third-party directories to the dependencies of your build file and to your Java CLASSPATH. For more information, see Downloading and Extracting the SDK in the AWS SDK for Java Developer Guide.

3. Compile the file.

$ javac GreeterActivities.java 4. Run the file.

$ java GreeterActivities

5. In the Step Functions console, navigate to the Execution Details page.

6. When the execution completes, choose Output to see the results of your execution.

7. Stop the worker.

Handling Error Conditions Using a Step Functions State Machine

In this tutorial, you create an AWS Step Functions state machine with a Catch field. The Catch field uses an AWS Lambda function to respond with conditional logic based on error message type. This is a technique called function error handling.

For more information, see Function Error Handling in the AWS Lambda Developer Guide.

NoteYou can also create state machines that Retry on timeouts or those that use Catch to transition to a specific state when an error or timeout occurs. For examples of these error handling techniques, see Examples Using Retry and Using Catch (p. 79).

Topics

• Step 1: Create a Lambda Function That Fails (p. 128)

• Step 2: Test the Lambda Function (p. 129)

• Step 3: Create a State Machine with a Catch Field (p. 129)

• Step 4: Start a New Execution (p. 130)

Step 1: Create a Lambda Function That Fails

Use a Lambda function to simulate an error condition.

Important

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

1. Open the AWS Lambda console at https://console.aws.amazon.com/lambda/.

Choose Create function.

2. Choose Use a blueprint, enter functions into the filter, and then choose the step-functions-error blueprint.

3. Choose Configure.

Step 2: Test the Lambda Function

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

a. For Name, enter FailFunction.

b. For Role, choose Create a new role with basic Lambda permissions.

5. The following code is displayed in the Lambda function code pane.

exports.handler = async (event, context) => { function CustomError(message) {

this.name = 'CustomError';

this.message = message;

}

CustomError.prototype = new Error();

throw new CustomError('This is a custom error!');

};

The context object returns the error message This is a custom error!.

6. Choose Create function.

When your Lambda function is created, make a note of its Amazon Resource Name (ARN) in the upper-right corner of the page, as shown in the following example.

arn:aws:lambda:us-east-1:123456789012:function:FailFunction 7. Choose Deploy.

Step 2: Test the Lambda Function

Test your Lambda function to see it in operation.

1. On the FailFunction page, choose Test.

2. In the Configure test event dialog box, enter FailFunction for Event name, and then choose Create.

3. On the FailFunction page, choose Test to test your Lambda function.

The results of the test (the simulated error) are displayed in a new tab Execution results.

Step 3: Create a State Machine with a Catch Field

Use the Step Functions console to create a state machine that uses a Task state with a Catch field. Add a reference to your Lambda function in the Task state. The Lambda function is invoked and fails during execution. Step Functions retries the function twice using exponential backoff between retries.

1. Open the Step Functions console and choose Create state machine.

2. On the Choose authoring method page, choose Write your workflow in code.

3. Under Type, choose Standard.

4. In the Definition pane, paste the following code, but replace the ARN of the Lambda function that you created earlier (p. 128) in the Resource field.

{

"Comment": "A Catch example of the Amazon States Language using an AWS Lambda function",

"StartAt": "CreateAccount", "States": {

Step 4: Start a New Execution

"CreateAccount": { "Type": "Task",

"Resource": "arn:aws:lambda:us-east-1:123456789012:function:FailFunction", "Catch": [ {

"Result": "This is a fallback from a custom Lambda function exception", "End": true

},

"ReservedTypeFallback": { "Type": "Pass",

This is a description of your state machine using the Amazon States Language. It defines a single Task state named CreateAccount. For more information, see State Machine Structure (p. 24).

For more information about the syntax of the Retry field, see Examples using Retry and using Catch (p. 79).

Note

Unhandled errors in Lambda are reported as Lambda.Unknown in the error output. These include out-of-memory errors and function timeouts. You can match on Lambda.Unknown, States.ALL, or States.TaskFailed to handle these errors. When Lambda hits the maximum number of invocations, the error is Lambda.TooManyRequestsException. For more information about Lambda Handled and Unhandled errors, see FunctionError in the AWS Lambda Developer Guide.

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 in the Visual Workflow pane.

6. Choose Next.

7. Enter a Name for your state machine, such as Catchfailure. 8. In Permissions, choose Create new role.

9. Choose Create state machine.

Step 4: Start a New Execution

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

Periodically Start a State Machine Execution Using CloudWatch Events 1. On the Catchfailure page, choose Start execution.

The Start execution dialog box is displayed.

2. (Optional) To identify your execution, you can specify a name for it in the Name box. By default, Step Functions generates a unique execution name automatically.

Note

Step Functions allows you to create state machine, execution, and activity names that contain non-ASCII characters. These non-ASCII names don't work with Amazon CloudWatch.

To ensure that you can track CloudWatch metrics, choose a name that uses only ASCII characters.

3. Choose Start Execution.

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

4. Go to the Execution output tab to view the output of your workflow.

5. To view your custom error message, select CreateAccount in the Graph inspector pane and choose the Step output tab.

Note

You can preserve the state input with the error by using ResultPath. See Use ResultPath to Include Both Error and Input in a Catch (p. 67).

Periodically Start a State Machine Execution Using CloudWatch Events

You can execute an AWS Step Functions state machine in response to an event pattern or on a schedule using Amazon CloudWatch Events. This tutorial shows you how to set a state machine as a target for a CloudWatch Events rule that starts the execution of a state machine every five minutes.

For more information about setting a Step Functions state machine as a target using the PutTarget Amazon CloudWatch Events API action, see Add a Step Functions state machine as a target.

Topics

• Step 1: Create a State Machine (p. 132)

• Step 2: Create a CloudWatch Events Rule (p. 132)

Step 1: Create a State Machine

Step 1: Create a State Machine

Before you can set a CloudWatch Events target, you must create a state machine.

• To create a basic state machine, use the Getting Started (p. 10) tutorial.

• If you already have a state machine, proceed to the next step.

Step 2: Create a CloudWatch Events Rule

After you create your state machine, you can create your CloudWatch Events rule.

1. Navigate to the CloudWatch Events console, choose Events, and then choose Create Rule.

The Step 1: Create rule page is displayed.

2. In the Event source section, choose Schedule, and then enter 5 for Fixed rate of.

3. In the Targets section, choose Add target, and then from the list choose Step Functions state machine.

4. CloudWatch Events can create the IAM role needed for your event to run:

• To create an IAM role automatically, choose Create a new role for this specific resource.

• To use an IAM role that you created previously, choose Use existing role.

• To use an IAM role that you created previously, choose Use existing role.

在文檔中 AWS Step Functions (頁 132-160)