본문 바로가기
WIKI 기술 지식 베이스

Terraform으로 RDS Autodiscovery를 사용한 Datadog Database Monitoring 설정하기

원문 보기 위키 갱신

이 가이드는 Terraform을 사용해 RDS Autodiscovery가 활성화된 EC2 인스턴스에 Datadog Agent를 배포하는 과정을 안내해요. 에이전트가 AWS 계정에서 적격한 RDS 인스턴스를 자동으로 발견하고 Database Monitoring 메트릭 수집을 시작해요 — 수동 구성이 필요 없어요.

출처: 문서

본문

시작하기 전에

지원되는 데이터베이스: Postgres, MySQL

지원되는 Agent 버전: 7.74.0+

이것이 프로비저닝하는 것:

  • 최신 버전의 Datadog Agent를 실행하는 EC2 인스턴스(t3.medium)
  • rds:DescribeDBInstances를 호출할 권한을 부여하는, EC2 인스턴스에 할당된 IAM 역할
  • EC2 인스턴스에 적용된 아웃바운드 인터넷 접근을 허용하는 보안 그룹

사전 요구사항:

  • Terraform, AWS Security Groups, VPC 네트워킹에 대한 이해(별도 VPC에 에이전트를 배포한다면 VPC peering 포함)
  • use_dbm:true 태그가 적용된 계정에 존재하는 기존 RDS 인스턴스
  • Terraform >= 1.3.0
  • VPC의 공용 서브넷(또는 NAT 게이트웨이가 있는 프라이빗 서브넷)이 있어 에이전트가 datadoghq.com에 도달할 수 있어야 함

개요 (Overview)

  1. 각 RDS 인스턴스에 Datadog 모니터링 사용자 만들기
  2. 비밀을 환경 변수로 설정하기
  3. Terraform으로 에이전트 배포하기

각 RDS 인스턴스에 Datadog 모니터링 사용자 만들기

Datadog 문서를 따라 각 RDS 인스턴스에 datadog 모니터링 사용자를 만들어요:

다음 단계에서 TF_VAR_datadog_db_password로 설정할 비밀번호와 동일한 비밀번호를 사용하세요.

비밀을 환경 변수로 설정하기

Terraform을 실행하기 전에 비밀을 셸로 내보내세요. 이렇게 하면 민감한 값을 디스크의 파일에 저장하지 않아요.

export TF_VAR_datadog_api_key="<YOUR_DATADOG_API_KEY>"
export TF_VAR_datadog_db_password="<YOUR_DATADOG_DB_PASSWORD>"

Datadog API 키는 Datadog UI의 Organization Settings > API Keys에서 찾을 수 있어요.

Terraform으로 에이전트 배포하기

main.tf라는 파일을 다음 내용으로 만들어요. 적용하기 전에 다음 값을 교체하세요:

  • region — AWS 리전
  • vpc_id — 기존 VPC의 ID
  • subnet_id — 에이전트를 배포할 서브넷의 ID
terraform {
  required_version = ">= 1.3.0"
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }
}

provider "aws" {
  region = "us-east-1" # replace with your AWS region
}

# -------------------------------------------------------
# Variables — set via environment variables
# export TF_VAR_datadog_api_key="<your-api-key>"
# export TF_VAR_datadog_db_password="<your-db-password>"
# -------------------------------------------------------

variable "datadog_api_key" {
  description = "Datadog API key"
  type        = string
  sensitive   = true
}

variable "datadog_db_password" {
  description = "Password for the 'datadog' monitoring user on your RDS instances"
  type        = string
  sensitive   = true
}

# -------------------------------------------------------
# Look up the latest Amazon Linux 2 AMI
# -------------------------------------------------------

data "aws_ami" "amazon_linux_2" {
  most_recent = true
  owners      = ["amazon"]

  filter {
    name   = "name"
    values = ["amzn2-ami-hvm-*-x86_64-gp2"]
  }
}

# -------------------------------------------------------
# IAM — let the agent call rds:DescribeDBInstances
# so it can autodiscover RDS instances in your account
# -------------------------------------------------------

resource "aws_iam_role" "agent" {
  name = "dd-dbm-agent-role" # replace with your preferred name

  assume_role_policy = jsonencode({
    Version = "2012-10-17"
    Statement = [{
      Effect    = "Allow"
      Principal = { Service = "ec2.amazonaws.com" }
      Action    = "sts:AssumeRole"
    }]
  })
}

