AWS::Events::Rule - AWS CloudFormation (original) (raw)

Creates or updates the specified rule. Rules are enabled by default, or based on value of the state. You can disable a rule using DisableRule.

A single rule watches for events from a single event bus. Events generated by AWS services go to your account's default event bus. Events generated by SaaS partner services or applications go to the matching partner event bus. If you have custom applications or services, you can specify whether their events go to your default event bus or a custom event bus that you have created. For more information, see CreateEventBus.

If you are updating an existing rule, the rule is replaced with what you specify in thisPutRule command. If you omit arguments in PutRule, the old values for those arguments are not kept. Instead, they are replaced with null values.

When you create or update a rule, incoming events might not immediately start matching to new or updated rules. Allow a short period of time for changes to take effect.

A rule must contain at least an EventPattern or ScheduleExpression. Rules with EventPatterns are triggered when a matching event is observed. Rules with ScheduleExpressions self-trigger based on the given schedule. A rule can have both an EventPattern and a ScheduleExpression, in which case the rule triggers on matching events as well as on a schedule.

Most services in AWS treat : or / as the same character in Amazon Resource Names (ARNs). However, EventBridge uses an exact match in event patterns and rules. Be sure to use the correct ARN characters when creating event patterns so that they match the ARN syntax in the event you want to match.

In EventBridge, it is possible to create rules that lead to infinite loops, where a rule is fired repeatedly. For example, a rule might detect that ACLs have changed on an S3 bucket, and trigger software to change them to the desired state. If the rule is not written carefully, the subsequent change to the ACLs fires the rule again, creating an infinite loop.

To prevent this, write the rules so that the triggered actions do not re-fire the same rule. For example, your rule could fire only if ACLs are found to be in a bad state, instead of after any change.

An infinite loop can quickly cause higher than expected charges. We recommend that you use budgeting, which alerts you when charges exceed your specified limit. For more information, see Managing Your Costs with Budgets.

Syntax

To declare this entity in your AWS CloudFormation template, use the following syntax:

JSON

{
  "Type" : "AWS::Events::Rule",
  "Properties" : {
      "Description" : String,
      "EventBusName" : String,
      "EventPattern" : Json,
      "Name" : String,
      "RoleArn" : String,
      "ScheduleExpression" : String,
      "State" : String,
      "Targets" : [ Target, ... ]
    }
}

YAML

Type: AWS::Events::Rule
Properties:
  Description: String
  EventBusName: String
  EventPattern: Json
  Name: String
  RoleArn: String
  ScheduleExpression: String
  State: String
  Targets: 
    - Target

Properties

Description

The description of the rule.

Required: No

Type: String

Maximum: 512

Update requires: No interruption

EventBusName

The name or ARN of the event bus associated with the rule. If you omit this, the default event bus is used.

Required: No

Type: String

Pattern: [/\.\-_A-Za-z0-9]+

Minimum: 1

Maximum: 256

Update requires: Some interruptions

EventPattern

The event pattern of the rule. For more information, see Events and Event Patterns in the _Amazon EventBridge User Guide .

Required: Conditional

Type: Json

Maximum: 4096

Update requires: No interruption

Name

The name of the rule.

Required: No

Type: String

Pattern: [\.\-_A-Za-z0-9]+

Minimum: 1

Maximum: 64

Update requires: Replacement

RoleArn

The Amazon Resource Name (ARN) of the role that is used for target invocation.

If you're setting an event bus in another account as the target and that account granted permission to your account through an organization instead of directly by the account ID, you must specify a RoleArn with proper permissions in the Target structure, instead of here in this parameter.

Required: No

Type: String

Minimum: 1

Maximum: 1600

Update requires: No interruption

ScheduleExpression

The scheduling expression. For example, "cron(0 20 * * ? *)", "rate(5 minutes)". For more information, see Creating an Amazon EventBridge rule that runs on a schedule.

Required: Conditional

Type: String

Maximum: 256

Update requires: No interruption

State

The state of the rule.

Valid values include:

Required: No

Type: String

Allowed values: DISABLED | ENABLED | ENABLED_WITH_ALL_CLOUDTRAIL_MANAGEMENT_EVENTS

Update requires: No interruption

Targets

Adds the specified targets to the specified rule, or updates the targets if they are already associated with the rule.

