|
| 1 | +import events = require('@aws-cdk/aws-events'); |
| 2 | +import iam = require('@aws-cdk/aws-iam'); |
| 3 | +import sqs = require('@aws-cdk/aws-sqs'); |
| 4 | + |
| 5 | +/** |
| 6 | + * Customize the SQS Queue Event Target |
| 7 | + */ |
| 8 | +export interface SqsQueueProps { |
| 9 | + |
| 10 | + /** |
| 11 | + * Message Group ID for messages sent to this queue |
| 12 | + * |
| 13 | + * Required for FIFO queues, leave empty for regular queues. |
| 14 | + * |
| 15 | + * @default - no message group ID (regular queue) |
| 16 | + */ |
| 17 | + readonly messageGroupId?: string; |
| 18 | + |
| 19 | + /** |
| 20 | + * The message to send to the queue. |
| 21 | + * |
| 22 | + * Must be a valid JSON text passed to the target queue. |
| 23 | + * |
| 24 | + * @default the entire CloudWatch event |
| 25 | + */ |
| 26 | + readonly message?: events.RuleTargetInput; |
| 27 | + |
| 28 | +} |
| 29 | + |
| 30 | +/** |
| 31 | + * Use an SQS Queue as a target for AWS CloudWatch event rules. |
| 32 | + * |
| 33 | + * @example |
| 34 | + * |
| 35 | + * // publish to an SQS queue every time code is committed |
| 36 | + * // to a CodeCommit repository |
| 37 | + * repository.onCommit(new targets.SqsQueue(queue)); |
| 38 | + * |
| 39 | + */ |
| 40 | +export class SqsQueue implements events.IRuleTarget { |
| 41 | + |
| 42 | + constructor(public readonly queue: sqs.IQueue, private readonly props: SqsQueueProps = {}) { |
| 43 | + } |
| 44 | + |
| 45 | + /** |
| 46 | + * Returns a RuleTarget that can be used to trigger this SQS queue as a |
| 47 | + * result from a CloudWatch event. |
| 48 | + * |
| 49 | + * @see https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/resource-based-policies-cwe.html#sqs-permissions |
| 50 | + */ |
| 51 | + public bind(rule: events.IRule): events.RuleTargetProperties { |
| 52 | + // deduplicated automatically |
| 53 | + this.queue.grantSendMessages(new iam.ServicePrincipal('events.amazonaws.com', |
| 54 | + { |
| 55 | + conditions: { |
| 56 | + ArnEquals: { "aws:SourceArn": rule.ruleArn } |
| 57 | + } |
| 58 | + }) |
| 59 | + ); |
| 60 | + |
| 61 | + const result = { |
| 62 | + id: this.queue.node.id, |
| 63 | + arn: this.queue.queueArn, |
| 64 | + input: this.props.message, |
| 65 | + }; |
| 66 | + if (!!this.props.messageGroupId) { |
| 67 | + Object.assign(result, { sqsParameters: { messageGroupId: this.props.messageGroupId } }); |
| 68 | + } |
| 69 | + return result; |
| 70 | + |
| 71 | + } |
| 72 | + |
| 73 | +} |
0 commit comments