Skip to content
v2.274.0

CustomState ​

State defined by supplying Amazon States Language (ASL) in the state machine.

Example ​

ts
import * as dynamodb from 'aws-cdk-lib/aws-dynamodb';

// create a table
const table = new dynamodb.Table(this, 'montable', {
  partitionKey: {
    name: 'id',
    type: dynamodb.AttributeType.STRING,
  },
});

const finalStatus = new sfn.Pass(this, 'final step');

// States language JSON to put an item into DynamoDB
// snippet generated from https://docs.aws.amazon.com/step-functions/latest/dg/tutorial-code-snippet.html#tutorial-code-snippet-1
const stateJson = {
  Type: 'Task',
  Resource: 'arn:aws:states:::dynamodb:putItem',
  Parameters: {
    TableName: table.tableName,
    Item: {
      id: {
        S: 'MyEntry',
      },
    },
  },
  ResultPath: null,
};

// custom state which represents a task to insert data into DynamoDB
const custom = new sfn.CustomState(this, 'my custom task', {
  stateJson,
});

// catch errors with addCatch
const errorHandler = new sfn.Pass(this, 'handle failure');
custom.addCatch(errorHandler);

// retry the task if something goes wrong
custom.addRetry({
  errors: [sfn.Errors.ALL],
  interval: Duration.seconds(10),
  maxAttempts: 5,
});

const chain = sfn.Chain.start(custom)
  .next(finalStatus);

const sm = new sfn.StateMachine(this, 'StateMachine', {
  definitionBody: sfn.DefinitionBody.fromChainable(chain),
  timeout: Duration.seconds(30),
  comment: 'a super cool state machine',
});

// don't forget permissions. You need to assign them
table.grantWriteData(sm);
python
import aws_cdk.aws_dynamodb as dynamodb


# create a table
table = dynamodb.Table(self, "montable",
    partition_key=dynamodb.Attribute(
        name="id",
        type=dynamodb.AttributeType.STRING
    )
)

final_status = sfn.Pass(self, "final step")

# States language JSON to put an item into DynamoDB
# snippet generated from https://docs.aws.amazon.com/step-functions/latest/dg/tutorial-code-snippet.html#tutorial-code-snippet-1
state_json = {
    "Type": "Task",
    "Resource": "arn:aws:states:::dynamodb:putItem",
    "Parameters": {
        "TableName": table.table_name,
        "Item": {
            "id": {
                "S": "MyEntry"
            }
        }
    },
    "ResultPath": null
}

# custom state which represents a task to insert data into DynamoDB
custom = sfn.CustomState(self, "my custom task",
    state_json=state_json
)

# catch errors with addCatch
error_handler = sfn.Pass(self, "handle failure")
custom.add_catch(error_handler)

# retry the task if something goes wrong
custom.add_retry(
    errors=[sfn.Errors.ALL],
    interval=Duration.seconds(10),
    max_attempts=5
)

chain = sfn.Chain.start(custom).next(final_status)

sm = sfn.StateMachine(self, "StateMachine",
    definition_body=sfn.DefinitionBody.from_chainable(chain),
    timeout=Duration.seconds(30),
    comment="a super cool state machine"
)

# don't forget permissions. You need to assign them
table.grant_write_data(sm)
java
import software.amazon.awscdk.services.dynamodb.*;


// create a table
Table table = Table.Builder.create(this, "montable")
        .partitionKey(Attribute.builder()
                .name("id")
                .type(AttributeType.STRING)
                .build())
        .build();

Pass finalStatus = new Pass(this, "final step");

// States language JSON to put an item into DynamoDB
// snippet generated from https://docs.aws.amazon.com/step-functions/latest/dg/tutorial-code-snippet.html#tutorial-code-snippet-1
Map<String, Object> stateJson = Map.of(
        "Type", "Task",
        "Resource", "arn:aws:states:::dynamodb:putItem",
        "Parameters", Map.of(
                "TableName", table.getTableName(),
                "Item", Map.of(
                        "id", Map.of(
                                "S", "MyEntry"))),
        "ResultPath", null);

// custom state which represents a task to insert data into DynamoDB
CustomState custom = CustomState.Builder.create(this, "my custom task")
        .stateJson(stateJson)
        .build();

// catch errors with addCatch
Pass errorHandler = new Pass(this, "handle failure");
custom.addCatch(errorHandler);

// retry the task if something goes wrong
custom.addRetry(RetryProps.builder()
        .errors(List.of(Errors.ALL))
        .interval(Duration.seconds(10))
        .maxAttempts(5)
        .build());

Chain chain = Chain.start(custom).next(finalStatus);

StateMachine sm = StateMachine.Builder.create(this, "StateMachine")
        .definitionBody(DefinitionBody.fromChainable(chain))
        .timeout(Duration.seconds(30))
        .comment("a super cool state machine")
        .build();

// don't forget permissions. You need to assign them
table.grantWriteData(sm);
csharp
// Install: dotnet add package Amazon.CDK.Lib
using Amazon.CDK.AWS.DynamoDB;


// create a table
var table = new Table(this, "montable", new TableProps {
    PartitionKey = new Attribute {
        Name = "id",
        Type = AttributeType.STRING
    }
});

