Git Product home page Git Product logo

serverless-step-functions's Introduction

Serverless Step Functions

serverless CI npm version Coverage Status MIT License serverless-step-functions Dev Token

This is the Serverless Framework plugin for AWS Step Functions.

Requirement

Serverless Framework v2.32.0 or later is required.

TOC

Install

Run npm install in your Serverless project.

$ npm install --save-dev serverless-step-functions

Add the plugin to your serverless.yml file

plugins:
  - serverless-step-functions

Setup

Specify your state machine definition using Amazon States Language in a definition statement in serverless.yml. You can use CloudFormation intrinsic functions such as Ref and Fn::GetAtt to reference Lambda functions, SNS topics, SQS queues and DynamoDB tables declared in the same serverless.yml. Since Ref returns different things (ARN, ID, resource name, etc.) depending on the type of CloudFormation resource, please refer to this page to see whether you need to use Ref or Fn::GetAtt.

Alternatively, you can also provide the raw ARN, or SQS queue URL, or DynamoDB table name as a string. If you need to construct the ARN by hand, then we recommend to use the serverless-pseudo-parameters plugin together to make your life easier.

In addition, if you want to reference a DynamoDB table managed by an external CloudFormation Stack, as long as that table name is exported as an output from that stack, it can be referenced by importing it using Fn::ImportValue. See the ddbtablestepfunc Step Function definition below for an example.

functions:
  hello:
    handler: handler.hello

stepFunctions:
  stateMachines:
    hellostepfunc1:
      events:
        - http:
            path: gofunction
            method: GET
        - schedule:
            rate: rate(10 minutes)
            enabled: true
            input:
              key1: value1
              key2: value2
              stageParams:
                stage: dev
      name: myStateMachine
      definition:
        Comment: "A Hello World example of the Amazon States Language using an AWS Lambda Function"
        StartAt: HelloWorld1
        States:
          HelloWorld1:
            Type: Task
            Resource:
              Fn::GetAtt: [hello, Arn]
            End: true
      dependsOn: CustomIamRole
      tags:
        Team: Atlantis
      alarms:
        topics:
          ok: arn:aws:sns:us-east-1:1234567890:NotifyMe
          alarm: arn:aws:sns:us-east-1:1234567890:NotifyMe
          insufficientData: arn:aws:sns:us-east-1:1234567890:NotifyMe
        metrics:
          - executionsTimedOut
          - executionsFailed
          - executionsAborted
          - metric: executionThrottled
            treatMissingData: breaching # overrides below default
          - executionsSucceeded
        treatMissingData: ignore # optional
    hellostepfunc2:
      definition:
        StartAt: HelloWorld2
        States:
          HelloWorld2:
            Type: Task
            Resource:
              Fn::GetAtt: [hello, Arn]
            End: true
    ddbtablestepfunc:
      definition:
        Comment: Demonstrates how to reference a DynamoDB Table Name exported from an external CloudFormation Stack
        StartAt: ImportDDBTableName
        States:
          ImportDDBTableName:
            Type: Task
            Resource: "arn:aws:states:::dynamodb:updateItem"
            Parameters:
              TableName:
                Fn::ImportValue: MyExternalStack:ToDoTable:Name # imports a table name from an external stack
              Key:
                id:
                  S.$: "$.todoId"
              UpdateExpression: "SET #status = :updatedStatus"
              ExpressionAttributeNames:
                "#status": status
              ExpressionAttributeValues:
                ":updatedStatus":
                  S: DONE
            End: true
      dependsOn:
        - DynamoDBTable
        - KinesisStream
        - CustomIamRole
      tags:
        Team: Atlantis
  activities:
    - myTask
    - yourTask
  validate: true # enable pre-deployment definition validation (disabled by default)

plugins:
  - serverless-step-functions
  - serverless-pseudo-parameters

In the example above, notice that we used Fn::GetAtt: [hello, Arn] to get the ARN for the hello function defined earlier. This means you don't have to know how the Serverless framework converts these local names to CloudFormation logical IDs (e.g. hello-world becomes HelloDashworldLambdaFunction).

However, if you prefer to work with logical IDs, you can. You can also express the above Fn::GetAtt function as Fn::GetAtt: [HelloLambdaFunction, Arn]. If you're unfamiliar with the convention the Serverless framework uses, then the easiest thing to do is to first run sls package then look in the .serverless folder for the generated CloudFormation template. Here you can find the logical resource names for the functions you want to reference.

Adding a custom name for a stateMachine

In case you need to interpolate a specific stage or service layer variable as the stateMachines name you can add a name property to your yaml.

service: messager

functions:
  sendMessage:
    handler: handler.sendMessage

stepFunctions:
  stateMachines:
    sendMessageFunc:
      name: sendMessageFunc-${self:custom.service}-${opt:stage}
      definition:
        <your definition>

plugins:
  - serverless-step-functions

Adding a custom logical id for a stateMachine

You can use a custom logical id that is only unique within the stack as opposed to the name that needs to be unique globally. This can make referencing the state machine easier/simpler because you don't have to duplicate the interpolation logic everywhere you reference the state machine.

service: messager

functions:
  sendMessage:
    handler: handler.sendMessage

stepFunctions:
  stateMachines:
    sendMessageFunc:
      id: SendMessageStateMachine
      name: sendMessageFunc-${self:custom.service}-${opt:stage}
      definition:
        <your definition>

plugins:
  - serverless-step-functions

You can then Ref: SendMessageStateMachine in various parts of CloudFormation or serverless.yml

Depending on another logical id

If your state machine depends on another resource defined in your serverless.yml then you can add a dependsOn field to the state machine definition. This would add the DependsOnclause to the generated CloudFormation template.

This dependsOn field can be either a string, or an array of strings.

stepFunctions:
  stateMachines:
    myStateMachine:
      dependsOn: myDB

    myOtherStateMachine:
      dependsOn:
        - myOtherDB
        - myStream

Adding retain property for a stateMachine

There are some practical cases when you would like to prevent state machine from deletion on stack delete or update. This can be achieved by adding retain property to the state machine section.

stepFunctions:
  stateMachines:
    myStateMachine:
      retain: true

Configuring in such way adds "DeletionPolicy" : "Retain" to the state machine within CloudFormation template.

CloudWatch Alarms

It's common practice to want to monitor the health of your state machines and be alerted when something goes wrong. You can either:

  • do this using the serverless-plugin-aws-alerts, which lets you configure custom CloudWatch Alarms against the various metrics that Step Functions publishes.
  • or, you can use the built-in alarms configuration from this plugin, which gives you an opinionated set of default alarms (see below)
stepFunctions:
  stateMachines:
    myStateMachine:
      alarms:
        topics:
          ok: arn:aws:sns:us-east-1:1234567890:NotifyMe
          alarm: arn:aws:sns:us-east-1:1234567890:NotifyMe
          insufficientData: arn:aws:sns:us-east-1:1234567890:NotifyMe
        metrics:
          - executionsTimedOut
          - executionsFailed
          - executionsAborted
          - executionThrottled
          - executionsSucceeded
        treatMissingData: missing

Both topics and metrics are required properties. There are 4 supported metrics, each map to the CloudWatch Metrics that Step Functions publishes for your executions.

You can configure how the CloudWatch Alarms should treat missing data:

  • missing (AWS default): The alarm does not consider missing data points when evaluating whether to change state.
  • ignore: The current alarm state is maintained.
  • breaching: Missing data points are treated as breaching the threshold.
  • notBreaching: Missing data points are treated as being within the threshold.

For more information, please refer to the official documentation.

The generated CloudWatch alarms would have the following configurations:

namespace: 'AWS/States'
metric: <ExecutionsTimedOut | ExecutionsFailed | ExecutionsAborted | ExecutionThrottled>
threshold: 1
period: 60
evaluationPeriods: 1
ComparisonOperator: GreaterThanOrEqualToThreshold
Statistic: Sum
treatMissingData: <missing (default) | ignore | breaching | notBreaching>
Dimensions:
  - Name: StateMachineArn
    Value: <ArnOfTheStateMachine>

You can also override the default treatMissingData setting for a particular alarm by specifying an override:

alarms:
  topics:
    ok: arn:aws:sns:us-east-1:1234567890:NotifyMe
    alarm: arn:aws:sns:us-east-1:1234567890:NotifyMe
    insufficientData: arn:aws:sns:us-east-1:1234567890:NotifyMe
  metrics:
    - executionsTimedOut
    - executionsFailed
    - executionsAborted
    - metric: executionThrottled
      treatMissingData: breaching # override
    - executionsSucceeded
  treatMissingData: ignore # default

Custom CloudWatch Alarm names

By default, the CloudFormation assigns names to the alarms based on the CloudFormation stack and the resource logical Id, and in some cases and these names could be confusing.

To use custom names to the alarms add nameTemplate property in the alarms object.

example:

service: myservice

plugins:
  - serverless-step-functions

stepFunctions:
  stateMachines:
    main-workflow:
      name: main
      alarms:
        nameTemplate: $[stateMachineName]-$[cloudWatchMetricName]-alarm
        topics:
          alarm: !Ref AwsAlertsGenericAlarmTopicAlarm
        metrics:
          - executionsFailed
          - executionsAborted
          - executionsTimedOut
          - executionThrottled
        treatMissingData: ignore
      definition: ${file(./step-functions/main.asl.yaml)}

Supported variables to the nameTemplate property:

  • stateMachineName
  • metricName
  • cloudWatchMetricName
Per-Metric Alarm Name

