{Organizations}チュートリアル: CloudWatch Events を使用して、組織の重要な変更をモニタリングする

https://docs.aws.amazon.com/ja_jp/organizations/latest/userguide/orgs_tutorials_cwe.html

現在、AWS Organizations は、米国東部 (バージニア北部) リージョン でホストされています。
このチュートリアルのステップを実行するには、米国東部 (バージニア北部) リージョンを使用するよう AWS Management Console を設定する必要があります。


CloudTrail証跡 -> CloudWatch Events -> Lambda and SNS

-- 1. コマンド等のインストール

-- 1.1 aws cli version 2 インストール

curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
unzip awscliv2.zip
sudo ./aws/install
aws --version

-- 1.2 jqインストール
sudo yum -y install jq


ステップ 1: 証跡およびイベントセレクターの設定

 


-- 2. S3 バケットを作成する

export AWS_DEFAULT_REGION=us-east-1

aws s3 mb s3://bucket123

aws s3 ls


-- 3. バケットポリシーの追加

vim s3_policy.json

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "AWSCloudTrailAclCheck20150319",
            "Effect": "Allow",
            "Principal": {
                "Service": [
                    "cloudtrail.amazonaws.com"
                ]
            },
            "Action": "s3:GetBucketAcl",
            "Resource": "arn:aws:s3:::bucket123"
        },
        {
            "Sid": "AWSCloudTrailWrite20150319",
            "Effect": "Allow",
            "Principal": {
                "Service": [
                    "cloudtrail.amazonaws.com"
                ]
            },
            "Action": "s3:PutObject",
            "Resource": "arn:aws:s3:::bucket123/AWSLogs/999999999999/*",
            "Condition": {
                "StringEquals": {
                    "s3:x-amz-acl": "bucket-owner-full-control",
                    "aws:SourceArn": "arn:aws:cloudtrail:us-east-1:999999999999:trail/trail01"
                }
            }
        },
        {
            "Sid": "AWSCloudTrailWrite20150319",
            "Effect": "Allow",
            "Principal": {
                "Service": [
                    "cloudtrail.amazonaws.com"
                ]
            },
            "Action": "s3:PutObject",
            "Resource": "arn:aws:s3:::bucket123/AWSLogs/o-1111111111/*",
            "Condition": {
                "StringEquals": {
                    "s3:x-amz-acl": "bucket-owner-full-control",
                    "aws:SourceArn": "arn:aws:cloudtrail:us-east-1:999999999999:trail/trail01"
                }
            }
        }
    ]
}


aws s3api put-bucket-policy \
--bucket bucket123 \
--policy file://s3_policy.json

aws s3api get-bucket-policy \
--bucket bucket123

-- 4. AWS Organizations で信頼済みサービスとして CloudTrail を有効にする

aws organizations enable-all-features

aws organizations list-aws-service-access-for-organization

aws organizations \
enable-aws-service-access \
--service-principal cloudtrail.amazonaws.com

 

-- 5. 証跡の作成

aws cloudtrail create-trail  \
--name trail01  \
--s3-bucket-name bucket123  \
--include-global-service-events  \
--is-multi-region-trail  \
--enable-log-file-validation  \
--is-organization-trail


aws cloudtrail list-trails
aws cloudtrail describe-trails
aws cloudtrail get-trail \
--name trail01


aws cloudtrail get-event-selectors \
--trail-name trail01

 


-- 6. ログ記録の開始
aws cloudtrail get-trail-status \
--name trail01

aws cloudtrail start-logging \
--name trail01


ステップ 2: Lambda 関数を設定する

-- 7. IAMロール作成
vim role01.json

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Service": "lambda.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}

aws iam create-role \
--role-name role01 \
--assume-role-policy-document file://role01.json


-- 8. ポリシーをロールにアタッチ
aws iam attach-role-policy \
--policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole \
--role-name role01

-- 9. Lambda関数作成

vim test.js

console.log('Loading function');

exports.handler = async (event, context) => {
    console.log('LogOrganizationsEvents');
    console.log('Received event:', JSON.stringify(event, null, 2));
    return event.key1;  // Echo back the first key value
    // throw new Error('Something went wrong');
};


chmod 755 test.js
zip test.zip test.js

aws lambda create-function \
--function-name func01 \
--zip-file fileb://test.zip \
--handler test.handler  \
--runtime nodejs14.x  \
--role arn:aws:iam::999999999999:role/role01


aws lambda list-functions | grep func01

aws lambda get-function --function-name func01

 

ステップ 3: 受信者に E メールを送信する Amazon SNS トピックを作成する

-- 10. SNSトピック作成

aws sns list-topics
aws sns list-subscriptions

aws sns create-topic --name topic01