var finalStatus = new Pass(this, "final step");

// States language JSON to put an item into DynamoDB
// snippet generated from https://docs.aws.amazon.com/step-functions/latest/dg/tutorial-code-snippet.html#tutorial-code-snippet-1
IDictionary<string, object> stateJson = new Dictionary<string, object> {
    { "Type", "Task" },
    { "Resource", "arn:aws:states:::dynamodb:putItem" },
    { "Parameters", new Dictionary<string, object> {
        { "TableName", table.TableName },
        { "Item", new Dictionary<string, IDictionary<string, string>> {
            { "id", new Dictionary<string, string> {
                { "S", "MyEntry" }
            } }
        } }
    } },
    { "ResultPath", null }
};

// custom state which represents a task to insert data into DynamoDB
var custom = new CustomState(this, "my custom task", new CustomStateProps {
    StateJson = stateJson
});

// catch errors with addCatch
var errorHandler = new Pass(this, "handle failure");
custom.AddCatch(errorHandler);

// retry the task if something goes wrong
custom.AddRetry(new RetryProps {
    Errors = new [] { Errors.ALL },
    Interval = Duration.Seconds(10),
    MaxAttempts = 5
});

var chain = Chain.Start(custom).Next(finalStatus);

var sm = new StateMachine(this, "StateMachine", new StateMachineProps {
    DefinitionBody = DefinitionBody.FromChainable(chain),
    Timeout = Duration.Seconds(30),
    Comment = "a super cool state machine"
});

// don't forget permissions. You need to assign them
table.GrantWriteData(sm);
go
// Install: go get github.com/aws/aws-cdk-go/awscdk/v2
import "github.com/aws/aws-cdk-go/awscdk"


// create a table
table := dynamodb.NewTable(this, jsii.String("montable"), &TableProps{
	PartitionKey: &Attribute{
		Name: jsii.String("id"),
		Type: dynamodb.AttributeType_STRING,
	},
})

finalStatus := sfn.NewPass(this, jsii.String("final step"))

// States language JSON to put an item into DynamoDB
// snippet generated from https://docs.aws.amazon.com/step-functions/latest/dg/tutorial-code-snippet.html#tutorial-code-snippet-1
stateJson := map[string]interface{}{
	"Type": jsii.String("Task"),
	"Resource": jsii.String("arn:aws:states:::dynamodb:putItem"),
	"Parameters": map[string]interface{}{
		"TableName": table.tableName,
		"Item": map[string]map[string]*string{
			"id": map[string]*string{
				"S": jsii.String("MyEntry"),
			},
		},
	},
	"ResultPath": nil,
}

// custom state which represents a task to insert data into DynamoDB
custom := sfn.NewCustomState(this, jsii.String("my custom task"), &CustomStateProps{
	StateJson: StateJson,
})

// catch errors with addCatch
errorHandler := sfn.NewPass(this, jsii.String("handle failure"))
custom.AddCatch(errorHandler)

// retry the task if something goes wrong
custom.AddRetry(&RetryProps{
	Errors: []*string{
		sfn.Errors_ALL(),
	},
	Interval: awscdk.Duration_Seconds(jsii.Number(10)),
	MaxAttempts: jsii.Number(5),
})

chain := sfn.Chain_Start(custom).Next(finalStatus)

sm := sfn.NewStateMachine(this, jsii.String("StateMachine"), &StateMachineProps{
	DefinitionBody: sfn.DefinitionBody_FromChainable(chain),
	Timeout: awscdk.Duration_*Seconds(jsii.Number(30)),
	Comment: jsii.String("a super cool state machine"),
})

// don't forget permissions. You need to assign them
table.GrantWriteData(sm)

Initializer ​

ts
new CustomState(scope: Construct, id: string, props: CustomStateProps)
python
CustomState(scope: Construct, id: str, props: CustomStateProps)
java
new CustomState(Construct scope, String id, CustomStateProps props)
csharp
new CustomState(Construct scope, string id, CustomStateProps props)
go
NewCustomState(Scope Construct, Id *string, Props CustomStateProps)

Construct Props ​

stateJson{ [key: string]: any }state_jsontyping.Mapping[str, Any]stateJsonMap<String, Object>StateJsonIDictionary<string, object>StateJson*map[string]interface{}required#
Amazon States Language (JSON-based) definition of the state.

Properties ​

endStatesINextable[]end_statestyping.List[INextable]endStatesList<INextable>EndStatesINextable[]EndStates*[]INextablerequired#
Continuable states of this Chainable.
idstringidstridStringIdstringId*stringrequired#
Descriptive identifier for this chainable.
nodeNodenodeNodenodeNodeNodeNodeNodeNoderequired#
The tree node.
startStateStatestart_stateStatestartStateStateStartStateStateStartStateStaterequired#
First state of this Chainable.
stateIdstringstate_idstrstateIdStringStateIdstringStateId*stringrequired#
Tokenized string that evaluates to the state's ID.

Methods ​

