Lightsail インスタンス上の WordPress のディスクとメモリのメトリクスを監視する方法

Lightsail インスタンス上の WordPress のディスクとメモリのメトリクスを監視する手順をまとめました。CloudWatch エージェントのエラー別対処法も添えました!
2021.12.01

この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。

はじめに

バンクーバーでポケモン GO に勤しむオペレーションチームの者です。
さて今回は Lightsail インスタンス上の WordPress のディスクとメモリのメトリクスを取得する機会がありましたので、設定方法についてブログを書きたいと思います。

① IAM ユーザーの作成

CloudWatch にデータを送るための権限を持つ IAM ユーザーを作成します。
IAM コンソールからユーザーを選択し、「ユーザーを追加」をクリックします。

ユーザー名を「lightsail-cloudwatch-agent」とし、「アクセスキー - プログラムによるアクセス」を選択します。

lightsail-cloudwatch-agent


次のステップに進み、「既存のポリシーを直接アタッチ」を選択、検索バーに「CloudWatchAgentServerPolicy」と入力してそのポリシーにチェックマークを入れます。

CloudWatchAgentServerPolicy


オプションのタグの追加はスキップし、レビュー画面で内容に問題ないことを確認したら、「ユーザーの作成」をクリックします。ユーザー作成時に生成される csv ファイルは後ほど使用するので保存しておいてください。


② ターミナルで SSH を使用してインスタンスに接続

ブラウザベースの SSH クライアントで接続を行うことも可能ですが、今回はターミナルで SSH 接続を行います。

対象インスタンスが実行中であることを確認し、対象インスタンス名をクリックします。

実行中


「接続」タブの一番下にある「独自の SSH クライアントを使用する」より、パブリック IPを確認します。
そして、このインスタンスはデフォルトのキーペアを使用しているため、「アカウントページ」をクリックしてプライベートキーをダウンロードをしに行きます。

IPv4とか


デフォルトキーの「ダウンロード」を選択します。

キーのダウンロード


ターミナルを開いて、ダウンロードしたデフォルトキーがあるパスに移動し、chmod コマンドで読み取り・書き込み権限を変更します。
私はオレゴンリージョンでのデフォルトキーを利用しているので以下のようにコマンド入力しました。

$ sudo chmod 600 LightsailDefaultKey-us-west-2.pem


以下のコマンドのパブリック IP を先ほど確認したパブリック IP に置き換えた上で SSH 接続を行ってください。
WordPress は Certified by Bitnami インスタンス上で稼働しているので、ユーザー名は bitnami です。

$ ssh -i LightsailDefaultKey-us-west-2.pem bitnami@パブリックIP


インスタンスに接続ができると、以下のようなメッセージが表示されます。

The programs included with the Debian GNU/Linux system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.

Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.
       ___ _ _                   _
      | _ |_) |_ _ _  __ _ _ __ (_)
      | _ \ |  _| ' \/ _` | '  \| |
      |___/_|\__|_|_|\__,_|_|_|_|_|

  *** Welcome to the WordPress packaged by Bitnami 5.8.1-18        ***

③ CloudWatch エージェントのインストール

次に CloudWatch エージェントをダウンロードします。

Certified by Bitnami インスタンス上で稼働している WordPress の OS は Debian なので、以下のコマンドを実行します。

$ wget https://s3.amazonaws.com/amazoncloudwatch-agent/debian/amd64/latest/amazon-cloudwatch-agent.deb

次に以下のコマンドを実行します。

$ sudo dpkg -i -E ./amazon-cloudwatch-agent.deb

Selecting previously unselected package amazon-cloudwatch-agent.
(Reading database ... 32069 files and directories currently installed.)
Preparing to unpack ./amazon-cloudwatch-agent.deb ...
create group cwagent, result: 0
create user cwagent, result: 0
Unpacking amazon-cloudwatch-agent (1.247349.0b251399-1) ...
Setting up amazon-cloudwatch-agent (1.247349.0b251399-1) ...

④ クレデンシャルのセットアップ

CloudWatch エージェントが AWS リソースにアクセスできるようにクレデンシャルのセットアップを行います。

$ sudo aws configure --profile AmazonCloudWatchAgent

IAM ユーザー作成時に生成された csv ファイルを参考にアクセスキーとシークレットアクセスキーを入力します。

AWS Access Key ID [None]:******************XK
AWS Secret Access Key [None]: ******************7c
Default region name [None]:
Default output format [None]:

⑤ ウィザードを使用して CloudWatch 設定ファイルを生成する

以下のコマンドを実行し、ウィザードを起動します。

$ sudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-config-wizard

そしてAWS ナレッジセンターの記事を参考にしつつ、質問に回答していきます。
以下を除くすべての質問に対してデフォルトの回答を選択できるとのことで、その点だけ注意して進めていきます。

Are you using EC2 or On-Premises hosts?
1. EC2
2. On-Premises
default choice: [1]:
2

