Skip to main content

Command Palette

Search for a command to run...

How to use Terraform to define cloud watch event rules to trigger the Stepfunction state machine

Published
1 min read

For this, we have to do the following Terraform Configuration:

  1. Define the rule for the CloudWatch event:

    resource "aws_cloudwatch_event_rule" "example" {

    name = "trigger-stepfunction"

    description = "Rule to trigger Step Functions state machine"

    event_pattern = jsonencode({

    "source" : ["aws.s3"],

    "detail-type" : ["Object Created"],

    "detail" : {

    "bucket-name" : ["your-bucket-name"]

    }

    })

    }

  2. Create the IAM role for the Cloudwatch event:

    resource "aws_iam_role" "event_to_stepfunction" {

name = "event-to-stepfunction-role"

assume_role_policy = jsonencode({

"Version": "2012-10-17",

"Statement": [

{

"Action": "sts:AssumeRole",

"Effect": "Allow",

"Principal": {

"Service": "events.amazonaws.com"

}

}

]

})

}

resource "aws_iam_policy" "stepfunction_policy" {

name = "stepfunction-trigger-policy"

description = "Policy to allow CloudWatch Events to trigger Step Functions"

policy = jsonencode({

"Version": "2012-10-17",

"Statement": [

{

"Effect": "Allow",

"Action": [

"states:StartExecution"

],

"Resource": "arn:aws:states:REGION:ACCOUNT_ID:stateMachine:YOUR_STATE_MACHINE_NAME"

}

]

})

}

resource "aws_iam_role_policy_attachment" "attach_policy" {

role = aws_iam_role.event_to_stepfunction.name

policy_arn = aws_iam_policy.stepfunction_policy.arn

}

  1. Create a Target for the Cloudwatch event

resource "aws_cloudwatch_event_target" "example" {

rule = aws_cloudwatch_event_rule.example.name

target_id = "stepfunction-target"

arn = "arn:aws:states:REGION:ACCOUNT_ID:stateMachine:YOUR_STATE_MACHINE_NAME"

role_arn = aws_iam_role.event_to_stepfunction.arn

}

  1. Apply the above Terraform Configuration

    • terraform init

    • terraform plan

    • terraform apply