AWS CDK Step Functions SNS 任务 - 注入到消息中的输入路径参数

AWS CDK Step Functions SNS Task - input path parameter injected into message

我正在尝试制作一个步骤函数工作流来处理交易并在交易成功时广播消息。 想出了这样的事情:

new SnsPublish(this, 'publish-successful-transaction', {
            message: TaskInput.fromText(`transaction #${TaskInput.fromJsonPathAt('$.transactionId')} was processed successfully!`),
            resultPath: '$.message',
            topic: this.notification.topic
        })

但是,可以预见的是 .fromJsonPath() returns TaskInput 的实例会导致正常的字符串中对象行为,即 [Object object].

我尝试从 TaskInput 实例获取 value 属性 但这导致错误:

Error: Field references must be the entire string, cannot concatenate them
(found 'transaction #${Token[transactionId.269]} was processed successfully!')

有没有办法让自定义短信带有注入的输入路径参数?尽管它看起来像是一个非常简单的用例,但似乎无法找到任何东西。我错过了什么?

原来有一个简单的 one-line 解决方案:

message: sfn.TaskInput.fromJsonPathAt("States.Format('transaction {} was processed successfully!', $.transactionId)")

答案的原始选项有效但更冗长


Step Functions 有一个 States.Format intrinsic function 来插入字符串。 但由于并非所有领域都接受内在函数(包括 SnsPublish.message 中的不接受),因此解决方案并不像您希望的那么简单。

首先,格式化。内部函数有两个等效的 CDK 语法:

// produce identical State Machine JSON output:
{
  // State Machine Language JSON Syntax - DON'T FORGET .$ SUFFIX IN THE KEY
  'myMessage.$' "States.Format('transaction {} was processed successfully!', $.transactionId)",
  // JsonPath helpers - CDK only
  sameMessage: sfn.JsonPath.format('transaction {} was processed successfully!', sfn.JsonPath.stringAt('$.transactionId'))
}

接下来,您有两种连接方式:

选项 1:sfn.Pass + tasks.SnsPublish

添加一个Pass任务来格式化消息并在SnsPublish的消息中使用结果属性:

const formatMessage = new sfn.Pass(this, 'formatMessage', {
  parameters: { 'message.$': "States.Format('transaction {} was processed successfully!', $.transactionId)", },
  resultPath: '$.formatted',
});

const snsPublish = new tasks.SnsPublish(this, 'SnsPublish', {
  topic: this.notification.topic,
  message: sfn.TaskInput.fromJsonPathAt('$.formatted.message'),
});

选项 2:tasks.CallAwsService

通用 CallAwsService 任务的 parameters 属性 可以处理内部函数。单任务状态下格式化发布:

const snsPublish2 = new tasks.CallAwsService(this, 'SnsPublish2', {
  service: 'sns',
  action: 'publish',
  parameters: {
    TopicArn: this.notification.topic.topicArn,
    'Message.$': "States.Format('transaction {} was processed successfully!', $.transactionId)",
  },
  iamResources: [this.notification.topic.topicArn],
});