Targets are the resources that are invoked when a rule is triggered.

The maximum number of entries per request is 10.

Note

Each rule can have up to five (5) targets associated with it at one time.

For a list of services you can configure as targets for events, see EventBridge targets in the _Amazon EventBridge User Guide .

Creating rules with built-in targets is supported only in the AWS Management Console. The built-in targets are:

For some target types, PutTargets provides target-specific parameters. If the target is a Kinesis data stream, you can optionally specify which shard the event goes to by using the KinesisParameters argument. To invoke a command on multiple EC2 instances with one rule, you can use the RunCommandParameters field.

To be able to make API calls against the resources that you own, Amazon EventBridge needs the appropriate permissions:

For more information, see Authentication and Access Control in the _Amazon EventBridge User Guide .

If another AWS account is in the same region and has granted you permission (using PutPermission), you can send events to that account. Set that account's event bus as a target of the rules in your account. To send the matched events to the other account, specify that account's event bus as the Arn value when you runPutTargets. If your account sends events to another account, your account is charged for each sent event. Each event sent to another account is charged as a custom event. The account receiving the event is not charged. For more information, see Amazon EventBridge Pricing.

Note

Input, InputPath, and InputTransformer are not available with PutTarget if the target is an event bus of a different AWS account.

If you are setting the event bus of another account as the target, and that account granted permission to your account through an organization instead of directly by the account ID, then you must specify a RoleArn with proper permissions in theTarget structure. For more information, see Sending and Receiving Events Between AWS Accounts in the Amazon EventBridge User Guide.

Note

If you have an IAM role on a cross-account event bus target, a PutTargets call without a role on the same target (same Id and Arn) will not remove the role.

For more information about enabling cross-account events, see PutPermission.

Input, InputPath, andInputTransformer are mutually exclusive and optional parameters of a target. When a rule is triggered due to a matched event:

When you specify InputPath or InputTransformer, you must use JSON dot notation, not bracket notation.

When you add targets to a rule and the associated rule triggers soon after, new or updated targets might not be immediately invoked. Allow a short period of time for changes to take effect.

This action can partially fail if too many requests are made at the same time. If that happens, FailedEntryCount is non-zero in the response and each entry inFailedEntries provides the ID of the failed target and the error code.

Required: No

Type: Array of Target

Update requires: No interruption

Return values

Ref

When you pass the logical ID of this resource to the intrinsic Ref function, Ref returns event rule ID, such asmystack-ScheduledRule-ABCDEFGHIJK.

For more information about using the Ref function, see Ref.

Fn::GetAtt

Arn

The ARN of the rule, such asarn:aws:events:us-east-2:123456789012:rule/example.

Examples

Create a cross-Region rule

The following example demonstrates how to create a rule that routes events across Regions.

JSON