aws sns subscribe \
--topic-arn arn:aws:sns:us-east-1:999999999999:topic01 \
--protocol email \
--notification-endpoint hoge@example.com


-- 11. SNSアクセスポリシー設定


vim sns_policy.json

{
  "Version": "2008-10-17",
  "Id": "__default_policy_ID",
  "Statement": [
    {
      "Sid": "__default_statement_ID",
      "Effect": "Allow",
      "Principal": {
        "AWS": "*"
      },
      "Action": [
        "SNS:GetTopicAttributes",
        "SNS:SetTopicAttributes",
        "SNS:AddPermission",
        "SNS:RemovePermission",
        "SNS:DeleteTopic",
        "SNS:Subscribe",
        "SNS:ListSubscriptionsByTopic",
        "SNS:Publish"
      ],
      "Resource": "arn:aws:sns:us-east-1:999999999999:topic01",
      "Condition": {
        "StringEquals": {
          "AWS:SourceOwner": "999999999999"
        }
      }
    },
    {
      "Sid": "AWSEvents_rule01_Id46feb474-b735-4a15-8157-71fba10e0d7f",
      "Effect": "Allow",
      "Principal": {
        "Service": "events.amazonaws.com"
      },
      "Action": "sns:Publish",
      "Resource": "arn:aws:sns:us-east-1:999999999999:topic01"
    }
  ]
}


aws sns set-topic-attributes \
--topic-arn arn:aws:sns:us-east-1:999999999999:topic01 \
--attribute-name Policy \
--attribute-value file://sns_policy.json

aws sns get-topic-attributes \
--topic-arn arn:aws:sns:us-east-1:999999999999:topic01

 

ステップ 4: CloudWatch Events ルールを作成する


-- 12. ルールの作成

aws events put-rule \
--name rule01 \
--event-pattern '{
  "source": ["aws.organizations"],
  "detail-type": ["AWS API Call via CloudTrail"],
  "detail": {
    "eventSource": ["organizations.amazonaws.com"],
    "eventName": ["CreateAccount", "CreateOrganizationalUnit"]
  }
}' \
--state ENABLED \
--description rule01


aws events list-rules
aws events describe-rule --name rule01

 

-- 13. ターゲットの作成

aws events put-targets \
--rule rule01 \
--targets "Id"="1","Arn"="arn:aws:lambda:us-east-1:999999999999:function:func01"

aws events put-targets \
--rule rule01 \
--targets "Id"="2","Arn"="arn:aws:sns:us-east-1:999999999999:topic01"

aws events list-targets-by-rule \
--rule rule01

-- 14. Lambda関数に権限を追加する

aws lambda add-permission \
--function-name func01 \
--statement-id events \
--action lambda:InvokeFunction \
--principal events.amazonaws.com \
--source-arn arn:aws:events:us-east-1:999999999999:rule/rule01

aws lambda get-policy \
--function-name func01 | jq -r .Policy  | jq .


ステップ 5: CloudWatch Events ルールをテストする

-- 15. 動作確認

OU を作成

aws organizations list-roots

aws organizations list-children \
--parent-id r-xxxx \
--child-type ORGANIZATIONAL_UNIT

aws organizations create-organizational-unit \
--parent-id r-xxxx \
--name ou01

CloudWatch Events ログ確認

Eメール受信確認

 

-- 16. クリーンアップ


-- OUの削除

aws organizations list-children \
--parent-id r-xxxx \
--child-type ORGANIZATIONAL_UNIT

aws organizations delete-organizational-unit \
--organizational-unit-id ou-xxxx-yyyyyyyy

 

 

-- ターゲットの削除
aws events list-targets-by-rule \
--rule rule01

aws events remove-targets \
--rule rule01 \
--ids 1

aws events remove-targets \
--rule rule01 \
--ids 2

-- ルールの削除
aws events list-rules

aws events delete-rule \
--name rule01


-- SNSトピック削除

aws sns unsubscribe --subscription-arn arn:aws:sns:us-east-1:999999999999:topic01:11111111-2222-3333-4444-555555555555
aws sns delete-topic --topic-arn arn:aws:sns:us-east-1:999999999999:topic01


aws sns list-topics
aws sns list-subscriptions

 

-- Lambda関数の削除
aws lambda get-function --function-name func01
aws lambda delete-function --function-name func01


-- ロールの削除
aws iam list-roles | grep role01

aws iam detach-role-policy \
--role-name role01 \
--policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole

aws iam delete-role --role-name role01

 

-- 証跡の削除
aws cloudtrail describe-trails

aws cloudtrail delete-trail \
--name trail01

 

-- バケットの削除

aws s3 ls
aws s3 rb s3://bucket123  --force