Schedule AWS State Machine (AWS Step Functions) using AWS CloudWatch rules with AWS CLI

Execute State Machine using CloudWatch Events

In this story we will see how we can schedule an AWS State Machine to execute automatically at pre-scheduled time using AWS CloudWatch rules with AWS CLI.

End Goal

Schedule an AWS State Machine to execute automatically every Saturday at 00:00 GMT

Prerequisite

  1. We have already configured AWS cli in our machine.
  2. We already have a state machine created in our AWS account.

Step to schedule AWS State Machine

  1. Create an IAM Role which has the permission to access & trigger our State Machine.
  2. Create a CloudWatch rule which will get automatically executed at our schedule time.
  3. Attach our state machine to the CloudWatch rule created.
  1. Creating IAM Role

As we are creating IAM role for CloudWatch Events we need to pass the service as events.amazonaws.com in trust policy of role.

https://raw.githubusercontent.com/atulquest93/step-function-cron/main/cloudwatch-event-role-trust-policy.json

Now create the role using the CLI command

aws iam create-role --role-name state-machine-role --assume-role-policy-document file://cloudwatch-event-role-trust-policy.json

As our role is created we need to attach policy to role to access & execute state machine.

https://raw.githubusercontent.com/atulquest93/step-function-cron/main/state-machine-execution-policy.json

Now attach this policy to our role.

aws iam put-role-policy --role-name state-machine-role --policy-name state-machine-execution-policy --policy-document file://state-machine-execution-policy.json

Now our role is ready.

2. Create a CloudWatch Event rule

Now we will create a CloudWatch rule which will execute every Saturday.

aws events put-rule --name state-machine-rule --schedule-expression “cron(0 0 ? * SAT *)” --state “ENABLED”

3. Attach state machine to the rule

As our rule is now created , we need to attach the state machine to the rule.

aws events put-targets --rule state-machine-rulee --targets “Id”=”1",”Arn”=”state_machine_arn”, ”RoleArn”=”iam_role_arn”

Complete Script

Here’s the complete script to achieve the goal.

# 1. Create IAM Role
aws iam create-role --role-name state-machine-role --assume-role-policy-document file://cloudwatch-event-role-trust-policy.json

# 2. Attach Policy to role
#Don't forgot to update State machine ARN in state-machine-execution-policy.json file.
aws iam put-role-policy --role-name state-machine-role --policy-name state-machine-execution-policy --policy-document file://state-machine-execution-policy.json

# 3. Create CloudWatch Event
aws events put-rule --name state-machine-rule --schedule-expression "cron(0 0 ? * SAT *)" --state "ENABLED"

# 4. Attach State Machine to rule
aws events put-targets --rule state-machine-rule --targets "Id"="1","Arn"="$statemachine","RoleArn"="$rolearn","Input"='"{}"'