DatadogでAWSインテグレーションのモニターを作成してみた

2020.05.18

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

こんにちは、CX事業本部の若槻です。

今回は、DatadogでAWSとのインテグレーションの設定を行い、AWSサービスのメトリクスを監視するモニターを作成してみたのでご紹介します。

Datadogとは

Datadogとは、様々なサーバーやアプリケーションから取得したメトリクスやログデータをもとにアラート通知を実装したり、分析を行ったりすることができるクラウド型のモニタリングツールです。

また、DatadogにはAWS、Azure、Google Cloudなど主要なクラウドサービスに対するインテグレーションが標準で用意されており、このインテグレーションを利用することにより監視対象のサービスとDatadogの連携を簡単に実装することができます。

DatadogでAWSインテグレーションのモニターを作成してみる

ここから、Datadogアカウントのサインアップから、AWSインテグレーションのモニターを作成し実際にアラートを動作させてみるまでの流れを、悪戦苦闘の記録をそのままに残しつつ、キャプチャ付きで紹介していきます。

Datadogアカウントのサインアップ

まずはDatadogのアカウントを無償版でサインアップします。

Datadogトップページ を開きます。画面右上にある[無料で試す]をクリックし、情報を入力して[サインアップ]をクリックします。 image.png

[2. Your Stack]ページが開き、Datadogと接続するスタックについて聞かれます。[Next]をクリックします。(画像では[Tell us about your stack]で「AWS」を選択していますが、今回は結局不要となりました) image.png

[3. Agent Setup]ページが開き、Datadog Agentのインストールを促されます。Agentが最低1つは必要とのことなので、今回はCloud9環境にインストールするために、[Amazon Linux]を選択します。[New Installation]欄のAgentインストール用のコマンドをコピーします。 image.png

コピーしたコマンドをCloud9(Amazon Linux)上のShellで実行し、Datadog Agentをインストールします。

$ DD_AGENT_MAJOR_VERSION=7 DD_API_KEY=************ bash -c "$(curl -L https://raw.githubusercontent.com/DataDog/datadog-agent/master/cmd/agent/install_script.sh)"
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100 15080  100 15080    0     0  71132      0 --:--:-- --:--:-- --:--:-- 71132

* Installing YUM sources for Datadog

* Installing the Datadog Agent package

Loaded plugins: priorities, update-motd, upgrade-helper
Cleaning repos: amzn-main amzn-updates datadog epel
19 metadata files removed
9 sqlite files removed
0 metadata files removed
Loaded plugins: priorities, update-motd, upgrade-helper
Resolving Dependencies
--> Running transaction check
---> Package datadog-agent.x86_64 1:7.19.2-1 will be installed
--> Finished Dependency Resolution

Dependencies Resolved

================================================================================
 Package               Arch           Version             Repository       Size
================================================================================
Installing:
 datadog-agent         x86_64         1:7.19.2-1          datadog         133 M

Transaction Summary
================================================================================
Install  1 Package

Total download size: 133 M
Installed size: 441 M
Downloading packages:
warning: /var/cache/yum/x86_64/latest/datadog/packages/datadog-agent-7.19.2-1.x86_64.rpm: Header V4 RSA/SHA1 Signature, key ID e09422b3: NOKEY
Public key for datadog-agent-7.19.2-1.x86_64.rpm is not installed
Retrieving key from https://yum.datadoghq.com/DATADOG_RPM_KEY_E09422B3.public
Importing GPG key 0xE09422B3:
 Userid     : "Datadog, Inc <package@datadoghq.com>"
 Fingerprint: a4c0 b90d 7443 cf6e 4e8a a341 f106 8e14 e094 22b3
 From       : https://yum.datadoghq.com/DATADOG_RPM_KEY_E09422B3.public
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
  Installing : 1:datadog-agent-7.19.2-1.x86_64                              1/1 
