要实现“AWS SQS 触发 Step Functions”,可以按照以下步骤进行操作:
下面是一个使用 AWS SDK for Python (Boto3) 的代码示例,演示如何实现上述步骤:
import boto3
sqs_client = boto3.client('sqs')
response = sqs_client.create_queue(
QueueName='my-sqs-queue'
)
queue_url = response['QueueUrl']
import boto3
stepfunctions_client = boto3.client('stepfunctions')
state_machine_definition = {
"Comment": "A Hello World example of the Amazon States Language using a Pass state",
"StartAt": "HelloWorld",
"States": {
"HelloWorld": {
"Type": "Pass",
"Result": "Hello, World!",
"End": True
}
}
}
response = stepfunctions_client.create_state_machine(
name='my-state-machine',
definition=json.dumps(state_machine_definition),
roleArn='arn:aws:iam::123456789012:role/StepFunctions-HelloWorld'
)
state_machine_arn = response['stateMachineArn']
import boto3
sqs_client = boto3.client('sqs')
response = sqs_client.set_queue_attributes(
QueueUrl='my-sqs-queue-url',
Attributes={
'Policy': json.dumps({
"Version": "2012-10-17",
"Statement": [
{
"Sid": "Allow-StepFunctions-Access",
"Effect": "Allow",
"Principal": {
"Service": "states.amazonaws.com"
},
"Action": "SQS:SendMessage",
"Resource": "arn:aws:sqs:us-east-1:123456789012:my-sqs-queue",
"Condition": {
"ArnEquals": {
"aws:SourceArn": "arn:aws:states:us-east-1:123456789012:stateMachine:my-state-machine"
}
}
}
]
})
}
)
这样,当 SQS 队列中有新的消息时,消息将触发 Step Functions 状态机的执行。你可以根据实际需求修改示例代码中的参数和配置,以适应你的场景。