To overwrite the alarm name for a specific metric, add the alarmName property in the metric object.

service: myservice

plugins:
  - serverless-step-functions

stepFunctions:
  stateMachines:
    main-workflow:
      name: main
      alarms:
        nameTemplate: $[stateMachineName]-$[cloudWatchMetricName]-alarm
        topics:
          alarm: !Ref AwsAlertsGenericAlarmTopicAlarm
        metrics:
          - metric: executionsFailed
            alarmName: mycustom-name-${self:stage.region}-Failed-alarm
          - executionsAborted
          - executionsTimedOut
          - executionThrottled
        treatMissingData: ignore
      definition: ${file(./step-functions/main.asl.yaml)}

CloudWatch Notifications

You can monitor the execution state of your state machines via CloudWatch Events. It allows you to be alerted when the status of your state machine changes to ABORTED, FAILED, RUNNING, SUCCEEDED or TIMED_OUT.

You can configure CloudWatch Events to send notification to a number of targets. Currently this plugin supports sns, sqs, kinesis, firehose, lambda and stepFunctions.

To configure status change notifications to your state machine, you can add a notifications like below:

stepFunctions:
  stateMachines:
    hellostepfunc1:
      name: test
      definition:
        ...
      notifications:
        ABORTED:
          - sns: SNS_TOPIC_ARN
          - sqs: SQS_TOPIC_ARN
          - sqs: # for FIFO queues, which requires you to configure the message group ID
              arn: SQS_TOPIC_ARN
              messageGroupId: 12345
          - lambda: LAMBDA_FUNCTION_ARN
          - kinesis: KINESIS_STREAM_ARN
          - kinesis:
               arn: KINESIS_STREAM_ARN
               partitionKeyPath: $.id # used to choose the parition key from payload
          - firehose: FIREHOSE_STREAM_ARN
          - stepFunctions: STATE_MACHINE_ARN
        FAILED:
          ... # same as above
        ... # other status

As you can see from the above example, you can configure different notification targets for each type of status change. If you want to configure the same targets for multiple status changes, then consider using YML anchors to keep your YML succinct.

CloudFormation intrinsic functions such as Ref and Fn::GetAtt are supported.

When setting up a notification target against a FIFO SQS queue, the queue must enable the content-based deduplication option and you must configure the messageGroupId.

Blue green deployment

To implement a blue-green deployment with Step Functions you need to reference the exact versions of the functions.

To do this, you can specify useExactVersion: true in the state machine.

stepFunctions:
  stateMachines:
    hellostepfunc1:
      useExactVersion: true
      definition:
        ...

Pre-deployment validation

By default, your state machine definition will be validated during deployment by StepFunctions. This can be cumbersome when developing because you have to upload your service for every typo in your definition. In order to go faster, you can enable pre-deployment validation using asl-validator which should detect most of the issues (like a missing state property).

stepFunctions:
  validate: true

Disable Output Cloudformation Outputs section

Disables the generation of outputs in the CloudFormation Outputs section. If you define many state machines in serverless.yml you may reach the CloudFormation limit of 60 outputs. If you define noOutput: true then this plugin will not generate outputs automatically.

stepFunctions:
  noOutput: true

Express Workflow

At re:invent 2019, AWS introduced Express Workflows as a cheaper, more scalable alternative (but with a cut-down set of features). See this page for differences between standard and express workflows.

To declare an express workflow, specify type as EXPRESS and you can specify the logging configuration:

stepFunctions:
  stateMachines:
    hellostepfunc1:
      type: EXPRESS
      loggingConfig:
        level: ERROR
        includeExecutionData: true
        destinations:
          - Fn::GetAtt: [MyLogGroup, Arn]

CloudWatch Logs

You can enable CloudWatch Logs for standard Step Functions, the syntax is exactly like with Express Workflows.

stepFunctions:
  stateMachines:
    hellostepfunc1:
      loggingConfig:
        level: ERROR
        includeExecutionData: true
        destinations:
          - Fn::GetAtt: [MyLogGroup, Arn]

X-Ray

You can enable X-Ray for your state machine, specify tracingConfig as shown below.

stepFunctions:
  stateMachines:
    hellostepfunc1:
      tracingConfig:
        enabled: true

Current Gotcha

Please keep this gotcha in mind if you want to reference the name from the resources section. To generate Logical ID for CloudFormation, the plugin transforms the specified name in serverless.yml based on the following scheme.

  • Transform a leading character into uppercase
  • Transform - into Dash
  • Transform _ into Underscore

If you want to use variables system in name statement, you can't put the variables as a prefix like this:${self:service}-${opt:stage}-myStateMachine since the variables are transformed within Output section, as a result, the reference will be broken.

The correct sample is here.

stepFunctions:
  stateMachines:
    myStateMachine:
      name: myStateMachine-${self:service}-${opt:stage}
...

resources:
  Outputs:
    myStateMachine:
      Value:
        Ref: MyStateMachineDash${self:service}Dash${opt:stage}

Events

API Gateway

To create HTTP endpoints as Event sources for your StepFunctions statemachine

Simple HTTP Endpoint

This setup specifies that the hello state machine should be run when someone accesses the API gateway at hello via a GET request.

Here's an example:

stepFunctions:
  stateMachines:
    hello:
      events:
        - http:
            path: hello
            method: GET
      definition:

Here You can define an POST endpoint for the path posts/create.

stepFunctions:
  stateMachines:
    hello:
      events:
        - http:
            path: posts/create
            method: POST
      definition:

Custom Step Functions Action

Step Functions have custom actions like DescribeExecution or StopExecution to fetch and control them. You can use custom actions like this:

stepFunctions:
  stateMachines:
    start:
      events:
        - http:
            path: action/start
            method: POST
      definition:
        ...
    status:
      events:
        - http:
            path: action/status
            method: POST
            action: DescribeExecution
      definition:
        ...
    stop:
      events:
        - http:
            path: action/stop
            method: POST
            action: StopExecution
      definition:
        ...

Request template is not used when action is set because there're a bunch of actions. However if you want to use request template you can use Customizing request body mapping templates.

HTTP Endpoint with custom IAM Role

The plugin would generate an IAM Role for you by default. However, if you wish to use an IAM role that you have provisioned separately, then you can override the IAM Role like this:

stepFunctions:
  stateMachines:
    hello:
      events:
        - http:
            path: posts/create
            method: POST
            iamRole: arn:aws:iam::<accountId>:role/<roleName>
      definition:

Share API Gateway and API Resources

You can share the same API Gateway between multiple projects by referencing its REST API ID and Root Resource ID in serverless.yml as follows:

service: service-name
provider:
  name: aws
  apiGateway:
    # REST API resource ID. Default is generated by the framework
    restApiId: xxxxxxxxxx
    # Root resource, represent as / path
    restApiRootResourceId: xxxxxxxxxx

functions:
  ...

If your application has many nested paths, you might also want to break them out into smaller services.

However, Cloudformation will throw an error if we try to generate an existing path resource. To avoid that, we reference the resource ID:

service: service-a
provider:
  apiGateway:
    restApiId: xxxxxxxxxx
    restApiRootResourceId: xxxxxxxxxx
    # List of existing resources that were created in the REST API. This is required or the stack will be conflicted
    restApiResources:
      /users: xxxxxxxxxx

functions:
  ...

Now we can define endpoints using existing API Gateway ressources

stepFunctions:
  stateMachines:
    hello:
      events:
        - http:
            path: users/create
            method: POST

Enabling CORS

To set CORS configurations for your HTTP endpoints, simply modify your event configurations as follows:

stepFunctions:
  stateMachines:
    hello:
      events:
        - http:
            path: posts/create
            method: POST
            cors: true
      definition:

Setting cors to true assumes a default configuration which is equivalent to:

stepFunctions:
  stateMachines:
    hello:
      events:
        - http:
            path: posts/create
            method: POST
            cors:
              origin: '*'
              headers:
                - Content-Type
                - X-Amz-Date
                - Authorization
                - X-Api-Key
                - X-Amz-Security-Token
                - X-Amz-User-Agent
              allowCredentials: false
      definition:

Configuring the cors property sets Access-Control-Allow-Origin, Access-Control-Allow-Headers, Access-Control-Allow-Methods,Access-Control-Allow-Credentials headers in the CORS preflight response. To enable the Access-Control-Max-Age preflight response header, set the maxAge property in the cors object:

stepFunctions:
  stateMachines:
    SfnApiGateway:
      events:
        - http:
            path: /playground/start
            method: post
            cors:
              origin: '*'
              maxAge: 86400

HTTP Endpoints with AWS_IAM Authorizers

If you want to require that the caller submit the IAM user's access keys in order to be authenticated to invoke your Lambda Function, set the authorizer to AWS_IAM as shown in the following example:

stepFunctions:
  stateMachines:
    hello:
      events:
        - http:
            path: posts/create
            method: POST
            authorizer: aws_iam
      definition:

HTTP Endpoints with Custom Authorizers

Custom Authorizers allow you to run an AWS Lambda Function before your targeted AWS Lambda Function. This is useful for Microservice Architectures or when you simply want to do some Authorization before running your business logic.

You can enable Custom Authorizers for your HTTP endpoint by setting the Authorizer in your http event to another function in the same service, as shown in the following example:

stepFunctions:
  stateMachines:
    hello:
      - http:
          path: posts/create
          method: post
          authorizer: authorizerFunc
      definition:

