如何使用aws cdk为cloudwatch事件规则向目标添加输入转换?

时间:2019-12-30 07:40:29

标签: aws-cdk

创建云监视事件规则后,我尝试向其添加目标,但无法添加输入转换。以前,添加目标具有允许输入转换的道具,但现在不再支持。

codeBuildRule.addTarget(new SnsTopic(props.topic));

aws cdk页面提供了此解决方案,但我不完全理解它的意思

您可以使用eventRule.addTarget(target [,input])通过可选的输入转换器添加其他目标。例如,我们可以添加一个SNS主题目标,该目标目标格式化提交内容的可读信息。

2 个答案:

答案 0 :(得分:0)

您应指定message道具并使用RuleTargetInput static methods。其中一些方法可以使用EventField.fromPath()返回的字符串:

// From a path
codeBuildRule.addTarget(new SnsTopic(props.topic, {
  message: events.RuleTargetInput.fromEventPath('$.detail')
}));

// Custom object
codeBuildRule.addTarget(new SnsTopic(props.topic, {
  message: RuleTargetInput.fromObject({
    foo: EventField.fromPath('$.detail.bar')
  })
}));

答案 1 :(得分:0)

我尝试在CDK中实施本教程时遇到了相同的问题:Tutorial: Set up a CloudWatch Events rule to receive email notifications for pipeline state changes

我发现这也有帮助:Detect and react to changes in pipeline state with Amazon CloudWatch Events

注意:我无法使用管道的类方法onStateChange()使其工作。

我最终写了一条规则:

const topic = new Topic(this, 'topic', {topicName: 'codepipeline-notes-failure',
});

const description = `Generated by the CDK for stack: ${this.stackName}`;
new Rule(this, 'failed', {
  description: description,
  eventPattern: {
    detail: {state: ['FAILED'], pipeline: ['notes']},
    detailType: ['CodePipeline Pipeline Execution State Change'],
    source: ['aws.codepipeline'],
  },
  targets: [
    new SnsTopic(topic, {
      message: RuleTargetInput.fromText(
        `The Pipeline '${EventField.fromPath('$.detail.pipeline')}' has ${EventField.fromPath(
          '$.detail.state',
        )}`,
      ),
    }),
  ],
});

实施后,如果您导航到Amazon EventBridge->规则,然后选择规则,然后选择目标,然后单击查看详细信息,您将看到带有输入转换器和InputTemplate的目标详细信息。

输入变压器: {“ InputPathsMap”:{“ detail-pipeline”:“ $。detail.pipeline”,“ detail-state”:“ $。detail.state”},“ InputTemplate”:“ \” The 管道''具有 \“”}