resource "aws_iam_role_policy" "rds_autodiscovery" {
  name = "dd-dbm-agent-rds-autodiscovery"
  role = aws_iam_role.agent.id

  policy = jsonencode({
    Version = "2012-10-17"
    Statement = [{
      Effect   = "Allow"
      Action   = ["rds:DescribeDBInstances"]
      Resource = "*"
    }]
  })
}

resource "aws_iam_instance_profile" "agent" {
  name = "dd-dbm-agent-profile"
  role = aws_iam_role.agent.name
}

# -------------------------------------------------------
# Security Group — outbound internet access only
# -------------------------------------------------------

resource "aws_security_group" "agent" {
  name   = "dd-dbm-agent-sg"
  vpc_id = "vpc-xxxxxxxxxxxxxxxxx" # replace with your VPC ID

  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }
}

# -------------------------------------------------------
# EC2 Instance — Datadog agent with RDS autodiscovery
# -------------------------------------------------------

resource "aws_instance" "agent" {
  ami                         = data.aws_ami.amazon_linux_2.id
  instance_type               = "t3.medium"
  subnet_id                   = "subnet-xxxxxxxxxxxxxxxxx" # replace with your public subnet ID
  iam_instance_profile        = aws_iam_instance_profile.agent.name
  vpc_security_group_ids      = [aws_security_group.agent.id]
  associate_public_ip_address = true
  user_data_replace_on_change = true

  user_data = <<-EOF
    #!/bin/bash
    set -e

    # Install Datadog Agent 7
    DD_API_KEY="${var.datadog_api_key}" DD_SITE="datadoghq.com" \
      bash -c "$(curl -L https://install.datadoghq.com/scripts/install_script_agent7.sh)"

    # Enable RDS autodiscovery — the agent will poll rds:DescribeDBInstances
    # every 300 seconds and auto-configure monitoring for discovered instances
    cat >> /etc/datadog-agent/datadog.yaml <<DDCONFIG

    database_monitoring:
      autodiscovery:
        rds:
          enabled: true
          discovery_interval: 300
          tags:
            - "use_dbm:true"
          dbm_tag: "use_dbm:true"
    DDCONFIG

    # Postgres integration template
    # %%host%%, %%port%%, %%extra_*%% are filled in by the agent at runtime
    cat > /etc/datadog-agent/conf.d/postgres.d/conf_aws_rds.yaml <<PGCONF
    ad_identifiers:
      - _dbm_postgres
    init_config:
    instances:
      - host: "%%host%%"
        port: "%%port%%"
        username: datadog
        password: "${var.datadog_db_password}"
        dbm: "%%extra_dbm%%"
        database_autodiscovery:
          enabled: true
        collect_schemas:
          enabled: true
        collect_settings:
          enabled: true
        aws:
          instance_endpoint: "%%host%%"
          region: "%%extra_region%%"
        tags:
          - "dbinstanceidentifier:%%extra_dbinstanceidentifier%%"
    PGCONF

    systemctl restart datadog-agent
  EOF

  tags = {
    Name = "dd-dbm-agent" # optional — replace or remove
  }
}

초기화하고 적용하세요:

terraform init
terraform apply

참고: Agent Autodiscovery는 같은 AWS 리전 내에서 실행되는 RDS 인스턴스만 발견할 수 있어요. autodiscovery 구성의 use_dbm 필드는 어떤 RDS 인스턴스가 발견되는지 제어해요. 이 가이드에서는 use_dbm:true가 사용되지만, RDS 인스턴스에 적용된 어떤 사용자 정의 태그로도 교체할 수 있어요. 데이터베이스 표준 통합으로 계정의 모든 RDS 인스턴스를 모니터링해 높은 수준의 메트릭을 얻으려면 datadog.yaml에서 tags를 빈 배열로 설정하세요:

database_monitoring:
  autodiscovery:
    rds:
      enabled: true
      tags: []

지원되는 템플릿 변수

다음 변수는 발견된 각 RDS 인스턴스에서 실행 시점에 에이전트가 자동으로 채워요:

템플릿 변수 출처
%%host%% RDS 인스턴스 엔드포인트
%%port%% RDS 인스턴스 포트
%%extra_region%% 인스턴스가 위치한 AWS 리전
%%extra_dbinstanceidentifier%% RDS 인스턴스 식별자
%%extra_dbm%% dbm_tag 값을 기반으로 DBM이 활성화되었는지 여부

더 알아보기 (Learn more)