If the Authorizer function does not exist in your service but exists in AWS, you can provide the ARN of the Lambda function instead of the function name, as shown in the following example:

stepFunctions:
  stateMachines:
    hello:
      - http:
          path: posts/create
          method: post
          authorizer: xxx:xxx:Lambda-Name
      definition:

Shared Authorizer

Auto-created Authorizer is convenient for conventional setup. However, when you need to define your custom Authorizer, or use COGNITO_USER_POOLS authorizer with shared API Gateway, it is painful because of AWS limitation. Sharing Authorizer is a better way to do.

stepFunctions:
  stateMachines:
    createUser:
      ...
      events:
        - http:
            path: /users
            ...
            authorizer:
              # Provide both type and authorizerId
              type: COGNITO_USER_POOLS # TOKEN, CUSTOM or COGNITO_USER_POOLS, same as AWS Cloudformation documentation
              authorizerId:
                Ref: ApiGatewayAuthorizer  # or hard-code Authorizer ID
              # [Optional] you can also specify the OAuth scopes for Cognito
              scopes:
                - scope1
                ...

LAMBDA_PROXY request template

The plugin generates default body mapping templates for application/json and application/x-www-form-urlencoded content types. The default template would pass the request body as input to the state machine. If you need access to other contextual information about the HTTP request such as headers, path parameters, etc. then you can also use the lambda_proxy request template like this:

stepFunctions:
  stateMachines:
    hello:
      events:
        - http:
            path: posts/create
            method: POST
            request:
              template: lambda_proxy

This would generate the normal LAMBDA_PROXY template used for API Gateway integration with Lambda functions.

Customizing request body mapping templates

If you'd like to add content types or customize the default templates, you can do so by including your custom API Gateway request mapping template in serverless.yml like so:

stepFunctions:
  stateMachines:
    hello:
      events:
        - http:
            path: posts/create
            method: POST
            request:
              template:
                application/json: |
                  #set( $body = $util.escapeJavaScript($input.json('$')) )
                  #set( $name = $util.escapeJavaScript($input.json('$.data.attributes.order_id')) )
                  {
                    "input": "$body",
                    "name": "$name",
                    "stateMachineArn":"arn:aws:states:#{AWS::Region}:#{AWS::AccountId}:stateMachine:processOrderFlow-${opt:stage}"
                  }
      name: processOrderFlow-${opt:stage}
      definition:

Customizing response headers and templates

If you'd like to add custom headers in the HTTP response, or customize the default response template (which just returns the response from Step Function's StartExecution API), then you can do so by including your custom headers and API Gateway response mapping template in serverless.yml like so:

stepFunctions:
  stateMachines:
    hello:
      events:
        - http:
            path: posts/create
            method: POST
            response:
              headers:
                Content-Type: "'application/json'"
                X-Application-Id: "'my-app'"
              template:
                application/json: |
                  {
                    "status": 200,
                    "info": "OK"
                  }
      definition:

Send request to an API

You can input an value as json in request body, the value is passed as the input value of your statemachine

$ curl -XPOST https://xxxxxxxxx.execute-api.us-east-1.amazonaws.com/dev/posts/create -d '{"foo":"bar"}'

Setting API keys for your Rest API

You can specify a list of API keys to be used by your service Rest API by adding an apiKeys array property to the apiGateway subsection of the provider object in serverless.yml. You'll also need to explicitly specify which endpoints are private and require one of the api keys to be included in the request by adding a private boolean property to the http event object you want to set as private. API Keys are created globally, so if you want to deploy your service to different stages make sure your API key contains a stage variable as defined below. When using API keys, you can optionally define usage plan quota and throttle, using usagePlan object.

Here's an example configuration for setting API keys for your service Rest API:

service: my-service
provider:
  name: aws
  apiGateway:
    apiKeys:
        - myFirstKey
        - ${opt:stage}-myFirstKey
        - ${env:MY_API_KEY} # you can hide it in a serverless variable
  usagePlan:
    quota:
      limit: 5000
      offset: 2
      period: MONTH
    throttle:
      burstLimit: 200
      rateLimit: 100
functions:
  hello:
    handler: handler.hello

    stepFunctions:
      stateMachines:
        statemachine1:
          name: ${self:service}-${opt:stage}-statemachine1
          events:
            - http:
                path: /hello
                method: post
                private: true
          definition:
            Comment: "A Hello World example of the Amazon States Language using an AWS Lambda Function"
            StartAt: HelloWorld1
            States:
              HelloWorld1:
                Type: Task
                Resource:
                  Fn::GetAtt: [hello, Arn]
                End: true


    plugins:
      - serverless-step-functions
      - serverless-pseudo-parameters

Please note that those are the API keys names, not the actual values. Once you deploy your service, the value of those API keys will be auto generated by AWS and printed on the screen for you to use. The values can be concealed from the output with the --conceal deploy option.

Clients connecting to this Rest API will then need to set any of these API keys values in the x-api-key header of their request. This is only necessary for functions where the private property is set to true.

Request Schema Validators

To use request schema validation with API gateway, add the JSON Schema for your content type. Since JSON Schema is represented in JSON, it's easier to include it from a file.

stepFunctions:
  stateMachines:
    create:
      events:
        - http:
            path: posts/create
            method: post
            request:
              schemas:
                application/json: ${file(create_request.json)}

In addition, you can also customize created model with name and description properties.

stepFunctions:
  stateMachines:
    create:
      events:
        - http:
            path: posts/create
            method: post
            request:
              schemas:
                application/json:
                  schema: ${file(create_request.json)}
                  name: PostCreateModel
                  description: 'Validation model for Creating Posts'

To reuse the same model across different events, you can define global models on provider level. In order to define global model you need to add its configuration to provider.apiGateway.request.schemas. After defining a global model, you can use it in the event by referencing it by the key. Provider models are created for application/json content type.

provider:
    ...
    apiGateway:
      request:
        schemas:
          post-create-model:
            name: PostCreateModel
            schema: ${file(api_schema/post_add_schema.json)}
            description: "A Model validation for adding posts"
 
stepFunctions:
  stateMachines:
    create:
      events:
        - http:
            path: posts/create
            method: post
            request:
              schemas:
                application/json: post-create-model

A sample schema contained in create_request.json might look something like this:

{
  "definitions": {},
  "$schema": "http://json-schema.org/draft-04/schema#",
  "type": "object",
  "title": "The Root Schema",
  "required": ["username"],
  "properties": {
    "username": {
      "type": "string",
      "title": "The Foo Schema",
      "default": "",
      "pattern": "^[a-zA-Z0-9]+$"
    }
  }
}

NOTE: schema validators are only applied to content types you specify. Other content types are not blocked. Currently, API Gateway supports JSON Schema draft-04.

Schedule

The following config will attach a schedule event and causes the stateMachine crawl to be called every 2 hours. The configuration allows you to attach multiple schedules to the same stateMachine. You can either use the rate or cron syntax. Take a look at the AWS schedule syntax documentation for more details.

stepFunctions:
  stateMachines:
    crawl:
      events:
        - schedule: rate(2 hours)
        - schedule: cron(0 12 * * ? *)
      definition:

Enabling / Disabling

Note: schedule events are enabled by default.

This will create and attach a schedule event for the aggregate stateMachine which is disabled. If enabled it will call the aggregate stateMachine every 10 minutes.

stepFunctions:
  stateMachines:
    aggregate:
      events:
        - schedule:
            rate: rate(10 minutes)
            enabled: false
            input:
              key1: value1
              key2: value2
              stageParams:
                stage: dev
        - schedule:
            rate: cron(0 12 * * ? *)
            enabled: false
            inputPath: '$.stageVariables'

Specify Name and Description

Name and Description can be specified for a schedule event. These are not required properties.

events:
  - schedule:
      name: your-scheduled-rate-event-name
      description: 'your scheduled rate event description'
      rate: rate(2 hours)

Scheduled Events IAM Role

By default, the plugin will create a new IAM role that allows AWS Events to start your state machine. Note that this role is different than the role assumed by the state machine. You can specify your own role instead (it must allow events.amazonaws.com to assume it, and it must be able to run states:StartExecution on your state machine):

events:
  - schedule:
      rate: rate(2 hours)
      role: arn:aws:iam::xxxxxxxx:role/yourRole

Specify InputTransformer

You can specify input values ​​to the Lambda function.

stepFunctions:
  stateMachines:
    stateMachineScheduled:
      events:
        - schedule: 
            rate: cron(30 12 ? * 1-5 *)
            inputTransformer:
              inputPathsMap: 
                time: '$.time'
                stage: '$.stageVariables'
              inputTemplate: '{"time": <time>, "stage" : <stage> }'
      definition:
        ...

Use EventBridge Scheduler instead of EventBridge rules

AWS has account-wide limits on the number of AWS::Event::Rule triggers per bus (300 events), and all Lambda schedules go into a single bus with no way to override it. This can lead to a situation where large projects hit the limit with no ability to schedule more events.

However, AWS::Scheduler::Schedule has much higher limits (1,000,000 events), and is configured identically. method can be set in order to migrate to this trigger type seamlessly. It also allows you to specify a timezone to run your event based on local time.

stepFunctions:
  stateMachines:
    stateMachineScheduled:
      events:
        - schedule:
            method: scheduler
            rate: cron(30 12 ? * 1-5 *)
            enabled: true
            timezone: America/New_York
      definition:
        ...

CloudWatch Event / EventBridge

Simple event definition

This will enable your Statemachine to be called by an EC2 event rule. Please check the page of Event Types for CloudWatch Events.