{
   "Resources": {
      "EventRuleRegion1": {
         "Type": "AWS::Events::Rule",
         "Properties": {
            "Description": "Routes to us-east-1 event bus",
            "EventBusName": "MyBusName",
            "State": "ENABLED",
            "EventPattern": {
               "source": [
                   "MyTestApp"
               ],
               "detail": [
                   "MyTestAppDetail"
               ]
            },
            "Targets": [
               {
                   "Arn": "arn:aws:events:us-east-1:123456789012:event-bus/CrossRegionDestinationBus",
                   "Id": " CrossRegionDestinationBus",
                   "RoleArn": {
                      "Fn::GetAtt": [
                         "EventBridgeIAMrole",
                         "Arn"
                      ]
                   }
               }
           ]
      }
   },
   "EventBridgeIAMrole": {
      "Type": "AWS::IAM::Role",
      "Properties": {
         "AssumeRolePolicyDocument": {
            "Version": "2012-10-17",
            "Statement": [
               {
                  "Effect": "Allow",
                  "Principal": {
                     "Service": {
                        "Fn::Sub": "events.amazonaws.com"
                     }
                  },
                  "Action": "sts:AssumeRole"
               }
            ]
      },
      "Path": "/",
      "Policies": [
         {
            "PolicyName": "PutEventsDestinationBus",
            "PolicyDocument": {
               "Version": "2012-10-17",
               "Statement": [
                  {
                     "Effect": "Allow",
                     "Action": [
                        "events:PutEvents"
                     ],
                     "Resource": [
                        "arn:aws:events:us-east-1:123456789012:event-bus/CrossRegionDestinationBus"
                     ]
                  }
               ]
            }
         }
      ]
   }
}

YAML

Resources:
  EventRuleRegion1:
    Type: 'AWS::Events::Rule'
    Properties:
      Description: Routes to us-east-1 event bus
      EventBusName: MyBusName
      State: ENABLED
      EventPattern:
        source:
          - MyTestApp
        detail:
          - MyTestAppDetail
      Targets:
        - Arn: >-
            arn:aws:events:us-east-1:123456789012:event-bus/CrossRegionDestinationBus
          Id: ' CrossRegionDestinationBus'
          RoleArn: !GetAtt 
            - EventBridgeIAMrole
            - Arn
  EventBridgeIAMrole:
    Type: 'AWS::IAM::Role'
    Properties:
      AssumeRolePolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Principal:
              Service: !Sub events.amazonaws.com
            Action: 'sts:AssumeRole'
      Path: /
      Policies:
        - PolicyName: PutEventsDestinationBus
          PolicyDocument:
            Version: 2012-10-17
            Statement:
              - Effect: Allow
                Action:
                  - 'events:PutEvents'
                Resource:
                  - >-
                    arn:aws:events:us-east-1:123456789012:event-bus/CrossRegionDestinationBus

Create a rule that includes a dead-letter queue for a target

The following example demonstrates how to send all EC2 events to an SQS queue, and include a dead-letter queue and retry policy settings for the target of the rule.

JSON

{
   "MyNewEventsRule": {
      "Type": "AWS::Events::Rule",
      "Properties": {
         "Description": "Test Events Rule",
         "Name": "mynewabc",
         "EventPattern": {
            "source": [
               "aws.ec2"
            ]
         },
         "State": "ENABLED",
         "Targets": [
            {
               "Arn": "arn:aws:sqs:us-west-2:081035103721:demoSQS",
               "Id": "Id1234",
               "RetryPolicy": {
                  "MaximumRetryAttempts": 4,
                  "MaximumEventAgeInSeconds": 400
               },
               "DeadLetterConfig": {
                  "Arn": "arn:aws:sqs:us-west-2:081035103721:demoDLQ"
               }
            }
         ]
      }
   }
}

YAML

MyNewEventsRule:
  Type: 'AWS::Events::Rule'
  Properties:
    Description: Test Events Rule
    Name: mynewabc
    EventPattern:
      source:
        - aws.ec2
    State: ENABLED
    Targets:
      - Arn: 'arn:aws:sqs:us-west-2:081035103721:demoSQS'
        Id: Id1234
        RetryPolicy:
          MaximumRetryAttempts: 4
          MaximumEventAgeInSeconds: 400
        DeadLetterConfig:
          Arn: 'arn:aws:sqs:us-west-2:081035103721:demoDLQ'

Regularly invoke Lambda function

The following example creates a rule that invokes the specified Lambda function every 10 minutes. The PermissionForEventsToInvokeLambda resource grants EventBridge permission to invoke the associated function.

JSON

"ScheduledRule": {
  "Type": "AWS::Events::Rule",
  "Properties": {
    "Description": "ScheduledRule",
    "ScheduleExpression": "rate(10 minutes)",
    "State": "ENABLED",
    "Targets": [{
      "Arn": { "Fn::GetAtt": ["LambdaFunction", "Arn"] },
      "Id": "TargetFunctionV1"
    }]
  }
},
"PermissionForEventsToInvokeLambda": {
  "Type": "AWS::Lambda::Permission",
  "Properties": {
    "FunctionName": { "Ref": "LambdaFunction" },
    "Action": "lambda:InvokeFunction",
    "Principal": "events.amazonaws.com",
    "SourceArn": { "Fn::GetAtt": ["ScheduledRule", "Arn"] }
  }
}

YAML

ScheduledRule: 
  Type: AWS::Events::Rule
  Properties: 
    Description: "ScheduledRule"
    ScheduleExpression: "rate(10 minutes)"
    State: "ENABLED"
    Targets: 
      - 
        Arn: 
          Fn::GetAtt: 
            - "LambdaFunction"
            - "Arn"
        Id: "TargetFunctionV1"
PermissionForEventsToInvokeLambda: 
  Type: AWS::Lambda::Permission
  Properties: 
    FunctionName: !Ref "LambdaFunction"
    Action: "lambda:InvokeFunction"
    Principal: "events.amazonaws.com"
    SourceArn: 
      Fn::GetAtt: 
        - "ScheduledRule"
        - "Arn"

Invoke Lambda Function in Response to an Event

The following example creates a rule that invokes the specified Lambda function when any EC2 instance's state changes to stopping.

JSON

"EventRule": {
  "Type": "AWS::Events::Rule",
  "Properties": {
    "Description": "EventRule",
    "EventPattern": {
      "source": [
        "aws.ec2"
      ],
      "detail-type": [
        "EC2 Instance State-change Notification"
      ],
      "detail": {
        "state": [
          "stopping"
        ]
      }
    },
    "State": "ENABLED",
    "Targets": [{
      "Arn": { "Fn::GetAtt": ["LambdaFunction", "Arn"] },
      "Id": "TargetFunctionV1"
    }]
  }
},
"PermissionForEventsToInvokeLambda": {
  "Type": "AWS::Lambda::Permission",
  "Properties": {
    "FunctionName": { "Ref": "LambdaFunction" },
    "Action": "lambda:InvokeFunction",
    "Principal": "events.amazonaws.com",
    "SourceArn": { "Fn::GetAtt": ["EventRule", "Arn"] }
  }
}

YAML

EventRule: 
  Type: AWS::Events::Rule
  Properties: 
    Description: "EventRule"
    EventPattern: 
      source: 
        - "aws.ec2"
      detail-type: 
        - "EC2 Instance State-change Notification"
      detail: 
        state: 
          - "stopping"
    State: "ENABLED"
    Targets: 
      - 
        Arn: 
          Fn::GetAtt: 
            - "LambdaFunction"
            - "Arn"
        Id: "TargetFunctionV1"
PermissionForEventsToInvokeLambda: 
  Type: AWS::Lambda::Permission
  Properties: 
    FunctionName: 
      Ref: "LambdaFunction"
    Action: "lambda:InvokeFunction"
    Principal: "events.amazonaws.com"
    SourceArn: 
      Fn::GetAtt: 
        - "EventRule"
        - "Arn"

Notify a Topic in Response to a Log Entry

The following example creates a rule that notifies an Amazon Simple Notification Service topic if an AWS CloudTrail log entry contains a call by the root user. TheEventTopicPolicy resource grants Amazon EventBridge permission to notify the associated Amazon SNS topic.

JSON

"OpsEventRule": {
  "Type": "AWS::Events::Rule",
  "Properties": {
    "Description": "EventRule",
    "EventPattern": {
      "detail-type": [ "AWS API Call via CloudTrail" ],
      "detail": { 
        "userIdentity": { 
          "type": [ "Root" ]
        }
      }
    },
    "State": "ENABLED",
    "Targets": [
      {
        "Arn": { "Ref": "MySNSTopic" },
        "Id": "OpsTopic"
      }
    ]
  }
}
"EventTopicPolicy": {
  "Type": "AWS::SNS::TopicPolicy",
  "Properties": {
    "PolicyDocument": {
      "Statement": [
        {
          "Effect": "Allow",
          "Principal": { "Service": "events.amazonaws.com" },
          "Action": "sns:Publish",
          "Resource": "*"
        }
      ]
    },
    "Topics": [ { "Ref": "MySNSTopic" } ]
  }
}

YAML

OpsEventRule: 
  Type: AWS::Events::Rule
  Properties: 
    Description: "EventRule"
    EventPattern: 
      detail-type: 
        - "AWS API Call via CloudTrail"
      detail: 
        userIdentity: 
          type: 
            - "Root"
    State: "ENABLED"
    Targets: 
      - 
        Arn: 
          Ref: "MySNSTopic"
        Id: "OpsTopic"
EventTopicPolicy:
  Type: 'AWS::SNS::TopicPolicy'
  Properties:
    PolicyDocument:
      Statement:
        - Effect: Allow
          Principal:
            Service: events.amazonaws.com
          Action: 'sns:Publish'
          Resource: '*'
    Topics:
      - !Ref MySNSTopic