概要
この記事では、Eventbridge を使用してKinesis ストリームにインスタンス状態変更通知イベントを送信してみました。ここでは、AmazonEC2インスタンスが開始または停止したときにKinesis ストリームにイベントを送信するEventBridgeルールを作成しました。
作成するリソース:
- Kinesis Stream
- IAM Role
- EventBridge rule
- EC2 Instance
やってみた
Kinesis ストリームの作成
- 次のコマンドを使用してData Streamを作成しておきます。
//Create a Kinesis Stream
aws kinesis create-stream --stream-name demo-stream --shard-count 1 --region us-east-1
- [describe-stream]コマンドを実行して、ストリームの詳細を取得します。
////Describe the Data Stream
aws kinesis describe-stream --stream-name demo-stream --region us-east-1
//Output
{
"StreamDescription": {
"Shards": [
{
"ShardId": "shardId-000000000000",
"HashKeyRange": {
"StartingHashKey": "0",
"EndingHashKey": "............."
},
"SequenceNumberRange": {
"StartingSequenceNumber": "..............."
}
}
],
"StreamARN": "arn:aws:kinesis:us-east-1:xxxxxxxxxxxx:stream/demo-stream",
"StreamName": "demo-stream",
"StreamStatus": "ACTIVE",
"RetentionPeriodHours": 24,
"EnhancedMonitoring": [
{
"ShardLevelMetrics": []
}
],
"EncryptionType": "NONE",
"KeyId": null,
"StreamCreationTimestamp": "2022-07-26T12:18:33+09:00"
}
}
IAMロールの作成
- EventBridgeがイベントをKinesisStreamに送信できるようにするIAMロールを作成しておきます。
- 以下のポリシーを含むjson [policy.json] ファイルを作成しておきます。
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"kinesis:PutRecord",
"kinesis:PutRecords"
],
"Resource": [
"arn:aws:kinesis:us-east-1:xxxxxxxxxxxx:stream/demo-stream"
]
}
]
}
- 次のコマンドを使用して、上記のjsonファイルでIAMポリシーを作成しておきます。
//Create an IAM Policy
aws iam create-policy --policy-name EventBridge-Invoke-Kinesis --policy-document file://policy.json
//Output
{
"Policy": {
"PolicyName": "EventBridge-Invoke-Kinesis",
"PolicyId": ".............",
"Arn": "arn:aws:iam::xxxxxxxxxx:policy/EventBridge-Invoke-Kinesis",
"Path": "/",
"DefaultVersionId": "v1",
"AttachmentCount": 0,
"PermissionsBoundaryUsageCount": 0,
"IsAttachable": true,
"CreateDate": "2022-07-26T03:27:56+00:00",
"UpdateDate": "2022-07-26T03:27:56+00:00"
}
}
- 次のassumeRoleポリシーを含むjsonファイルを作成しておきます。
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": "events.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
}
- 上記のポリシーでIAMロールを作成しておきます。
//Create an IAM role
aws iam create-role --role-name "EventBridge-Kinesis-role" --assume-role-policy-document file://assumeRole.json
//Output
{
"Role": {
"Path": "/",
"RoleName": "EventBridge-Kinesis-role",
"RoleId": "............",
"Arn": "arn:aws:iam::xxxxxxxxxx:role/EventBridge-Kinesis-role",
"CreateDate": "2022-07-26T03:28:52+00:00",
"AssumeRolePolicyDocument": {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": "events.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
}
}
}
- 上記で作成したIAMポリシーをIAMロールにアタッチしておきます。
aws iam attach-role-policy \
--role-name EventBridge-Kinesis-role \
--policy-arn 'arn:aws:iam::xxxxxxxxxxx:policy/EventBridge-Invoke-Kinesis'
EventBridge ルールの作成
- EventBridge コンソールのナビゲーションペインで [Rules] を選択しておきます。
- [Create rule]をクリックしておきます。
- ルール名を入力し、[Rule with an event pattern]としてルールタイプを選択しておきます。
- イベントソースとして[AWS events or EventBridge partner events]を選択しておきます。
- 次の設定でイベントパターンを定義しておきます。
- Event source : AWS services
- AWS service : EC2
- Event type : EC2 Instance State-change Notification
- Specific state(s) : running, stopped
- [Any Instance]を選択しておきます。
- ターゲットの詳細を入力しておきます。
- Target types: AWS service
- Target : Kinesis stream
- Stream: 以前に作成したKinesisストリームを選択しておきます。
- Execution role: 前の手順で作成したIAMロールを選択しておきます。
- 上記の設定で、EventBridgeルールを作成しておきます。
テストする
- この設定で EC2インスタンスを作成しておきます。
- AMI : Amazon Linux 2 AMI
- インスタンスタイプ : t2.micro
- サブネット:パブリックサブネット
- インスタンスを停止して開始すると、イベントがKinesisストリームに送信されます。AWS CLI を使用してストリームからレコードを取得し、イベントが送信されたことを確認できます。
- 次のコマンドを実行して、シャードイテレータを取得しておきます。
//Command to get Kinesis shard iterator.
aws kinesis get-shard-iterator --shard-id shardId-000000000 --shard-iterator-type TRIM_HORIZON --stream-name demo-stream --region us-east-1
//Output
{
"ShardIterator": "AAAAAAAAAAEGY........................=="
}
- 次のコマンドでシャードイテレータを使用して、イベントレコードを取得しておきます。Kinesis のレコードは Base64 でエンコードされています。
//Get Records.
aws kinesis get-records --shard-iterator AAAAAAAAAAEGY........................== --region us-east-1
//Output
{
"Records": [
{
"SequenceNumber": ".........",
"ApproximateArrivalTimestamp": "2022-07-26T13:45:24.848000+09:00",
"Data": "eyJ8ZXJz.........",
"PartitionKey": "............."
},
{
"SequenceNumber": "...........",
"ApproximateArrivalTimestamp": "2022-07-26T13:57:22.386000+09:00",
"Data": "eyJ3ZXJza.............",
"PartitionKey": "................"
}
],
"NextShardIterator": "AAAAAAAA..............==",
"MillisBehindLatest": 0
}
- データをデコードして、ストリームに送信されたイベントを確認できます。イベントはJSON形式でストリームに送信されます。
- 以下のデコードされたデータから、[running, stopped]イベントがストリームに送信されていることを確認できます。
//Record 1
{
"version":"0",
"id":"........",
"detail-type":"EC2 Instance State-change Notification",
"source":"aws.ec2",
"account":"xxxxxxxxxxx",
"time":"2022-07-26T04:45:24Z",
"region":"us-east-1",
"resources":["arn:aws:ec2:us-east-1:xxxxxxxxxx:instance/i-000000000000"],
"detail":{"instance-id":"i-00000000000","state":"running"}
}
//Record 2
{
"version":"0",
"id":"..........",
"detail-type":"EC2 Instance State-change Notification",
"source":"aws.ec2",
"account":"xxxxxxxxxxx",
"time":"2022-07-26T04:57:21Z",
"region":"us-east-1",
"resources":["arn:aws:ec2:us-east-1:xxxxxxxxxx:instance/i-0000000000000"],
"detail":{"instance-id":"i-00000000000","state":"stopped"}
}
まとめ
Eventbridge を使用してKinesis ストリームにインスタンス状態変更通知イベントを送信してみました。Eventbridge を使用して、他のEC2状態変更通知イベントをKinesisまたは他のAWSサービスに送信することもできます。
Reference:
Sending EC2 state change events to an Amazon Kinesis stream using EventBridge