stepFunctions:
  stateMachines:
    first:
      events:
        - cloudwatchEvent:
            event:
              source:
                - "aws.ec2"
              detail-type:
                - "EC2 Instance State-change Notification"
              detail:
                state:
                  - pending
      definition:
        ...

You can alternatively use EventBridge:

stepFunctions:
  stateMachines:
    first:
      events:
        - eventBridge:
            event:
              source:
                - "aws.ec2"
              detail-type:
                - "EC2 Instance State-change Notification"
              detail:
                state:
                  - pending
      definition:
        ...

All the configurations in this section applies to both cloudwatchEvent and eventBridge.

Enabling / Disabling

Note: cloudwatchEvent and eventBridge events are enabled by default.

This will create and attach a disabled cloudwatchEvent event for the myCloudWatch statemachine.

stepFunctions:
  stateMachines:
    cloudwatchEvent:
      events:
        - cloudwatchEvent:
            event:
              source:
                - "aws.ec2"
              detail-type:
                - "EC2 Instance State-change Notification"
              detail:
                state:
                  - pending
            enabled: false
      definition:
        ...

Specify Input or Inputpath or InputTransformer

You can specify input values ​​to the Lambda function.

stepFunctions:
  stateMachines:
    cloudwatchEvent:
      events:
        - cloudwatchEvent:
            event:
              source:
                - "aws.ec2"
              detail-type:
                - "EC2 Instance State-change Notification"
              detail:
                state:
                  - pending
            input:
              key1: value1
              key2: value2
              stageParams:
                stage: dev
        - cloudwatchEvent:
            event:
              source:
                - "aws.ec2"
              detail-type:
                - "EC2 Instance State-change Notification"
              detail:
                state:
                  - pending
            inputPath: '$.stageVariables'
        - cloudwatchEvent:
            event:
              source:
                - "aws.ec2"
              detail-type:
                - "EC2 Instance State-change Notification"
              detail:
                state:
                  - pending
            inputTransformer:
              inputPathsMap:
                stage: '$.stageVariables'
              inputTemplate: '{ "stage": <stage> }'
      definition:
        ...

Specifying a Description

You can also specify a CloudWatch Event description.

stepFunctions:
  stateMachines:
    cloudwatchEvent:
      events:
        - cloudwatchEvent:
            description: 'CloudWatch Event triggered on EC2 Instance pending state'
            event:
              source:
                - "aws.ec2"
              detail-type:
                - "EC2 Instance State-change Notification"
              detail:
                state:
                  - pending
      definition:
        ...

Specifying a Name

You can also specify a CloudWatch Event name. Keep in mind that the name must begin with a letter; contain only ASCII letters, digits, and hyphens; and not end with a hyphen or contain two consecutive hyphens. More infomation here.

stepFunctions:
  stateMachines:
    cloudwatchEvent:
      events:
        - cloudwatchEvent:
            name: 'my-cloudwatch-event-name'
            event:
              source:
                - "aws.ec2"
              detail-type:
                - "EC2 Instance State-change Notification"
              detail:
                state:
                  - pending
      definition:
        ...

Specifying a RoleArn

You can also specify a CloudWatch Event RoleArn. The Amazon Resource Name (ARN) of the role that is used for target invocation.

Required: No

stepFunctions:
  stateMachines:
    cloudwatchEvent:
      events:
        - cloudwatchEvent:
            name: 'my-cloudwatch-event-name'
            iamRole: 'arn:aws:iam::012345678910:role/Events-InvokeStepFunctions-Role'
            event:
              source:
                - "aws.ec2"
              detail-type:
                - "EC2 Instance State-change Notification"
              detail:
                state:
                  - pending
      definition:
        ...

Specifying a custom CloudWatch EventBus

You can choose which CloudWatch Event bus:

stepFunctions:
  stateMachines:
    exampleCloudwatchEventStartsMachine:
      events:
        - cloudwatchEvent:
            eventBusName: 'my-custom-event-bus'
            event:
              source:
                - "my.custom.source"
              detail-type:
                - "My Event Type"
              detail:
                state:
                  - pending
      definition:
        ...

Specifying a custom EventBridge EventBus

You can choose which EventBridge Event bus:

stepFunctions:
  stateMachines:
    exampleEventBridgeEventStartsMachine:
      events:
        - eventBridge:
            eventBusName: 'my-custom-event-bus'
            event:
              source:
                - "my.custom.source"
              detail-type:
                - "My Event Type"
              detail:
                state:
                  - pending
      definition:
        ...

Specifying a DeadLetterQueue

You can configure a target queue to send dead-letter queue events to:

stepFunctions:
  stateMachines:
    exampleEventBridgeEventStartsMachine:
      events:
        - eventBridge:
            eventBusName: 'my-custom-event-bus'
            event:
              source:
                - "my.custom.source"
              detail-type:
                - "My Event Type"
              detail:
                state:
                  - pending
            deadLetterConfig: 'arn:aws:sqs:us-east-1:012345678910:my-dlq' # SQS Arn
      definition:
        ...
Important point

Don't forget to Grant permissions to the dead-letter queue, to do that you may need to have the ARN of the generated EventBridge Rule.

In order to get the ARN you can use intrinsic functions against the logicalId, this plugin generates logicalIds following this format:

`${StateMachineName}EventsRuleCloudWatchEvent${index}`

Given this example 👇

stepFunctions:
  stateMachines:
    hellostepfunc1: # <---- StateMachineName
      events:
        - eventBridge:
            eventBusName: 'my-custom-event-bus'
            event:
              source:
                - "my.custom.source"
        - eventBridge:
            eventBusName: 'my-custom-event-bus'
            event:
              source:
                - "my.custom.source"
            deadLetterConfig: 'arn:aws:sqs:us-east-1:012345678910:my-dlq'
      name: myStateMachine
      definition:
        Comment: "A Hello World example of the Amazon States Language using an AWS Lambda Function"
        StartAt: HelloWorld1
        States:
          HelloWorld1:
            Type: Task
            Resource:
              Fn::GetAtt: [hello, Arn]
            End: true

Then

# to get the Arn of the 1st EventBridge rule
!GetAtt Hellostepfunc1EventsRuleCloudWatchEvent1.Arn

# to get the Arn of the 2nd EventBridge rule
!GetAtt Hellostepfunc1EventsRuleCloudWatchEvent2.Arn

Tags

You can specify tags on each state machine. Additionally any global tags (specified under provider section in your serverless.yml) would be merged in as well.

If you don't want for global tags to be merged into your state machine, you can include the inheritGlobalTags property for your state machine.

provider:
  tags:
    app: myApp
    department: engineering
stepFunctions:
  stateMachines:
    hellostepfunc1:
      name: myStateMachine
      inheritGlobalTags: false
      tags:
        score: 42
      definition: something

As a result, hellostepfunc1 will only have the tag of score: 42, and not the tags at the provider level

Commands

deploy

Run sls deploy, the defined Stepfunctions are deployed.

invoke

$ sls invoke stepf --name <stepfunctionname> --data '{"foo":"bar"}'

options

  • --name or -n The name of the step function in your service that you want to invoke. Required.
  • --stage or -s The stage in your service you want to invoke your step function.
  • --region or -r The region in your stage that you want to invoke your step function.
  • --data or -d String data to be passed as an event to your step function.
  • --path or -p The path to a json file with input data to be passed to the invoked step function.

IAM Role

The IAM roles required to run Statemachine are automatically generated for each state machine in the serverless.yml, with the IAM role name of StatesExecutionPolicy-<environment>. These roles are tailored to the services that the state machine integrates with, for example with Lambda the InvokeFunction is applied. You can also specify a custom ARN directly to the step functions lambda.

Here's an example:

stepFunctions:
  stateMachines:
    hello:
      role: arn:aws:iam::xxxxxxxx:role/yourRole
      definition:

It is also possible to use the CloudFormation intrinsic functions to reference resources from elsewhere. This allows for an IAM role to be created, and applied to the state machines all within the serverless file.

The below example shows the policy needed if your step function needs the ability to send a message to an sqs queue. To apply the role either the RoleName can be used as a reference in the state machine, or the role ARN can be used like in the example above. It is important to note that if you want to store your state machine role at a certain path, this must be specified on the Path property on the new role.

stepFunctions:
  stateMachines:
    hello:
      role:
        Fn::GetAtt: ["StateMachineRole", "Arn"]
      definition:
        ...

resources:
  Resources:
    StateMachineRole:
      Type: AWS::IAM::Role
      Properties:
        RoleName: RoleName
        Path: /path_of_state_machine_roles/
        AssumeRolePolicyDocument:
          Statement:
          - Effect: Allow
            Principal:
              Service:
                - states.amazonaws.com
            Action:
              - sts:AssumeRole
        Policies:
          - PolicyName: statePolicy
            PolicyDocument:
              Version: "2012-10-17"
              Statement:
                - Effect: Allow
                  Action:
                    - lambda:InvokeFunction
                  Resource:
                    - arn:aws:lambda:lambdaName
                - Effect: Allow
                  Action:
                    - sqs:SendMessage
                  Resource:
                    - arn:aws:sqs::xxxxxxxx:queueName

The short form of the intrinsic functions (i.e. !Sub, !Ref) is not supported at the moment.

Tips

How to specify the stateMachine ARN to environment variables

Here is serverless.yml sample to specify the stateMachine ARN to environment variables. This makes it possible to trigger your statemachine through Lambda events