Do you want to turn on StatsD daemon?
1. yes
2. no
default choice: [1]:
2

Do you want to monitor metrics from CollectD?
1. yes
2. no
default choice: [1]:
2

Do you want to monitor cpu metrics per core? Additional CloudWatch charges may apply.
1. yes
2. no
default choice: [1]:
2

Do you want to add ec2 dimensions (ImageId, InstanceId, InstanceType, AutoScalingGroupName) into all of your metrics if the info is available?
1. yes
2. no
default choice: [1]:
2

Do you want to monitor any log files?
1. yes
2. no
default choice: [1]:
2

Do you want to store the config in the SSM parameter store?
1. yes
2. no
default choice: [1]:
2

⑥ CloudWatch エージェントの設定を行う

CloudWatch エージェントに先程設定した profile を使用するように設定を行います。

$ sudo vim /opt/aws/amazon-cloudwatch-agent/etc/common-config.toml

iをタイプして入力モードに変更して、以下の設定をペーストします。

[credentials]
shared_credential_profile = "AmazonCloudWatchAgent"

esc で入力モードを抜けた後、wq!をタイプして vim から抜けます。
反映されているか以下で念のため確認しておきます。

$ sudo cat /opt/aws/amazon-cloudwatch-agent/etc/common-config.toml

# This common-config is used to configure items used for both ssm and cloudwatch access


## Configuration for shared credential.
## Default credential strategy will be used if it is absent here:
## 	Instance role is used for EC2 case by default.
##	AmazonCloudWatchAgent profile is used for onPremise case by default.
# [credentials]
#    shared_credential_profile = "{profile_name}"
#    shared_credential_file = "{file_name}"

[credentials]
shared_credential_profile = "AmazonCloudWatchAgent"

(省略)

⑦ CloudWatch エージェントを有効にする

以下のコマンドで CloudWatch エージェントを有効にします。
Configuration validation succeeded」が表示されることを確認します。

$ sudo amazon-cloudwatch-agent-ctl -c file:/opt/aws/amazon-cloudwatch-agent/bin/config.json -a fetch-config -s
(省略)
Configuration validation first phase succeeded
/opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent -schematest -config /opt/aws/amazon-cloudwatch-agent/etc/amazon-cloudwatch-agent.toml
Configuration validation second phase succeeded
Configuration validation succeeded

以下のコマンドで CloudWatch エージェントが問題なく起動されているかを確認します。

$ sudo amazon-cloudwatch-agent-ctl -a status
{
  "status": "running",
  "starttime": "2021-11-29T18:48:28+00:00",
  "configstatus": "configured",
  "cwoc_status": "stopped",
  "cwoc_starttime": "",
  "cwoc_configstatus": "not configured",
  "version": "1.247349.0b251399"
}

⑧ CloudWatch メトリクスを確認する

無事に CloudWatch にてメモリとディスクのメトリクスを確認することができました。

カスタムメトリクス

CloudWatch でメトリクスが表示されない場合

CloudWatch エージェントのログを以下のコマンドで確認し、エラーを解消する必要があります。

$ sudo cat /opt/aws/amazon-cloudwatch-agent/logs/amazon-cloudwatch-agent.log

エラー別対処法

AccessDenied で IAM ユーザーの権限が足りてないというエラー

E! cloudwatch: code: AccessDenied,
 message: User: arn:aws:iam::XXXXXXXXXXXX:user/lightsail-cloudwatch-agent is not authorized to perform:
 cloudwatch:PutMetricData because no identity-based policy allows the cloudwatch:PutMetricData action, original error: <nil>

$ sudo aws configure --profile AmazonCloudWatchAgentで正しい IAM ユーザーのアクセスキーなどが格納されているか、IAM ポリシーをつけ間違えていないかをご確認ください。

AccessDenied で IAM ロールの権限が足りてないというエラー

E! cloudwatch: code: AccessDenied,
 message: User: arn:aws:sts::XXXXXXXXXXXX:assumed-role/AmazonLightsailInstanceRole/i-XXXXXXXXXXXXXXXXX is not authorized to perform:
 cloudwatch:PutMetricData because no identity-based policy allows the cloudwatch:PutMetricData action, original error: <nil>

$ sudo vim /opt/aws/amazon-cloudwatch-agent/etc/common-config.toml で正しくクレデンシャルが入力されているかご確認ください。

権限不足でクレデンシャルファイルが開けないというエラー

E! cloudwatch: code: SharedCredsLoad, message: failed to load shared credentials file, original error:
 FailedRead: unable to open file
caused by: open /root/.aws/credentials: permission denied

ウィザードを使用して CloudWatch 設定ファイルを生成するステップを見直してみてください。

おわりに

AWS ブログとナレッジセンターの記事をもとに設定を行ってきましたが、意外と詰まる部分がありました。  CloudWatch エージェント周りのことが勉強になりました。以上です!

参照