<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>監視 &#8211; エンジニア見習い</title>
	<atom:link href="https://otonan-syusyoku.work/archives/tag/%e7%9b%a3%e8%a6%96/feed" rel="self" type="application/rss+xml" />
	<link>https://otonan-syusyoku.work</link>
	<description>三流プログラマー</description>
	<lastBuildDate>Wed, 19 Nov 2025 05:42:32 +0000</lastBuildDate>
	<language>ja</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>

<image>
	<url>https://otonan-syusyoku.work/wp-content/uploads/2023/10/cropped-名称未設定のデザイン-16-32x32.png</url>
	<title>監視 &#8211; エンジニア見習い</title>
	<link>https://otonan-syusyoku.work</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>【CDKで構築】AWS ECS/RDSの監視・オートスケール基盤を自動構築しSlack通知する方法</title>
		<link>https://otonan-syusyoku.work/archives/2168</link>
					<comments>https://otonan-syusyoku.work/archives/2168#respond</comments>
		
		<dc:creator><![CDATA[hrokig2]]></dc:creator>
		<pubDate>Wed, 19 Nov 2025 04:44:12 +0000</pubDate>
				<category><![CDATA[インフラ]]></category>
		<category><![CDATA[業務]]></category>
		<category><![CDATA[AWS]]></category>
		<category><![CDATA[ECS]]></category>
		<category><![CDATA[RDS]]></category>
		<category><![CDATA[監視]]></category>
		<guid isPermaLink="false">https://otonan-syusyoku.work/?p=2168</guid>

					<description><![CDATA[ECS FargateとRDSでPHPアプリケーションを運用する際、リソースの異常検知や負荷に応じたスケール管理は必須です。 しかし、これらの仕組みを個別に手動で設定するのは手間がかかります。 本記事では、AWS CDK [&#8230;]]]></description>
										<content:encoded><![CDATA[<p><span class="">ECS FargateとRDSでPHPアプリケーションを運用する際、</span><span class="">リソースの異常検知や負荷に応じたスケール管理は必須です。<br />
</span><span class="">しかし、</span><span class="">これらの仕組みを個別に手動で設定するのは手間がかかります。</span></p>
<p><span class="">本記事では、</span><b class="">AWS CDK</b><span class="">（Cloud Development Kit）を用いて、</span><span class="">ECSとRDSの</span><b class="">監視アラーム</b><span class="">、</span><span class="">ECSの</span><b class="">オートスケーリング</b><span class="">、</span><span class="">そしてそのイベントを</span><b class="">Slack</b><span class="">に集約する通知基盤を<strong>IaC</strong>として一括で構築する方法を解説します。</span></p>
<p>&nbsp;</p>
<h2>監視・通知アーキテクチャの全体像</h2>
<p>採用するアーキテクチャは以下の通りです。</p>
<div class="table-block-component"></div>
<div>
<table style="border-collapse: collapse; width: 100%;">
<tbody>
<tr style="background-color: #5aabe8;">
<td style="width: 33.3333%;"><span style="color: #ffffff;">機能</span></td>
<td style="width: 33.3333%;"><span style="color: #ffffff;">AWSサービス</span></td>
<td style="width: 33.3333%;"><span style="color: #ffffff;">役割</span></td>
</tr>
<tr>
<td style="width: 33.3333%;"><b>監視</b></td>
<td style="width: 33.3333%;">CloudWatch</td>
<td style="width: 33.3333%;">メトリクスを収集・アラーム発報</td>
</tr>
<tr>
<td style="width: 33.3333%;"><b>自動応答</b></td>
<td style="width: 33.3333%;">Application Auto Scaling</td>
<td style="width: 33.3333%;">ECSの負荷に応じてタスク数を自動調整</td>
</tr>
<tr>
<td style="width: 33.3333%;"><b>通知ルーティング</b></td>
<td style="width: 33.3333%;">Amazon SNS</td>
<td style="width: 33.3333%;">アラームやスケーリングイベントを中継</td>
</tr>
<tr>
<td style="width: 33.3333%;"><b>通知先</b></td>
<td style="width: 33.3333%;">AWS Chatbot <span class="math-inline" data-math="\rightarrow">$\rightarrow$</span> Slack</td>
<td style="width: 33.3333%;">SNSからの通知を整形しSlackへ送信</td>
</tr>
</tbody>
</table>
</div>
<div></div>
<h2>事前準備: AWS ChatbotとSlackの連携</h2>
<p>CDKデプロイの前に、AWSアカウントとSlackを連携させるための<b>AWS Chatbotクライアント</b>を作成しておく必要があります。</p>
<ol start="1">
<li>AWS Chatbotコンソールで、<b>Slackワークスペース</b>と<b>チャンネル</b>を連携させます。</li>
<li>この設定により、通知先の<b>SlackチャンネルID</b>と<b>ワークスペースID</b>が取得できます。これらはCDKコード内で使用します。</li>
</ol>
<div class="sc_toggle_box">
<div class="sc_toggle_title">CDKでAWS Chatbot連携が完結しない理由</div>
<div class="sc_toggle_content">
<h3>1. 外部サービスとの認証（OAuthプロセス）が必要</h3>
<p>AWS Chatbotは、AWSアカウントと外部サービス（SlackやMicrosoft Teams）の連携を提供します。この連携は、Slack側でAWS Chatbotアプリをインストールし、AWSアカウントへのアクセスを許可するOAuth認証プロセスをユーザー（管理者）がブラウザ上で行う必要があります。</p>
<p>CDKはAWSアカウント内のリソースをプログラマブルにデプロイしますが、Slackワークスペース側の認証フローをプログラムで自動実行することは、セキュリティ上の理由からできません。</p>
<h3>2. AWS Chatbot Clientの事前設定が必要</h3>
<p>CDKのaws-chatbotモジュールで定義できるのは、連携が完了したワークスペースを参照し、その上でチャンネル設定（どのSNSトピックの通知をどのSlackチャンネルに送るか）を行う部分のみです。</p>
<p>CDKでnew chatbot.SlackChannelConfiguration(&#8230;)を作成する前に、通知先のSlackワークスペースID (slackWorkspaceId) を特定する必要があります。このワークスペースIDは、手動でChatbotコンソールからSlackとの連携を完了させた際に初めてAWS側に登録される情報です。</p>
</div>
</div>
<p>&nbsp;</p>
<h2>監視とオートスケール基盤の構築</h2>
<p>今回は、ECSサービスとRDSインスタンスが既に存在することを前提に、その監視・スケール設定を定義するCDKスタックを作成します。</p>
<h3>CDKスタックのセットアップ</h3>
<p>必要なCDKライブラリをインポートし、スタックを定義します。</p>
<p>&nbsp;</p>
<div>
<pre class="line-numbers"><code class="language-js">// lib/monitoring-stack.ts

import * as cdk from 'aws-cdk-lib';
import { Construct } from 'constructs';
import * as sns from 'aws-cdk-lib/aws-sns';
import * as cloudwatch from 'aws-cdk-lib/aws-cloudwatch';
import * as actions from 'aws-cdk-lib/aws-cloudwatch-actions';
import * as events from 'aws-cdk-lib/aws-events';
import * as targets from 'aws-cdk-lib/aws-events-targets';
import * as autoscaling from 'aws-cdk-lib/aws-applicationautoscaling';
import * as ecs from 'aws-cdk-lib/aws-ecs';
import * as chatbot from 'aws-cdk-lib/aws-chatbot';

// 環境依存の定数を定義 (適宜置き換えてください)
const CLUSTER_NAME = 'your-ecs-cluster-name';
const SERVICE_NAME = 'your-ecs-service-name';
const RDS_IDENTIFIER = 'your-rds-instance-identifier';
const SLACK_CHANNEL_ID = 'C01234567'; // 取得したチャンネルID
const SLACK_WORKSPACE_ID = 'T01234567'; // 取得したワークスペースID

export class MonitoringStack extends cdk.Stack {
  constructor(scope: Construct, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    // 既存のECSサービスを参照
    const ecsService = ecs.FargateService.fromFargateServiceAttributes(this, 'ExistingEcsService', {
      serviceArn: cdk.Stack.of(this).formatArn({
        service: 'ecs',
        resource: 'service',
        resourceName: `${CLUSTER_NAME}/${SERVICE_NAME}`,
        sep: '/',
      }),
      cluster: ecs.Cluster.fromClusterAttributes(this, 'ExistingCluster', {
        clusterName: CLUSTER_NAME,
        vpc: ({} as any), // 参照のため空オブジェクト
        securityGroups: [],
      }),
    });
  }
}</code></pre>
<p>&nbsp;</p>
</div>
<h3>通知用SNSトピックとChatbotの設定</h3>
<p>アラームやイベントが通知を送るSNSトピックを作成し、それをAWS Chatbotに連携させます。</p>
<p><response-element class="" ng-version="0.0.0-PLACEHOLDER"><code-block _nghost-ng-c519592647="" class="ng-tns-c519592647-2197 ng-star-inserted"></code-block></response-element></p>
<div _ngcontent-ng-c519592647="" class="code-block ng-tns-c519592647-2197 ng-animate-disabled ng-trigger ng-trigger-codeBlockRevealAnimation" jslog="223238;track:impression,attention;BardVeMetadataKey:[[&quot;r_a2c461939f765a9a&quot;,&quot;c_86e1e1d55e25872e&quot;,null,&quot;rc_330331dc660dc0f2&quot;,null,null,&quot;ja&quot;,null,1,null,null,1,0]]">
<div _ngcontent-ng-c519592647="" class="code-block-decoration header-formatted gds-title-s ng-tns-c519592647-2197 ng-star-inserted"><span _ngcontent-ng-c519592647="" class="ng-tns-c519592647-2197"></span></div>
</div>
<pre class="line-numbers"><code class="language-js">// 1. 通知用SNSトピックの作成
    const alarmTopic = new sns.Topic(this, 'AlarmTopic', {
      displayName: 'System-Monitoring-Notifications',
    });

    // 2. AWS ChatbotとSNSトピックの連携 (Slackへのルーティング)
    new chatbot.SlackChannelConfiguration(this, 'ChatbotConfig', {
      slackChannelConfigurationName: 'EcsRdsMonitoring',
      slackWorkspaceId: SLACK_WORKSPACE_ID,
      slackChannelId: SLACK_CHANNEL_ID,
      notificationTopics: [alarmTopic], // このトピックへの通知がSlackに送られる
    });</code></pre>
<h3>ECSとRDSの監視アラーム設定</h3>
<p>主要なメトリクスに対してCloudWatchアラームを作成し、アクションとして上記SNSトピックを設定します。</p>
<pre class="line-numbers"><code class="language-js">// --- ECS Fargate アラーム ---
    // ECS CPU利用率が80%を超えた場合にアラーム
    const ecsCpuAlarm = new cloudwatch.Alarm(this, 'EcsCpuHighAlarm', {
      metric: cloudwatch.Metric.fromNamespaceAndName('AWS/ECS', 'CPUUtilization').with({
        dimensionsMap: { ClusterName: CLUSTER_NAME, ServiceName: SERVICE_NAME },
      }),
      threshold: 80, 
      evaluationPeriods: 2,
      comparisonOperator: cloudwatch.ComparisonOperator.GREATER_THAN_OR_EQUAL_TO_THRESHOLD,
      alarmDescription: 'ECS Service CPU utilization is too high.',
    });
    ecsCpuAlarm.addAlarmAction(new actions.SnsAction(alarmTopic));
    // ecsCpuAlarm.addOkAction(new actions.SnsAction(alarmTopic)); // 復旧時も通知したい場合は追加

    // --- RDS アラーム ---
    // RDS CPU利用率が70%を超えた場合にアラーム
    const rdsCpuAlarm = new cloudwatch.Alarm(this, 'RdsCpuHighAlarm', {
      metric: cloudwatch.Metric.fromNamespaceAndName('AWS/RDS', 'CPUUtilization').with({
        dimensionsMap: { DBInstanceIdentifier: RDS_IDENTIFIER },
      }),
      threshold: 70, 
      evaluationPeriods: 3,
      comparisonOperator: cloudwatch.ComparisonOperator.GREATER_THAN_OR_EQUAL_TO_THRESHOLD,
      alarmDescription: 'RDS CPU utilization is too high.',
    });
    rdsCpuAlarm.addAlarmAction(new actions.SnsAction(alarmTopic));</code></pre>
<h3>ECSサービスのオートスケーリング設定</h3>
<p>ECSサービスをCPU利用率$60%$を目標に自動スケーリングするように設定します。</p>
<p><response-element class="" ng-version="0.0.0-PLACEHOLDER"><code-block _nghost-ng-c519592647="" class="ng-tns-c519592647-2199 ng-star-inserted"></code-block></response-element></p>
<div _ngcontent-ng-c519592647="" class="code-block ng-tns-c519592647-2199 ng-animate-disabled ng-trigger ng-trigger-codeBlockRevealAnimation" jslog="223238;track:impression,attention;BardVeMetadataKey:[[&quot;r_a2c461939f765a9a&quot;,&quot;c_86e1e1d55e25872e&quot;,null,&quot;rc_330331dc660dc0f2&quot;,null,null,&quot;ja&quot;,null,1,null,null,1,0]]">
<div _ngcontent-ng-c519592647="" class="code-block-decoration header-formatted gds-title-s ng-tns-c519592647-2199 ng-star-inserted">
<pre class="line-numbers"><code class="language-js">// 3. ECSサービスのオートスケーリング設定
    // サービスのDesired Countをスケーリング対象にする
    const scalableTarget = autoscaling.ScalableTarget.forEcsService(this, 'EcsScalableTarget', {
      service: ecsService,
      minCapacity: 1, // 最小タスク数
      maxCapacity: 5, // 最大タスク数
    });

    // 目標CPU利用率 60% を維持するように調整するターゲット追跡スケーリングポリシー
    scalableTarget.scaleToTrackMetric('CpuScalingPolicy', {
      metric: ecsService.metricCpuUtilization(), 
      targetValue: 60,
      scaleOutCooldown: cdk.Duration.seconds(60),
      scaleInCooldown: cdk.Duration.seconds(300),
    });</code></pre>
</div>
<h3>オートスケールイベントのSlack通知設定</h3>
<p>スケーリング操作の成功イベントをEventBridgeで捕捉し、Slackに通知します。</p>
<p><response-element class="" ng-version="0.0.0-PLACEHOLDER"><code-block _nghost-ng-c519592647="" class="ng-tns-c519592647-2200 ng-star-inserted"></code-block></response-element></p>
<div _ngcontent-ng-c519592647="" class="code-block ng-tns-c519592647-2200 ng-animate-disabled ng-trigger ng-trigger-codeBlockRevealAnimation" jslog="223238;track:impression,attention;BardVeMetadataKey:[[&quot;r_a2c461939f765a9a&quot;,&quot;c_86e1e1d55e25872e&quot;,null,&quot;rc_330331dc660dc0f2&quot;,null,null,&quot;ja&quot;,null,1,null,null,1,0]]">
<div _ngcontent-ng-c519592647="" class="code-block-decoration header-formatted gds-title-s ng-tns-c519592647-2200 ng-star-inserted">
<pre class="line-numbers"><code class="language-js">// 4. オートスケールイベントを捕捉しSNSトピックへルーティング
    new events.Rule(this, 'AutoScalingNotificationRule', {
      description: 'Notify Slack on successful ECS Auto Scaling events.',
      eventPattern: {
        source: ['aws.application-autoscaling'],
        detailType: ['Application Auto Scaling Policy Execution'],
        detail: {
          // 成功したスケーリング操作のみを通知
          statusCode: ['Successful'], 
        },
      },
      // ターゲットは既存のSNSトピック
      targets: [new targets.SnsTopic(alarmTopic)],
    });</code></pre>
</div>
<h2>まとめ</h2>
<p>CDKを使うことで、<b>TypeScriptコード</b>で以下の堅牢な運用基盤を構築できました。</p>
<ol start="1">
<li>ECS/RDSの重要なメトリクス監視</li>
<li>CloudWatch AlarmsとChatbotによるSlackへの即時通知</li>
<li>ECSサービスの負荷に応じた自動スケーリング（スケールイン/アウト）</li>
<li>スケーリング操作完了時の通知</li>
</ol>
<p>インフラをコード化することで、再現性、バージョン管理、レビューが可能になり、システムの信頼性が大きく向上します。</p>
<div _ngcontent-ng-c519592647="" class="code-block-decoration header-formatted gds-title-s ng-tns-c519592647-2200 ng-star-inserted"></div>
</div>
</div>
<p>&nbsp;</p>
<div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://otonan-syusyoku.work/archives/2168/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