addCatch(handler: IChainable, props?: CatchProps): CustomState // chainabledef add_catch(self, handler: IChainable, props: typing.Optional[CatchProps] = None) -> CustomStatepublic CustomState addCatch(IChainable handler, CatchProps props)public CustomState AddCatch(IChainable handler, CatchProps? props = null)func AddCatch(Handler IChainable, Props CatchProps) CustomState#
Add a recovery handler for this state.

When a particular error occurs, execution will continue at the error handler instead of failing the state machine execution.

addPrefix(x: string): voiddef add_prefix(self, x: str) -> Nonepublic void addPrefix(String x)public void AddPrefix(string x)func AddPrefix(X *string)#
Add a prefix to the stateId of this state.
addRetry(props?: RetryProps): CustomState // chainabledef add_retry(self, props: typing.Optional[RetryProps] = None) -> CustomStatepublic CustomState addRetry(RetryProps props)public CustomState AddRetry(RetryProps? props = null)func AddRetry(Props RetryProps) CustomState#
Add retry configuration for this state.

This controls if and how the execution will be retried if a particular error occurs.

bindToGraph(graph: StateGraph): voiddef bind_to_graph(self, graph: StateGraph) -> Nonepublic void bindToGraph(StateGraph graph)public void BindToGraph(StateGraph graph)func BindToGraph(Graph StateGraph)#
Register this state as part of the given graph.

Don't call this. It will be called automatically when you work with states normally.

filterNextables(states: State[]): INextable[]@staticmethod def filter_nextables(states: typing.List[State]) -> typing.List[INextable]public static List<INextable> filterNextables(List<State> states)public static INextable[] FilterNextables(State[] states)func FilterNextables(States *[]State) *[]INextablestatic#
Return only the states that allow chaining from an array of states.
findReachableEndStates(start: State, options?: FindStateOptions): State[]@staticmethod def find_reachable_end_states(start: State, options: typing.Optional[FindStateOptions] = None) -> typing.List[State]public static List<State> findReachableEndStates(State start, FindStateOptions options)public static State[] FindReachableEndStates(State start, FindStateOptions? options = null)func FindReachableEndStates(Start State, Options FindStateOptions) *[]Statestatic#
Find the set of end states states reachable through transitions from the given start state.
findReachableStates(start: State, options?: FindStateOptions): State[]@staticmethod def find_reachable_states(start: State, options: typing.Optional[FindStateOptions] = None) -> typing.List[State]public static List<State> findReachableStates(State start, FindStateOptions options)public static State[] FindReachableStates(State start, FindStateOptions? options = null)func FindReachableStates(Start State, Options FindStateOptions) *[]Statestatic#
Find the set of states reachable through transitions from the given start state.

This does not retrieve states from within sub-graphs, such as states within a Parallel state's branch.

isConstruct(x: any): boolean@staticmethod def is_construct(x: Any) -> boolpublic static Boolean isConstruct(Object x)public static bool IsConstruct(object x)func IsConstruct(X interface{}) *boolstatic#
Checks if `x` is a construct.
notes · 1 parameter · returns

Use this method instead of instanceof to properly detect Construct instances, even when the construct library is symlinked.

Explanation: in JavaScript, multiple copies of the constructs library on disk are seen as independent, completely different libraries. As a consequence, the class Construct in each copy of the constructs library is seen as a different class, and an instance of one class will not test as instanceof the other class. npm install will not create installations like this, but users may manually symlink construct libraries together or use a monorepo tool: in those cases, multiple copies of the constructs library can be accidentally installed, and instanceof will behave unpredictably. It is safest to avoid using instanceof, and using this type-testing method instead.

Parameters

  • xxxxX — Any object.

Returns: true if x is an object created from a class which extends Construct.

prefixStates(root: IConstruct, prefix: string): void@staticmethod def prefix_states(root: IConstruct, prefix: str) -> Nonepublic static void prefixStates(IConstruct root, String prefix)public static void PrefixStates(IConstruct root, string prefix)func PrefixStates(Root IConstruct, Prefix *string)static#
Add a prefix to the stateId of all States found in a construct tree.
toStateJson(queryLanguage?: QueryLanguage): jsondef to_state_json(self, query_language: typing.Optional[QueryLanguage] = None) -> Anypublic Object toStateJson(QueryLanguage queryLanguage)public object ToStateJson(QueryLanguage? queryLanguage = null)func ToStateJson(QueryLanguage QueryLanguage) interface{}#
Returns the Amazon States Language object for this state.
toString(): stringdef to_string(self, ) -> strpublic String toString()public string ToString()func ToString() *string#
Returns a string representation of this construct.
with(...mixins: IMixin[]): IConstructdef with(self, mixins: IMixin) -> IConstructpublic IConstruct with(IMixin mixins)public IConstruct With(IMixin mixins)func With(Mixins IMixin) IConstruct#
Applies one or more mixins to this construct.

Mixins are applied in order. The list of constructs is captured at the start of the call, so constructs added by a mixin will not be visited. Use multiple with() calls if subsequent mixins should apply to added constructs.

1 parameter · returns

Parameters

  • mixinsmixinsmixinsmixinsMixins — The mixins to apply.

Returns: This construct for chaining