functions:
  hello:
    handler: handler.hello
    environment:
      statemachine_arn: ${self:resources.Outputs.MyStateMachine.Value}

stepFunctions:
  stateMachines:
    hellostepfunc:
      name: myStateMachine
      definition:
        <your definition>

resources:
  Outputs:
    MyStateMachine:
      Description: The ARN of the example state machine
      Value:
        Ref: MyStateMachine

plugins:
  - serverless-step-functions

How to split up state machines into files

When you have a large serverless project with lots of state machines your serverless.yml file can grow to a point where it is unmaintainable.

You can split step functions into external files and import them into your serverless.yml file.

There are two ways you can do this:

Single external file

You can define the entire stateMachines block in a separate file and import it in its entirety.

includes/state-machines.yml:

stateMachines:
  hellostepfunc1:
    name: myStateMachine1
    definition:
      <your definition>
  hellostepfunc2:
    name: myStateMachine2
    definition:
      <your definition>

serverless.yml:

stepFunctions:
  ${file(includes/state-machines.yml)}

plugins:
  - serverless-step-functions

Separate Files

You can split up the stateMachines block into separate files.

includes/state-machine-1.yml:

name: myStateMachine1
definition:
  <your definition>

includes/state-machine-2.yml:

name: myStateMachine2
definition:
  <your definition>

serverless.yml:

stepFunctions:
  stateMachines:
    hellostepfunc1:
      ${file(includes/state-machine-1.yml)}
    hellostepfunc2:
      ${file(includes/state-machine-2.yml)}

plugins:
  - serverless-step-functions

Sample statemachines setting in serverless.yml

Wait State

functions:
  hello:
    handler: handler.hello

stepFunctions:
  stateMachines:
    yourWateMachine:
      definition:
        Comment: "An example of the Amazon States Language using wait states"
        StartAt: FirstState
        States:
          FirstState:
            Type: Task
            Resource:
              Fn::GetAtt: [hello, Arn]
            Next: wait_using_seconds
          wait_using_seconds:
            Type: Wait
            Seconds: 10
            Next: wait_using_timestamp
          wait_using_timestamp:
            Type: Wait
            Timestamp: '2015-09-04T01:59:00Z'
            Next: wait_using_timestamp_path
          wait_using_timestamp_path:
            Type: Wait
            TimestampPath: "$.expirydate"
            Next: wait_using_seconds_path
          wait_using_seconds_path:
            Type: Wait
            SecondsPath: "$.expiryseconds"
            Next: FinalState
          FinalState:
            Type: Task
            Resource:
              Fn::GetAtt: [hello, Arn]
            End: true
plugins:
  - serverless-step-functions
  - serverless-pseudo-parameters

Retry Failure

functions:
  hello:
    handler: handler.hello

stepFunctions:
  stateMachines:
    yourRetryMachine:
      definition:
        Comment: "A Retry example of the Amazon States Language using an AWS Lambda Function"
        StartAt: HelloWorld
        States:
          HelloWorld:
            Type: Task
            Resource:
              Fn::GetAtt: [hello, Arn]
            Retry:
            - ErrorEquals:
              - HandledError
              IntervalSeconds: 1
              MaxAttempts: 2
              BackoffRate: 2
            - ErrorEquals:
              - States.TaskFailed
              IntervalSeconds: 30
              MaxAttempts: 2
              BackoffRate: 2
            - ErrorEquals:
              - States.ALL
              IntervalSeconds: 5
              MaxAttempts: 5
              BackoffRate: 2
            End: true
plugins:
  - serverless-step-functions
  - serverless-pseudo-parameters

Parallel

functions:
  hello:
    handler: handler.hello

stepFunctions:
  stateMachines:
    yourParallelMachine:
      definition:
        Comment: "An example of the Amazon States Language using a parallel state to execute two branches at the same time."
        StartAt: Parallel
        States:
          Parallel:
            Type: Parallel
            Next: Final State
            Branches:
            - StartAt: Wait 20s
              States:
                Wait 20s:
                  Type: Wait
                  Seconds: 20
                  End: true
            - StartAt: Pass
              States:
                Pass:
                  Type: Pass
                  Next: Wait 10s
                Wait 10s:
                  Type: Wait
                  Seconds: 10
                  End: true
          Final State:
            Type: Pass
            End: true
plugins:
  - serverless-step-functions
  - serverless-pseudo-parameters

Catch Failure

functions:
  hello:
    handler: handler.hello

stepFunctions:
  stateMachines:
    yourCatchMachine:
      definition:
        Comment: "A Catch example of the Amazon States Language using an AWS Lambda Function"
        StartAt: HelloWorld
        States:
          HelloWorld:
            Type: Task
            Resource:
              Fn::GetAtt: [hello, Arn]
            Catch:
            - ErrorEquals: ["HandledError"]
              Next: CustomErrorFallback
            - ErrorEquals: ["States.TaskFailed"]
              Next: ReservedTypeFallback
            - ErrorEquals: ["States.ALL"]
              Next: CatchAllFallback
            End: true
          CustomErrorFallback:
            Type: Pass
            Result: "This is a fallback from a custom lambda function exception"
            End: true
          ReservedTypeFallback:
            Type: Pass
            Result: "This is a fallback from a reserved error code"
            End: true
          CatchAllFallback:
            Type: Pass
            Result: "This is a fallback from a reserved error code"
            End: true
plugins:
  - serverless-step-functions
  - serverless-pseudo-parameters

Choice

functions:
  hello1:
    handler: handler.hello1
  hello2:
    handler: handler.hello2
  hello3:
    handler: handler.hello3
  hello4:
    handler: handler.hello4

stepFunctions:
  stateMachines:
    yourChoiceMachine:
      definition:
        Comment: "An example of the Amazon States Language using a choice state."
        StartAt: FirstState
        States:
          FirstState:
            Type: Task
            Resource:
              Fn::GetAtt: [hello, Arn]
            Next: ChoiceState
          ChoiceState:
            Type: Choice
            Choices:
            - Variable: "$.foo"
              NumericEquals: 1
              Next: FirstMatchState
            - Variable: "$.foo"
              NumericEquals: 2
              Next: SecondMatchState
            Default: DefaultState
          FirstMatchState:
            Type: Task
            Resource:
              Fn::GetAtt: [hello2, Arn]
            Next: NextState
          SecondMatchState:
            Type: Task
            Resource:
              Fn::GetAtt: [hello3, Arn]
            Next: NextState
          DefaultState:
            Type: Fail
            Cause: "No Matches!"
          NextState:
            Type: Task
            Resource:
              Fn::GetAtt: [hello4, Arn]
            End: true
plugins:
  - serverless-step-functions
  - serverless-pseudo-parameters

Map

functions:
  entry:
    handler: handler.entry
  mapTask:
    handler: handler.mapTask

stepFunctions:
  stateMachines:
    yourMapMachine:
      definition:
        Comment: "A Map example of the Amazon States Language using an AWS Lambda Function"
        StartAt: FirstState
        States:
          FirstState:
            Type: Task
            Resource:
              Fn::GetAtt: [entry, Arn]
            Next: mapped_task
          mapped_task:
            Type: Map
            Iterator:
              StartAt: FirstMapTask
              States:
                FirstMapTask:
                  Type: Task
                  Resource:
                    Fn::GetAtt: [mapTask, Arn]
                  End: true
            End: true

plugins:
  - serverless-step-functions

serverless-step-functions's People

Contributors

akshaydk avatar alanfb avatar bahrmichael avatar bayoudhi avatar bucha09 avatar cm-kajiwara avatar deconltd avatar dependabot[bot] avatar eoinsha avatar hassaku63 avatar horike37 avatar hubertpompecki avatar j0k3r avatar juancarle avatar kitsuyui avatar kuhiga avatar lolbyte-code avatar lopburny avatar maafk avatar medikoo avatar noxharmonium avatar paolorossig avatar raphaeldeem-acorns avatar shota avatar stevecaldwell77 avatar theburningmonk avatar tvhees avatar vlewin avatar yudao avatar zirkelc avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

serverless-step-functions's Issues

Serverless service prefix not included in state machine name

When I deploy "myproject" with Serverless, Lambda functions are prefixed with the service name and suffixed by stage, so they are called "myproject-myfunc-dev" etc.

Perhaps serverless-step-functions should also do the same, so that state machines are called "myproject-mymachine-dev" instead of just "mymachine-dev"? Otherwise there will be conflicts.

Step function names have changed

Example serverless file:

service: example
plugins:
  - serverless-step-functions # 1.0
stepFunctions:
  stateMachines:
    foo:
      definition: ...

Expected
The generated lambda should be named: example-justin-foo

Actual
The generated lambda is FooStepFunctionsStateMachine-2C1XDD2NCZCR

Is there any way to control the name so I can have what it was before? Specifically for my usecases it must have the stage in it, it must start with the service name and it cannot have randomness in the name.

Activities?

Can you declare activities?

I realize the implementation of the activity would not be serverless, and therefore out of the scope of this, but how would you declare an activity task in the step-function with this plugin?

Accessing provisioned name of a state machine

Does anyone have a way to access the provisioned name of a state machine?

The situation I'm considering is where we modify a state machine and re-deploy. A new state machine is created with a new postfix. We have an API function that creates a new execution that needs access to the state machine name in order to create the execution. When there are multiple state machines names [machine_name]-XXXXX with different postfix hashes we can't identify the new state machine in order to create a new execution.

Note also that the old state machine is in 'deleting' state and we can't create new executions for that either.

