LoginSignup
3
4

More than 5 years have passed since last update.

CloudWatch Eventsの特定のルールを有効化/無効化できるポリシーを書いてみた

Last updated at Posted at 2016-04-04

書いてみた背景

  • EC2インスタンスの自動起動/自動終了をCloudWatch EventsとLambdaで運用していた。
  • 特定の部署で管理するEC2インスタンスの自動起動/自動終了をその部署で制御したいという要望があった。

実際書いた結果

以下のような感じで、ルールのARNをリソースに指定することで権限の付与が可能です。

ポリシー例
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "events:DescribeRule",
                "events:ListRuleNamesByTarget",
                "events:ListRules",
                "events:ListTargetsByRule",
                "events:TestEventPattern"
            ],
            "Resource": [
                "*"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "events:DisableRule",
                "events:EnableRule"
            ],
            "Resource": [
                "arn:aws:events:ap-northeast-1:************:rule/********"
            ]
        }
    ]
}

一括してRuleを指定できるように、RuleにTagをつけることができたらいいんですけどね。
(ルール名に特定の接頭辞を設定+ワイルドカードでもいいんですが、命名規則決めて運用でカバーになっちゃうしなー・・・)

補足

自動起動の方法について

自動終了はBuilt-in Targetを利用すればいいんですが、自動起動は用意されていなかったので
とりあえず、以下のようなLambda FunctionをInvokeしています。
インスタンスの指定は、Configure input >> Constant (JSON text)でインスタンスIDを直接指定しています。
(もっと汎用的なの書きたいなー、今のところ使うあてはないけど。)

import boto3

def lambda_handler(event, context):
    client = boto3.client('ec2')
    id = event['instance-id']
    response = client.start_instances(
        InstanceIds=[
            id,
        ]
    )
    print response
3
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4