Enabling service datadog-agent
Loading SELinux policy module for datadog-agent.
Couldn’t load system-probe policy.
To be able to run system-probe on your host, please install or update the selinux-policy-targeted and
policycoreutils-python (or policycoreutils-python-utils depending on your distribution) packages.
Then run the following commands, or reinstall datadog-agent:
    semodule -i /etc/datadog-agent/selinux/system_probe_policy.pp
    semanage fcontext -a -t system_probe_t /opt/datadog-agent/embedded/bin/system-probe
    restorecon -v /opt/datadog-agent/embedded/bin/system-probe
No datadog.yaml file detected, not starting the agent
  Verifying  : 1:datadog-agent-7.19.2-1.x86_64                              1/1 

Installed:
  datadog-agent.x86_64 1:7.19.2-1                                               

Complete!

* Adding your API key to the Agent configuration: /etc/datadog-agent/datadog.yaml

* Starting the Agent...

stop: Unknown instance: 
datadog-agent start/running, process 4293


Your Agent is running and functioning properly. It will continue to run in the
background and submit metrics to Datadog.

If you ever want to stop the Agent, run:

    sudo stop datadog-agent

And to run it again run:

    sudo start datadog-agent

Datadogの画面に戻り、10秒ほど待つと[Next]がクリック可能となったので、クリックして次に進みます。 76aad502-636b-43b0-b60d-bbda7991dbfa.png

[2. Your Stack]ページで何らかのスタックを選択していた場合はオプションでIntegrationのインストールが可能です。「AWS」を選択した場合は下記のようになります。[Install Integration]をクリックしてみます。 image.png

[Amazon Web Services Integration]ダイアログが開き、AWSのどのサービスをモニター対象とするか、および接続するアカウント情報を求められます。今回は一旦サインアップを完了させるため、[☓]でダイアログを閉じて[Skip]をクリックし、サインアップを完了させました。 image.png

サインアップしたアカウントのトップページが開きました。 image.png

[Events]を選択すると、アカウント上で行われたイベントが確認できます。サインアップ中にCloud9にインストールしたAgentのホストはi-038ff4fe29665bea7というIDで管理されていることが分かります。 image.png

[Monitors] - [Manage Monitors]を見ると、[Auto] Clock in sync with NTPというモニターが作成されています。 image.png

[Auto] Clock in sync with NTPの詳細を見ると、host:i-038ff4fe29665beとあり、これがサインアップ時にインストールしたエージェントを監視するモニターであるようです。 image.png

これでDatadogのサインアップが完了しました。

AWSのインテグレーションのインストール

次にAWSのインテグレーションのインストールを行い、DatadogとAWSのアカウント連携を行います。

[Integrations]を選択し、「aws」でフィルターをして、AvailableなIntegration一覧から「Amazon Web Services」を選択します。 image.png

AWSのIntegration設定画面が開きます。[Configuration]タブを選択します(サインアップ時と同じ画面です)。[AWS Accout]欄ではDatadogと連携させるAWSアカウントの情報の入力が必要となります。今回は自動でRole Delegationのセットアップを行ってみるため、[Automatically Using CloudFormation]を選択します。1 image.png

ブラウザの別タブでCloudFormationスタックの作成画面が開きます。(AWSにサインインしていない場合はサインインを要求されるかと思うのでサインインします。) image.png

[テンプレート URL]によれば、このスタックはDatadogが管理している以下のCloudFormationテンプレートを元にしたスタックであるようです。

  • https://datadog-cloudformation-template.s3.amazonaws.com/aws/main.yaml