Do we need to create two projects, one provisioning the state machines and one provisioning everything else and using the Cloud Formation ability to reference outputs across stacks? (haven't done this before).

Adding step functions to existing project fails with undefined error

I'm updating to v1.0.0 and I hit an error where its trying to, presumably, update step functions in an existing stack that I have previously deployed but the step functions don't yet exist in that stack.

  Type Error ---------------------------------------------

     Cannot read property 'forEach' of undefined

     For debugging logs, run again after setting the "SLS_DEBUG=*" environment variable.

  Stack Trace --------------------------------------------

TypeError: Cannot read property 'forEach' of undefined
    at _.forEach (/Users/justin/code/input-system/node_modules/serverless-step-functions/lib/index.js:140:29)
    at arrayEach (/Users/justin/code/input-system/node_modules/lodash/lodash.js:537:11)
    at Function.forEach (/Users/justin/code/input-system/node_modules/lodash/lodash.js:9359:14)
    at ServerlessStepFunctions.display (/Users/justin/code/input-system/node_modules/serverless-step-functions/lib/index.js:138:7)
    at runCallback (timers.js:637:20)
    at tryOnImmediate (timers.js:610:5)
    at processImmediate [as _immediateCallback] (timers.js:582:5)
From previous event:
    at PluginManager.invoke (/Users/justin/code/input-system/node_modules/serverless/lib/classes/PluginManager.js:210:22)
    at PluginManager.run (/Users/justin/code/input-system/node_modules/serverless/lib/classes/PluginManager.js:225:17)
    at Serverless.run (/Users/justin/code/input-system/node_modules/serverless/lib/Serverless.js:97:31)
    at serverless.init.then (/Users/justin/code/input-system/node_modules/serverless/bin/serverless:23:50)

version state machines

Currently this plugin replaces a state machine when deploying a change. This could be problematic for state machines that are under heavy load as it won't delete till all executions have been completed, while this also blocks any future executions till it has been deleted.

What do you think about implementing a way of versioning state machines for example, append a version to the name (.e.g myservice-dev-mystatemachine-v1)?

AWS Region not read from provider.region

Great plugin! I noticed one problem. I have this in serverless.yml:

provider:
  stage: dev
  region: eu-west-1
  profile: xxx

When I run sls deploy stepf, the state machine itself is deployed to eu-west-1, but the Lambda ARNs point to us-east-1 so they don't work and execution fails.

It works correctly when I manually specify sls deploy stepf -r eu-west-1 .

Add support for optional name parameter

Would be nice if you could add support for an optional name property.
E.g.:

stepFunctions:
  stateMachines:
    - name: myMachineName
      MyMachine:
         <description>

I would prefer to name the step function dynamically in order reference it from within a lambda that starts executing it, instead of having to hardcode the name into the lambda

Great job with the plugin btw 👍

Add integration test

do integration test when pushing master branch and release new version.
Here is test patterns

  • http event
  • no event, only plane setting

is it possible to keep the "Sample statemachines setting in serverless.yml" section into the README?

hey!

I was searching how to use another types like catch , wait and parallel with this plugin sadly with any good information until found this one https://github.com/horike37/serverless-step-functions/blob/6d3ebb3acc149e975c77c4db41fb4a95d014b7fb/README.md#sample-statemachines-setting-in-serverlessyml . Actually I fixed my issues following those examples.

I think those examples are pretty useful to have at hand.

What do you think to keep it into the master README of this plugin?

Thanks!

Provided ARN for resource is invalid

hey guys!

I'm getting an error with the following data using the plugin after start the state machine
{"error":"States.Runtime","cause":"An error occurred while scheduling the state 'CreatePhotoDocument'. The provided ARN 'create' is invalid."}

screen shot 2017-04-19 at 16 26 24

This is part of my YML file

    provider:
      iamRoleStatements:
        - Effect: Allow
          Action:
            - states:*
          Resource: "*"

    functions:
      create:
        handler: handler.create
      resize:
        handler: handler.resize

    stepFunctions:
      stateMachines:
        photoResizeWatermark:
          events:
            - http:
                path: ''
                method: POST
                cors: true
          definition:
            StartAt: CreatePhotoDocument
            States:
              CreatePhotoDocument:
                Type: Task
                Resource: create
                Next: ResizeThumbAndPreview
              ResizeThumbAndPreview:
                Type: Task
                Resource: resize
                End: true

could you give me a hand on this please?

Thanks

choice "type" in step-functions workflow

I was playing around with serverless-step-functions and I did not find a way to configure "choice" as part of the workflow.

To accomplish something like below.
"CheckInventory": {
"Type" : "Choice",
"Choices": [
{
"Variable": "$.inventoryExists",
"BooleanEquals": true,
"Next": "ProcessOrder"
},
{
"Variable": "$.inventoryExists",
"BooleanEquals": false,
"Next": "DeclineOrderBranch"
}
]
}

Support Fn::Join for resource ARN

Other parts of the serverless.yml file can be configured to use the Fn::Join syntax to pull out the ARN for a resource. Can the plugin support the following syntax?

Resource:
  Fn::Join:
    - ":"
    - - arn
      - aws
      - lambda
      - Ref: AWS::Region
      - Ref: AWS::AccountId
      - function
      - ${self:service}-${opt:stage}-myFunction

Custom name not working

I'm very excited to be able to use a custom name! I just gave it a go and am getting an error.

The CloudFormation template is invalid: Template format error: Unresolved resource dependencies [Hellostepfunc1StepFunctionsStateMachine] in the Resources block of the template

It appears that the step function is getting created with correct name, but the resource is being referenced using the old, compiled name.

Here is an example of the serverless.yml that will cause the issue:

service: step-functions
custom:
  accountId: xxxxxxxx
plugins:
  - serverless-step-functions
provider:
  name: aws
  runtime: nodejs6.10
functions:
  hellofunc:
    handler: handler.hello
stepFunctions:
  stateMachines:
    hellostepfunc1:
      events:
        - http:
            path: api/track
            method: post
      name: myStateMachine
      definition:
        Comment: "A Hello World example of the Amazon States Language using an AWS Lambda Function"
        StartAt: HelloWorld1
        States:
          HelloWorld1:
            Type: Task
            Resource: arn:aws:lambda:${opt:region}:${self:custom.accountId}:function:${self:service}-${opt:stage}-hello
            End: true

Thanks!

Using Version 1.0.3

Choice Steps

How can I create choice states?

I'm using this way:

States:
    Task1:
      Type: Task
      Resource: arn:aws:lambda:...
      Next: ChoiceState
    
    ChoiceState:
      Type: Choice
      Choices:
        - Variable: $.var
          NumericEquals: 0
          Next: Task2
          
        - Variable: $.var
          NumericEquals: 1
          End: true

    Task2:
      Type: Task
      Resource: arn:aws:lambda:...
      End: true

deploy fails with node 6.9.2. that.sdk[service] is not a constructor

I am receiving the following error:

sls deploy stepf --state stepFuncSteps -v
Serverless: Start to deploy stepFuncSteps step function...

Type Error ---------------------------------------------

 that.sdk[service] is not a constructor

 For debugging logs, run again after setting the "SLS_DEBUG=*" environment variable.

Stack Trace --------------------------------------------

TypeError: that.sdk[service] is not a constructor
at persistentRequest (/usr/local/lib/node_modules/serverless/lib/plugins/aws/provider/awsProvider.js:149:26)
at doCall (/usr/local/lib/node_modules/serverless/lib/plugins/aws/provider/awsProvider.js:134:9)
at BbPromise (/usr/local/lib/node_modules/serverless/lib/plugins/aws/provider/awsProvider.js:145:14)
at Promise._execute (/usr/local/lib/node_modules/serverless/node_modules/bluebird/js/release/debuggability.js:299:9)
at Promise._resolveFromExecutor (/usr/local/lib/node_modules/serverless/node_modules/bluebird/js/release/promise.js:481:18)
at new Promise (/usr/local/lib/node_modules/serverless/node_modules/bluebird/js/release/promise.js:77:14)
at persistentRequest (/usr/local/lib/node_modules/serverless/lib/plugins/aws/provider/awsProvider.js:132:38)
at AwsProvider.request (/usr/local/lib/node_modules/serverless/lib/plugins/aws/provider/awsProvider.js:148:12)
at ServerlessStepFunctions.deleteStateMachine (/Users/marc/dev/message-step-functions/node_modules/serverless-step-functions/index.js:307:26)
at ServerlessStepFunctions.tryCatcher (/Users/marc/dev/message-step-functions/node_modules/bluebird/js/release/util.js:16:23)
at Promise._settlePromiseFromHandler (/Users/marc/dev/message-step-functions/node_modules/bluebird/js/release/promise.js:510:31)
at Promise._settlePromise (/Users/marc/dev/message-step-functions/node_modules/bluebird/js/release/promise.js:567:18)
at Promise._settlePromise0 (/Users/marc/dev/message-step-functions/node_modules/bluebird/js/release/promise.js:612:10)
at Promise._settlePromises (/Users/marc/dev/message-step-functions/node_modules/bluebird/js/release/promise.js:691:18)
at Async._drainQueue (/Users/marc/dev/message-step-functions/node_modules/bluebird/js/release/async.js:133:16)
at Async._drainQueues (/Users/marc/dev/message-step-functions/node_modules/bluebird/js/release/async.js:143:10)
at Immediate.Async.drainQueues (/Users/marc/dev/message-step-functions/node_modules/bluebird/js/release/async.js:17:14)
at runCallback (timers.js:637:20)
at tryOnImmediate (timers.js:610:5)
at processImmediate [as _immediateCallback] (timers.js:582:5)

Get Support --------------------------------------------
Docs: docs.serverless.com
Bugs: github.com/serverless/serverless/issues

 Please report this error. We think it might be a bug.

Your Environment Information -----------------------------
OS: darwin
Node Version: 6.9.2
Serverless Version: 1.3.0

Can not get the stateMachine Arn as the environment virables

Hi,
I have followed the tutorial in the end of the README and I'm trying to get the stateMachine's arn. However, there seems a error:
Template format error: Unresolved resource dependencies
[MyStateMachine] in the Resources block of the template

Could you help me to figure it out? I just followed the same code as the tutorial.

that.sdk[service] is not a constructor

using version 0.2.0

 sls deploy stepf  --state <stepfunctionname>

Serverless: Start to deploy registerFlow step function...

Type Error ---------------------------------------------

 that.sdk[service] is not a constructor

 For debugging logs, run again after setting the "SLS_DEBUG=*" environment variable.

Get Support --------------------------------------------
Docs: docs.serverless.com
Bugs: github.com/serverless/serverless/issues

 Please report this error. We think it might be a bug.

Your Environment Information -----------------------------
OS: darwin
Node Version: 6.2.1
Serverless Version: 1.3.0

Support Tasks Deployment

It would be cool to be able to create new tasks and reference them from the workflow
Maybe something like this:

tasks
  MyTask:
    name: my_task_custom_name_${self:provider.stage}

ServerlessError: Invalid State Machine Definition: 'SCHEMA_VALIDATION_FAILED

Hi I'm trying to get a simple Step Function to be mapped with http endpoint

stepFunctions:
  stateMachines:
    Issue2FAToken:
      events:
        - http:
            path: 2fa/step
            method: GET
      definition:
        Comment: "Issuing 2FA token to user via SMS"
        StartAt: CreateToken
        States:
          CreateToken:
            Type: Task
            Resource: createToken
            Next: SendToken
          SendToken:
            Type: Task
            Resource: sendToken
            End: true

I do get the following error. Ive checked the syntax against the examples in but cant figure out whats wrong

ServerlessError: Invalid State Machine Definition: 'SCHEMA_VALIDATION_FAILED at , SCHEMA_VALIDATION_FAILED at , SCHEMA_VALIDATION_FAILED at '
    at provider.request.then.catch (/---/two-factor-authentication/node_modules/serverless-step-functions/lib/stateMachine.js:86:13)
From previous event:
    at ServerlessStepFunctions.createStateMachine (/---/two-factor-authentication/node_modules/serverless-step-functions/lib/stateMachine.js:79:11)
    at BbPromise.map (/---/two-factor-authentication/node_modules/serverless-step-functions/lib/stateMachine.js:97:36)
    at runCallback (timers.js:649:20)
    at tryOnImmediate (timers.js:622:5)
    at processImmediate [as _immediateCallback] (timers.js:594:5)

Appreciate any help that I could get to get this working. Thanks

Error creating IAM Role for Step Functions

It looks like there are some bugs when creating IAM Role for Step Functions. This plugin try to create IAM Role when it can't find statesExecutionRole-us-east-1 role, but always fail because of some reasons.

  1. this.iamRoleName is not defined.

When createRole is invoked, this.iamRoleName variable is not set, so failing with this error message.

$ sls deploy stepf -t hellostepfunc -v
Serverless: Start to deploy hellostepfunc step function...

  Serverless Error ---------------------------------------

     Missing required key 'RoleName' in params

  Get Support --------------------------------------------
     Docs:          docs.serverless.com
     Bugs:          github.com/serverless/serverless/issues

  Your Environment Information -----------------------------
     OS:                 darwin
     Node Version:       7.1.0
     Serverless Version: 1.4.0
  1. Invalid Policy Document

Also assumeRolePolicyDocument, passed to createRole as a param, is not valid policy document. It's value must be assume role policy, not policy for invoking Lambda function. Here is a error message with passing string to this.iamRoleName.

$ sls deploy stepf -t hellostepfunc -v
Serverless: Start to deploy hellostepfunc step function...

  Serverless Error ---------------------------------------

     Has prohibited field Resource

  Get Support --------------------------------------------
     Docs:          docs.serverless.com
     Bugs:          github.com/serverless/serverless/issues

  Your Environment Information -----------------------------
     OS:                 darwin
     Node Version:       7.1.0
     Serverless Version: 1.4.0

I think it's JSON object should be looks like this.

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Service": "states.<region-defined-in-provider>.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}

