CloudWatch Agent のメトリクス(ログも)を別リージョンへ送ってみる

2019.02.27

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

こんにちは オペレーション部 園部です。

CloudWatch のドキュメントを読んでいた際に、こんな記載を見つけたので実際に、やってみました。

CloudWatch エージェントを Amazon EC2 インスタンスにインストールした場合は、プロキシ設定を指定するか、インスタンスとは別のリージョンにある CloudWatch にエージェントからメトリクスを送信するときに限り、このファイルを変更します。

(引用:公式ドキュメントより)

やってみた

今回は、東京リージョンに作成したEC2へCloudWatch Agentをインストールし、CloudWatch Agentから取得できるメトリクスを バージニア北部リージョン(us-east-1)へ送ります。

1. CloudWatch Agent インストール

※ 詳細な手順は、公式ドキュメントをご確認ください。 公式ドキュメント

「Systems Manager」 >>> 「Run Command」 >>> 「AWS-ConfigureAWSPackage」 を利用して、 "AmazonCloudWatchAgent" をインストールを行います。

2. 名前付きプロファイル作成

2-1. IAM ユーザー作成

今回、IAM部分はシンプルにしておくため、IAMユーザーを作成して、クレデンシャル情報を取得します。

  • ユーザー名: clouwatch-agent-another-region
  • ポリシー: CloudWatchAgentServerRole

参考情報:公式ドキュメント

2-2. 名前付きプロファイル作成

2-1 で取得したクレデンシャル情報を利用して、root ユーザーへ新しいプロファイルを作成します。 プロファイル名はAmazonCloudWatchAgentとします。

  • AWS Access Key ID [None]: 2-1 で取得した情報
  • AWS Secret Access Key [None]: 2-1 で取得した情報
  • Default region name [None]: us-east-1(バージニア北部)
  • Default output format [None]:
$ sudo aws configure --profile AmazonCloudWatchAgent
AWS Access Key ID [None]: *******
AWS Secret Access Key [None]: *******
Default region name [None]: us-east-1
Default output format [None]:
$ cat .aws/config
[profile AmazonCloudWatchAgent]
region = us-east-1

3. CloudWatch Agent 構成ファイル修正

EC2へCloudWatch Agentをインストールすると以下のディレクトリとファイルが作成されます。

$ ls -l /opt/aws/amazon-cloudwatch-agent/
合計 120
-rw-r--r-- 1 root root 4705 1月 19 08:22 LICENSE
-rw-r--r-- 1 root root 96 1月 19 08:22 NOTICE
-rw-r--r-- 1 root root 3257 1月 19 08:22 RELEASE_NOTES
-rw-r--r-- 1 root root 104223 1月 19 08:22 THIRD-PARTY-LICENSES
drwxr-xr-x 2 root root 227 2月 27 04:50 bin
drwxr-xr-x 2 root root 49 2月 27 04:50 doc
drwxr-xr-x 3 root root 65 2月 27 04:50 etc
drwxr-xr-x 2 root root 6 1月 19 08:22 logs
drwxr-xr-x 2 root root 6 1月 19 08:22 var

3-1. 共通設定ファイルを変更

上記のディレクトリ内にある「common-config.toml」を変更します。

ファイル詳細情報:公式ドキュメント

$ 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}"

## Configuration for proxy.
## System-wide environment-variable will be read if it is absent here.
## i.e. HTTP_PROXY/http_proxy; HTTPS_PROXY/https_proxy; NO_PROXY/no_proxy
## Note: system-wide environment-variable is not accessible when using ssm run-command.
## Absent in both here and environment-variable means no proxy will be used.
# [proxy]
# http_proxy = "{http_url}"
# https_proxy = "{https_url}"
# no_proxy = "{domain}"

[変更前]

# [credentials]
# shared_credential_profile = "{profile_name}"
# shared_credential_file = "{file_name}"

[変更後]

[credentials]
shared_credential_profile = "AmazonCloudWatchAgent"
# shared_credential_file = "{file_name}"

4. CloudWatch Agent 設定ファイル作成

設定ウィザードから設定します。以下の2点だけご注意ください。

  • parameter store name
  • region
$ sudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-config-wizard
=============================================================
= Welcome to the AWS CloudWatch Agent Configuration Manager =
=============================================================
On which OS are you planning to use the agent?
1. linux
2. windows
default choice: [1]:

Trying to fetch the default region based on ec2 metadata...
Are you using EC2 or On-Premises hosts?
1. EC2
2. On-Premises
default choice: [1]:

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 any host metrics? e.g. CPU, memory, etc.
1. yes
2. no
default choice: [1]:

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

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]:

Would you like to collect your metrics at high resolution (sub-minute resolution)? This enables sub-minute resolution for all metrics, but you can customize for specific metrics in the output json file.
1. 1s
2. 10s
3. 30s
4. 60s
default choice: [4]:

Which default metrics config do you want?
1. Basic
2. Standard
3. Advanced
4. None
default choice: [1]:

Current config as follows:
{
    "metrics": {
        "append_dimensions": {
            "AutoScalingGroupName": "${aws:AutoScalingGroupName}",
            "ImageId": "${aws:ImageId}",
            "InstanceId": "${aws:InstanceId}",
            "InstanceType": "${aws:InstanceType}"
        },
        "metrics_collected": {
            "mem": {
                "measurement": [
                    "mem_used_percent"
                ],
                "metrics_collection_interval": 60
            },
            "swap": {
                "measurement": [
                    "swap_used_percent"
                ],
                "metrics_collection_interval": 60
            }
        }
    }
}
Are you satisfied with the above config? Note: it can be manually customized after the wizard completes to add additional items.
1. yes
2. no
default choice: [1]:

Do you have any existing CloudWatch Log Agent (http://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/AgentReference.html) configuration file to import for migration?
1. yes
2. no
default choice: [2]:

Do you want to monitor any log files?
1. yes
2. no
default choice: [1]:
2
Saved config file to /opt/aws/amazon-cloudwatch-agent/bin/config.json successfully.
Current config as follows:
{
    "metrics": {
        "append_dimensions": {
            "AutoScalingGroupName": "${aws:AutoScalingGroupName}",
            "ImageId": "${aws:ImageId}",
            "InstanceId": "${aws:InstanceId}",
            "InstanceType": "${aws:InstanceType}"
        },
        "metrics_collected": {
            "mem": {
                "measurement": [
                    "mem_used_percent"
                ],
                "metrics_collection_interval": 60
            },
            "swap": {
                "measurement": [
                    "swap_used_percent"
                ],
                "metrics_collection_interval": 60
            }
        }
    }
}
Please check the above content of the config.
The config file is also located at /opt/aws/amazon-cloudwatch-agent/bin/config.json.
Edit it manually if needed.
Do you want to store the config in the SSM parameter store?
1. yes
2. no
default choice: [1]:

What parameter store name do you want to use to store your config? (Use 'AmazonCloudWatch-' prefix if you use our managed AWS policy)
default choice: [AmazonCloudWatch-linux]
AmazonCloudWatch-linux-US-EAST-1
Trying to fetch the default region based on ec2 metadata...
Which region do you want to store the config in the parameter store?
default choice: [ap-northeast-1]
us-east-1
Which AWS credential should be used to send json config to parameter store?
1. ASIA3Q5AECC24S2AC7XN(From SDK)
2. Other
default choice: [1]:

Successfully put config to parameter store AmazonCloudWatch-linux-US-EAST-1.
Program exits now.

バージニア北部リージョンのSystems Manager パラメータストアに保存されます

5. CloudWatch Agent 設定ファイル適用

東京リージョンのSystems Manager にて 「Systems Manager」 >>> 「RunCommand」 >>> 「AmazonCloudWatch-ManageAgent」 を利用してインストールを行います。

現在の設定内容は、サーバ内のファイルで確認できます。

$ cat /opt/aws/amazon-cloudwatch-agent/etc/amazon-cloudwatch-agent.toml
[agent]
  collection_jitter = "0s"
  debug = false
  flush_interval = "1s"
  flush_jitter = "0s"
  hostname = ""
  interval = "60s"
  logfile = "/opt/aws/amazon-cloudwatch-agent/logs/amazon-cloudwatch-agent.log"
  metric_batch_size = 1000
  metric_buffer_limit = 10000
  omit_hostname = false
  precision = ""
  quiet = false
  round_interval = false

[inputs]

  [[inputs.mem]]
    fieldpass = ["used_percent"]
    interval = "60s"

  [[inputs.swap]]
    fieldpass = ["used_percent"]
    interval = "60s"
    
[outputs]

  [[outputs.cloudwatch]]
    force_flush_interval = "60s"
    namespace = "CWAgent"
    profile = "AmazonCloudWatchAgent"
    region = "us-east-1"
    shared_credential_file = "/root/.aws/credentials"
    tagexclude = ["host"]
    [outputs.cloudwatch.tagdrop]
      log_group_name = ["*"]

[processors]

  [[processors.ec2tagger]]
    ec2_instance_tag_keys = ["aws:autoscaling:groupName"]
    ec2_metadata_tags = ["ImageId", "InstanceId", "InstanceType"]
    profile = "AmazonCloudWatchAgent"
    refresh_interval_seconds = "2147483647s"
    shared_credential_file = "/root/.aws/credentials"
    [processors.ec2tagger.tagdrop]
      log_group_name = ["*"]

6. 結果確認

今回、作成したインスタンスのIDは「i-01cae6566d0c1277e」となります。 東京リージョンに作成されています。

6-1. CloudWatch (バージニア北部)

  • CWAgent としてメトリクスが存在します。

  • 別リージョンへ送信されるメトリクスは、CloudWatch Agentで取得されるメトリクスのみのようです。

6-1. CloudWatch (東京)

  • 東京リージョンに、デフォルトのメトリクスはあります。

まとめ

リージョンを跨いだメトリクスの送信は出来ないと認識していたので、新しい発見でした。

現時点での仕様として、対象が CloudWatch Agentによるメトリクスのみのため、デフォルトで取得できるメトリクスと分かれてしまうの辛いところです。 出来たらいいなと思った複数リージョンに送信することは出来ませんでした(再設定すると設定ファイルが上書きになるため、単一リージョンへの送信のみ)。

この辺りは今後に期待という思いです。

ここまで書いて、ログはどうだろう?と思い確認しました。こちらも同様に、別リージョンへ送信することが出来ました! こちらは、ログ分析などのユースケースによっては、使い道があるではないでしょうか。