AWSTemplateFormatVersion: 2010-09-09
Description: Datadog AWS Integration
Parameters:
  ExternalId:
    Description: >-
      External ID for the Datadog role (generate at
      https://app.datadoghq.com/account/settings#integrations/amazon-web-services)
    Type: String
    AllowedPattern: .+
    ConstraintDescription: ExternalId is required
  DdApiKey:
    Description: >-
      API key for the Datadog account (find at
      https://app.datadoghq.com/account/settings#api)
    Type: String
    NoEcho: true
    AllowedPattern: .+
    ConstraintDescription: DdApiKey is required
  DdSite:
    Type: String
    Default: datadoghq.com
    Description: Define your Datadog Site to send data to. For the Datadog EU site, set to datadoghq.eu
    AllowedPattern: .+
    ConstraintDescription: DdSite is required
  IAMRoleName:
    Description: Customize the name of IAM role for Datadog AWS integration
    Type: String
    Default: DatadogIntegrationRole
  Permissions:
    Description: >-
      Customize the permission level for the Datadog IAM role.
      Select "Core" to only grant Datadog read-only permissions (not recommended).
    Type: String
    Default: Full
    AllowedValues:
      - Full
      - Core
  LogArchives:
    Description: >-
      S3 paths to store log archives for log rehydration. Separate multiple paths with comma,
      e.g., "my-bucket,my-bucket-with-path/path". Permissions will be automatically added to
      the Datadog integration IAM role. https://docs.datadoghq.com/logs/archives/rehydrating/?tab=awss3
    Type: String
    Default: ''
  CloudTrails:
    Description: >-
      S3 buckets for Datadog CloudTrail integration. Separate multiple buckets with comma,
      e.g., "bucket1,bucket2". Permissions will be automatically added to the Datadog integration IAM role.
      https://docs.datadoghq.com/integrations/amazon_cloudtrail/
    Type: String
    Default: ''
  DdAWSAccountId:
    Description: >-
      Datadog AWS account ID allowed to assume the integration IAM role. DO NOT CHANGE!
    Type: String
    Default: "464622532012"
  DdForwarderName:
    Type: String
    Default: DatadogForwarder
    Description: >-
      The Datadog Forwarder Lambda function name. DO NOT change when updating an existing CloudFormation stack,
      otherwise the current forwarder function will be replaced and all the triggers will be lost.
  InstallDatadogPolicyMacro:
    Type: String
    Default: true
    AllowedValues:
      - true
      - false
    Description: If you already deployed a stack using this template, set this parameter to false to skip the installation of the DatadogPolicy Macro again.
Conditions:
  ShouldInstallDatadogPolicyMacro:
    Fn::Equals:
      - Ref: InstallDatadogPolicyMacro
      - true
Resources:
  # A Macro used to generate policies for the integration IAM role based on user inputs
  DatadogPolicyMacroStack:
    Type: AWS::CloudFormation::Stack
    Condition: ShouldInstallDatadogPolicyMacro
    Properties:
      TemplateURL: "https://datadog-cloudformation-template.s3.amazonaws.com/aws/datadog_policy_macro.yaml"
  # The IAM role for Datadog integration
  DatadogIntegrationRoleStack:
    Type: AWS::CloudFormation::Stack
    Properties:
      TemplateURL: "https://datadog-cloudformation-template.s3.amazonaws.com/aws/datadog_integration_role.yaml"
      Parameters:
        ExternalId: !Ref ExternalId
        Permissions: !Ref Permissions
        IAMRoleName: !Ref IAMRoleName
        LogArchives: !Ref LogArchives
        CloudTrails: !Ref CloudTrails
        DdAWSAccountId: !Ref DdAWSAccountId
      Tags:
        - # A trick to create a conditional dependency on DatadogPolicyMacroStack
          # https://stackoverflow.com/questions/34607476/cloudformation-apply-condition-on-dependson
          Key: "DatadogPolicyMacroStackId"
          Value: !If [ShouldInstallDatadogPolicyMacro, !Ref DatadogPolicyMacroStack, "null"]
  # The Lambda function to ship logs from S3 and CloudWatch, custom metrics and traces from Lambda functions to Datadog
  # https://github.com/DataDog/datadog-serverless-functions/tree/master/aws/logs_monitoring
  ForwarderStack:
    Type: AWS::CloudFormation::Stack
    Properties:
      TemplateURL: "https://datadog-cloudformation-template.s3.amazonaws.com/aws/forwarder/latest.yaml"
      Parameters:
        DdApiKey: !Ref DdApiKey
        DdSite: !Ref DdSite
        FunctionName: !Ref DdForwarderName
Metadata:
  AWS::CloudFormation::Interface:
    ParameterGroups:
    - Label:
        default: Required
      Parameters:
        - ExternalId
        - DdApiKey
        - DdSite
    - Label:
        default: Optional
      Parameters:
        - IAMRoleName
        - Permissions
        - LogArchives
        - CloudTrails
    - Label:
        default: Advanced
      Parameters:
        - DdAWSAccountId
        - DdForwarderName
        - InstallDatadogPolicyMacro
    ParameterLabels:
      ExternalId:
        default: "ExternalId *"
      DdApiKey:
        default: "DdApiKey *"
      DdSite:
        default: "DdSite *"

DatadogのAPI Keyは手動での指定が必要となります。Datadogの画面に戻り[Datadog API Key]のリンクをクリックして開きます。 image.png

DataDogの[Integrations] - [APIs]の画面が開きます。[API Keys]を開くとAPIキーが既定で1つ作成されているので、コピーします。 image.png

コピーしたAPIキーをスタック作成画面で[DdApiKey]欄にペーストします。また、リージョンはバージニア北部から適宜変更してください。 image.png

承認次項にチェックを入れて、[スタックの作成]をクリックします。 image.png

ネストされたものを含め4つのスタックが作成されました。 image.png

Datadogの画面に戻ります。[AWS Account ID]欄に連携させるAWSアカウントのIDを入力し、[AWS Role name] 欄に連携に利用するロール名としてDatadogIntegrationRoleを入力します。ロール名は自動作成の場合は既定でDatadogIntegrationRoleとなります。 image.png

[Install Integration]をクリックしてインテグレーションをインストールします。(最初に誤ったアカウントIDやロール名を入力してしまったせいか、正しい値を入力した後も画面右上のエラーが出続けていましたが、インストールは成功しました。)また今回はどのAWSサービスを監視対象とするかのフィルター(画面左)は特に設定しませんでした。 image.png

[Integrations]の一覧にインストールされたインテグレーション一覧にAWSの各種サービスが追加されました。 image.png

これで、AWSのインテグレーションによるDatadogとAWSのアカウント連携は完了です。

AWSのインテグレーションを利用したモニターの作成

次に、Datadogとインテグレーションにより連携したAWSアカウント上のサービスを監視するモニターを作成します。

なお、今回はモニターの詳細な設定については触れず、とりあえず動くものを作ることを趣旨としたいと思います。

[Monitors]で[New Monitor]をクリックします。 image.png

モニタータイプとして[Integration]を選択します。 image.png

作成に利用するインテグレーションとして[AWS]を選択します。 image.png

モニターの設定画面が開きます。[2 Define the metric]では監視するメトリックを指定します。今回はsample-tableというDynamoDBテーブルのアイテム数を関しするようにしました。[3 Set alert conditions]ではアラートや警告を上げ下げする基準を指定します。今回は1アイテムが検知されたらアラートを上げるようにしました。[4 Say what's happening]ではモニター名とモニターの詳細を指定します。 image.png

最後に設定画面の一番下部の[Save]をクリックして設定を保存します。 image.png

モニター一覧に戻ると作成したモニターが表示されているので選択します。 image.png

作成直後はメトリクスデータが一つも取得できていないためモニターのステータスはNO DATAとなっています。 image.png

sample-tableテーブルではあらかじめアイテムが作成済みだったので、少し経つとメトリクスデータが取得され、アラートの基準に抵触してモニターのステータスがALERTに変わりました。 image.png

おわりに

今回はDatadogとAWSでとりあえず動くものを作ってみることを目標にしたので詳細な設定などは深くは触れられていませんが、用意されているインテグレーションの数や設定パラメータの豊富さを見る限り、本当に様々なモニタリングが行えそうだという可能性を感じました。是非とも使いこなせるようになりたいですね!

以上


  1. ロールを手動で用意する場合は、こちらの記事が参考になります。Datadog のAWS監視にIAMロールを利用してみた