And I don't know how to implement, but you have to define poliicy for invoking Lambda function somewhere in code.

Thanks for very useful plugin!

Invalid principal deploying IamRoleStateMachineExecution Role

Hi,
using
[email protected]
[email protected]

found a problem while deploying a state machine

IamRoleStateMachineExecution Invalid principal in policy: "SERVICE":"states.${opt:region, self:custom.defaultRegion}.amazonaws.com"

I'm a noob at nodejs but I managed to fix it doing in the serverless-step-functions/lib/deploy/stepFunctions/compileIamRole.js file :

- iamRoleStateMachineExecutionTemplate.replace('[region]', this.region)
+ iamRoleStateMachineExecutionTemplate.replace('[region]', this.options.region)

please see the attached patch
local_history.patch.txt

sorry for not submitting PR, but I'm not sure if the fix is right :)

Regards and keep up with this good work!

Roberto

Variables are not being replaced

Variables replaced. So something like this dosent work:

stepFunctions:
  hellostepfunc:
    Comment: "A Hello World example of the Amazon States Language using an AWS External Lambda Function"
    StartAt: HelloWorld
    States: 
      HelloWorld: 
        Type: Task
        Resource: arn:aws:lambda:${self:provider.region}:${self:custom.accountid}:function:external_hello_lambda_function
        End: true

recommended way of packaging SFN project

Hi, I have a project, which has 7 steps (functions) with a shared node_modules directory.

What is the recommended way of packaging this, do you create a separate package.json for each function and deploy this individually and use the ARNs or put all functions as sun-folders with shared node_modules?

v1.0.2 not showing commands

I have been trying to upgrade our latest project to use serverless v1.11.0 with serverless-step-functions (SSF) v1.0.2 from v0.4.0. If I try to upgrade SSF to v1.0.2/latest it no longer shows the command serverless deploy stepf.

Here is the output of running serverless

Commands
* Serverless documentation: http://docs.serverless.com
* You can run commands with "serverless" or the shortcut "sls"
* Pass "--help" after any <command> for contextual help

config credentials ............ Configures a new provider profile for the Serverless Framework
create ........................ Create new Serverless service
install ....................... Install a Serverless service from GitHub
deploy ........................ Deploy a Serverless service
deploy function ............... Deploy a single function from the service
deploy list ................... List deployed version of your Serverless Service
invoke ........................ Invoke a deployed function
invoke local .................. Invoke function locally
invoke stepf .................. Invoke Step functions
info .......................... Display information about the service
logs .......................... Output the logs of a deployed function
metrics ....................... Show metrics for a specific function
remove ........................ Remove Serverless service and all resources
rollback ...................... Rollback the Serverless service to a specific deployment
slstats ....................... Enable or disable stats

Plugins
AwsCompileAlexaSkillEvents, AwsCompileApigEvents, AwsCompileCloudWatchEventEvents, AwsCompileCloudWatchLogEvents, AwsCompileFunctions, AwsCompileIoTEvents, 
AwsCompileS3Events, AwsCompileSNSEvents, AwsCompileScheduledEvents, AwsCompileStreamEvents, AwsConfigCredentials, AwsDeploy, AwsDeployFunction, AwsDeployList,
 AwsInfo, AwsInvoke, AwsInvokeLocal, AwsLogs, AwsMetrics, AwsProvider, AwsRemove, AwsRollback, Config, Create, Deploy, Info, Install, Invoke, Logs, Metrics, Package, Plugin, Remove,
 Rollback, ServerlessStepFunctions, SlStats

As you can see ServerlessStepFunctions is registered as a plugin but isn't listed under the deploy section of commands.

> serverless deploy stepf statemachines --stage $NODE_ENV -n


  Serverless Error ---------------------------------------

     Command "deploy stepf" not found, Run "serverless help"
     for a list of all available commands.

  Stack Trace --------------------------------------------

ServerlessError: Command "deploy stepf" not found, Run "serverless help" for a list of all available commands.
    at _.reduce (/Users/colton/git/vs/fusion2.0/etl/node_modules/serverless/lib/classes/PluginManager.js:176:13)
    at arrayReduce (/Users/colton/git/vs/fusion2.0/etl/node_modules/serverless/node_modules/lodash/lodash.js:704:21)
    at Function.reduce (/Users/colton/git/vs/fusion2.0/etl/node_modules/serverless/node_modules/lodash/lodash.js:9683:14)
    at PluginManager.getCommand (/Users/colton/git/vs/fusion2.0/etl/node_modules/serverless/lib/classes/PluginManager.js:166:14)
    at PluginManager.validateCommand (/Users/colton/git/vs/fusion2.0/etl/node_modules/serverless/lib/classes/PluginManager.js:233:10)
    at Serverless.run (/Users/colton/git/vs/fusion2.0/etl/node_modules/serverless/lib/Serverless.js:83:24)
    at serverless.init.then (/Users/colton/git/vs/fusion2.0/etl/node_modules/serverless/bin/serverless:23:50)
