如何在AWS Step Functions中无需Lambda提取指定JSON字段到SNS消息?
问题描述
我正在构建一个接收JSON格式输入的AWS Step Functions状态机,希望仅使用输入JSON中的部分字段生成通过SNS发送的消息。我尝试使用了ASL内置JSON操作函数,但未能成功实现。请问是否存在无需使用Lambda函数即可为SNS消息提取指定JSON字段的方法?
我原本期望Message字段可以这样写:
message.$: $.name $.questions etc...
但这种写法无法正常工作。
以下是我的代码示例:
stepFunctions: stateMachines: hellostepfunc1: name: test definition: Comment: "test" StartAt: SNSState States: SNSState: Type: Task InputPath: $ Resource: arn:aws:states:::sns:publish Parameters: TopicArn: Fn::GetAtt: [ MyTopic, TopicArn ] Message.$: $ // 这里我想发送多个字段,比如 $.name 和 $.questions End: true
解决方案
完全可以不用Lambda,直接借助ASL的内置函数构造符合需求的SNS消息,以下是两种常见场景的实现方式:
1. 生成JSON格式消息
如果需要将指定字段包装成JSON结构发送,可直接构造新的JSON对象并转为字符串:
Parameters: TopicArn: Fn::GetAtt: [ MyTopic, TopicArn ] Message.$: States.JsonToString({ "name": "$.name", "questions": "$.questions" })
States.JsonToString会把构造的JSON对象转换为字符串,满足SNS消息的格式要求。
2. 生成纯文本格式消息
如果需要拼接字段为纯文本内容,比如"用户:xxx,问题列表:xxx",可以用States.Format函数:
Parameters: TopicArn: Fn::GetAtt: [ MyTopic, TopicArn ] Message.$: States.Format("用户:{},问题列表:{}", $.name, $.questions)
关键注意点
- ASL内置函数的调用必须严格遵循语法规范,函数名、参数格式不能出错
- 若目标字段可能不存在,可结合
States.IsPresent函数做容错处理,避免状态机执行失败
内容的提问来源于stack exchange,提问作者Fred
相关产品推荐
相关产品推荐