From previous event:
    at runCallback (timers.js:666:20)
    at tryOnImmediate (timers.js:639:5)
    at processImmediate [as _immediateCallback] (timers.js:611:5)
From previous event:
    at __dirname (/Users/colton/git/vs/fusion2.0/etl/node_modules/serverless/bin/serverless:15:28)
    at Object.<anonymous> (/Users/colton/git/vs/fusion2.0/etl/node_modules/serverless/bin/serverless:27:4)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.runMain (module.js:604:10)
    at run (bootstrap_node.js:393:7)
    at startup (bootstrap_node.js:150:9)
    at bootstrap_node.js:508:3

  Get Support --------------------------------------------
     Docs:          docs.serverless.com
     Bugs:          github.com/serverless/serverless/issues
     Forums:        forum.serverless.com
     Chat:          gitter.im/serverless/serverless

  Your Environment Information -----------------------------
     OS:                 darwin
     Node Version:       6.10.1
     Serverless Version: 1.11.0

Parallel tasks do not have their arn identifiers resolved

When I try to use a parallel task the Resource's aren't being resolved within the Parallel task's Branches key.

Example serverless configuration

stepFunctions:
  createOrderStepFunc:
    Comment: "Step function that creates a new order"
    StartAt: FirstTask
    States:
      FirstTask:
        Type: Task
        Resource: firstTaskFunc
        Next: GetReports
      GetReports:
        Type: Parallel
        End: true
        Branches:
          -
            StartAt: GetReport1
            States:
              GetReport1:
                Type: Task
                Resource: getReport1Func
                End: true
          -
            StartAt: GetReport2
            States:
              GetReport2:
                Type: Task
                Resource: getReport2Func
                End: true

When this step function gets deployed to AWS, the following code is generated:

{
    "Comment": "Step function that creates a new order",
    "StartAt": "FirstTask",
    "States": {
        "FirstTask": {
            "Type": "Task",
            "Resource": "arn:aws:lambda:us-west-2:<id>:function:dev-firstTaskFunc",
            "Next": "GetReports"
        },
        "GetReports": {
            "Type": "Parallel",
            "End": true,
            "Branches": [{
                "StartAt": "GetReport1",
                "States": {
                    "GetReport1": {
                        "Type": "Task",
                        "Resource": "getReport1Func",
                        "End": true
                    }
                }
            }, {
                "StartAt": "GetReport2",
                "States": {
                    "GetReport2": {
                        "Type": "Task",
                        "Resource": "getReport2Func",
                        "End": true
                    }
                }
            }]
        }
    }
}

This step function does not work correctly, as the Resource entry within the nested States tag needs to be resolved for it to work.

Cloudwatch schedule events are not created

The Cloudwatch schedule events are not being created when deploying. Manual creation works. (aka seems its an allowed action)

stepFunctions:
  stateMachines:
    myMachine:
      events:
        - schedule: rate(5 minutes)
      definition:
        StartAt: MyStart
        States:
          MyStart:
            Type: Task
            Resource: "arn:aws:lambda:${opt:region}:${self:custom.accountId}:function:${self:service}-${opt:stage}-myFunction"
            End: true

Minor issue with empty activies in v1.0.0

I dont' have any activities and as a result my servlerless file looks sort of like:

stepFunctions:
  stateMachines:
    hello: ...

As a result I am getting this error:

Serverless: Packaging service...

  Serverless Error ---------------------------------------

     activities property is not an array Please check the
     README for more info.

Simply changing my file to this fixes it:

stepFunctions:
  activities: []
  stateMachines:
    hello: ...

But it seems like activities should default to an empty array automatically instead of null in this case.

Chosing the IAM Role

It would be great to enable us to pick the name of the execution role:

e.g.

stepFunctions:
  role: arn:aws:iam:::role/InsertYourFavoriteRoleNameHere
  stateMachines:
    myStateMachine:
      Comment: 'A state machine'
...```

Name is getting changed

I set a custom name "ProcessImage-s3" to my step function.
Now it turns out the created function is actually named "ProcessImageDashs3".

I noticed this because I tried refererncing the step function using ${self:resources.Outputs.processImageStepFunction.Value} and I got the following error:

The CloudFormation template is invalid: Template format error: Unresolved resource dependencies [ProcessImage-s3] in the Resources block of the template

Add the current `stage` name into the State Machine name

I have multiple stages deployed to my account and currently this:

stepFunctions:
  stateMachines:
    Example: ...

Will create a StateMachine like this:

ExampleStepFunctionsStateMachine-QWUYMJP6O0QH

The problem is that I have maybe half a dozen stages in a single account and I cannot tell the difference between them now. I would have 6 ExampleStepFunctionStateMachine-* state machines and there is no way to distinguish which is staging and which is prod for example.

What would be really nice is just if the name of the created state machine also had the stage in it, for example:

ExampleProdStepFunctionsStateMachine-QWUYMJP6O0QH
ExampleStagStepFunctionsStateMachine-IOUME4NGKVE2

etc.

Schema Validation

I've noticed that I can only name my states certain things. Several characters are excluded. I would appreciate not having to name my States in CamelCasingBecauseItIsntFun.

If there is a way you can change how we have to structure the yml in a different way so we can use spaces between words, it would be appreciated.

BTW, thanks for the fix for not requiring a state name to be passed.

Specification with v1.0

Hi everyone.
We discussed about including the step functions feature into Serverless Core for a while.
However, We decided to postpone that finally. The reason for that we should decide how to manage a plovider specific feature(Serverless is multi-provider support)
See the detail: serverless/serverless#3024

Therefore I will update the plugin to v1.0 and out of beta, based feedback I got.
Here is specification for v1.0. If you have any ideas, please comment here!

Specification for v1.0

serverless.yml

provider:
  name: aws
  runtime: nodejs4.3

functions:
  hellofunc:
    handler: handler.hello

stepFunctions:
  stateMachines:
    myStateMachine1:
      role: arn:aws:iam:::role/InsertYourFavoriteRoleNameHere #Optional, you can chose the existing IAM Role
      events: #Here is events for stepfunctions. You can define http, schedule and cloudwatchEvent.
        - http:
          method: GET
          path: executeMyStateMachine
        - schedule: rate(2 hours)
        - cloudwatchEvent:
          event:
            source:
              - "aws.ec2"
            detail-type:
              - "EC2 Instance State-change Notification"
            detail:
              state:
                - pending
      definition: #Required. Here is the Amazon States Language definition.
        Comment: "A Hello World example of the Amazon States Language using an AWS Lambda Function"
        StartAt: HelloWorld1
        States: 
          HelloWorld1:
            Type: Task
            Resource: [lambda name | activity name | lambda ARN | activity ARN | Fn::GetAtt (lambda) | Fn::Ref (activity) | Fn::ImportValue]
            End: true
  activities: #Here is Task activites
    - myTask

deploy

Include this in sls deploy without adding new commands.

invoke

Add sls invoke --stepfunction <statemachin name> option. -sf is as short version.

Don't remove superceded State machines

I'd like to suggest that we don't remove a superceded state machine when it is modified and redeployed.

It's highly likely, over the life of a solution employing step functions, that a step function will be modified where there are completed and in-progress executions. I understand that the step function won't be deleted until all executions are complete, however we want to keep the history of a step function and retain access to completed executions.

With the current behaviour of the plugin we remove the old version as soon as all executions are completed (at least as far as I can see).

Interested in other opinions or other ways to retain history of executions.

Feature Request: Not 0 exit status when fail.

$ sls invoke stepf -t hello_automation
Serverless: Start function hello_automation...


Execution Result -----------------------------------------

{ ...
  status: 'FAILED',
  input: '{}' }

Error Log ------------------------------------------------

{ cause: 'some error' }
$ echo $?
0

現状このように、成功・失敗にかかわらず
終了ステータスコードが 0 になっていると思います。
Unix 的な伝統にもとづき、失敗した時は 0 以外で終了するような機能があるとよいな、と思います。

Since 1.0.3 no more cf step is generated

When i upgrade to 1.0.3/1.0.4, the plugin has stopped generating the step function. The definition hasn't changed, find here an extract :

stepFunctions:
  stateMachines:
    fullIndex:
      name: myStateMachine
      role: arn:aws:iam::${self:custom.${opt:stage}.accountId}:role/service-role/StatesExecutionRole-${opt:region} 
      events:
        - http:
            path: /admin/trigger-full-index
            method: GET
      definition:
        Comment: ""
        StartAt: FullIndex
        States:
          FullIndex:
            Type: Task
            Resource: arn:aws:lambda:${opt:region}:${self:custom.${opt:stage}.accountId}:function:service-${opt:stage}-FullIndex
            Next: DeleteIndexes
          DeleteIndexes:
            Type: Task
            Resource: arn:aws:lambda:${opt:region}:${self:custom.${opt:stage}.accountId}:function:service-${opt:stage}-DeleteIndexes        
            End: true

Have you an idea ?
How to see the logs ?

Deprecation warnings upon deploy

Nice work you're doing here. You probably already know this but FYI:

$ sls --version
1.12.1

$ SLS_DEBUG=* sls deploy
Serverless: WARNING: Plugin ServerlessStepFunctions uses deprecated hook deploy:initialize
Serverless: WARNING: Plugin ServerlessStepFunctions uses deprecated hook deploy:compileFunctions
Serverless: WARNING: Plugin ServerlessStepFunctions uses deprecated hook deploy:compileEvents
Serverless: Packaging service...

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.