New Relic AWS統合設定とCloudWatch連携
はじめに
AWS環境でのインフラ監視は、EC2インスタンス上のInfrastructure Agentと、AWSサービスの統合監視を組み合わせることで、包括的な可視性を実現できます。New RelicのAWS統合により、CloudWatch、RDS、Lambda、ELBなどのAWSサービスの詳細メトリクスを統一されたダッシュボードで監視できます。
本記事では、Infrastructure AgentのAWS環境での設定から、AWS統合の有効化、CloudWatchとの連携まで、実践的な設定手順を詳しく解説します。また、IAMロールの適切な設定とセキュリティ考慮事項についても併せて説明します。
AWS統合監視の基本概念
Infrastructure AgentとAWS統合の関係
Infrastructure AgentはEC2インスタンス、コンテナ、オンプレミスサーバーのホストレベル監視を担当し、AWS統合はAWSマネージドサービスの監視を担当します。この2つを組み合わせることで、アプリケーションスタック全体の監視が可能になります。
監視対象の範囲
AWS環境でのNew Relic監視では、以下の情報を収集できます。
Infrastructure Agentによる監視
- EC2インスタンスのシステムメトリクス
- アプリケーションプロセスの詳細情報
- カスタムメトリクスとログ
AWS統合による監視
- CloudWatchメトリクス
- AWS X-Rayトレース情報
- CloudTrail監査ログ
- RDS、Lambda、ELB等のサービスメトリクス
EC2でのInfrastructure Agent設定
IAMロールの作成
EC2インスタンスでInfrastructure Agentを実行するためのIAMロールを作成します。
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"ec2:DescribeInstances",
"ec2:DescribeTags",
"ec2:DescribeVolumes",
"cloudwatch:GetMetricStatistics",
"cloudwatch:ListMetrics",
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents"
],
"Resource": "*"
}
]
}
User Dataを使用した自動インストール
EC2起動時にInfrastructure Agentを自動インストールするUser Dataスクリプトです。
#!/bin/bash
# EC2 User Data script for New Relic Infrastructure Agent
# セキュリティベストプラクティス: AWS Secrets Managerからライセンスキーを取得
# 事前にAWS Secrets Managerまたはパラメータストアにライセンスキーを保存してください
# AWS Secrets Managerから取得する場合
NEW_RELIC_LICENSE_KEY=$(aws secretsmanager get-secret-value \
--secret-id "newrelic/license-key" \
--query SecretString --output text)
# AWS Systems Manager Parameter Storeから取得する場合(別の方法)
# NEW_RELIC_LICENSE_KEY=$(aws ssm get-parameter \
# --name "/newrelic/license-key" --with-decryption \
# --query Parameter.Value --output text)
if [ -z "$NEW_RELIC_LICENSE_KEY" ]; then
echo "ERROR: New Relic ライセンスキーを取得できませんでした"
exit 1
fi
INSTANCE_NAME=$(curl -s http://169.254.169.254/latest/meta-data/instance-id)
AVAILABILITY_ZONE=$(curl -s http://169.254.169.254/latest/meta-data/placement/availability-zone)
INSTANCE_TYPE=$(curl -s http://169.254.169.254/latest/meta-data/instance-type)
# システム更新
yum update -y
# New Relic Infrastructure Agent インストール
curl -o /etc/yum.repos.d/newrelic-infra.repo https://download.newrelic.com/infrastructure_agent/linux/yum/el/7/x86_64/newrelic-infra.repo
yum -q makecache -y --disablerepo='*' --enablerepo='newrelic-infra'
yum install newrelic-infra -y
# 設定ファイル作成
cat > /etc/newrelic-infra.yml << EOF
license_key: ${NEW_RELIC_LICENSE_KEY}
display_name: ${INSTANCE_NAME}
verbose: 1
# AWS固有設定
custom_attributes:
environment: production
aws_region: ${AVAILABILITY_ZONE%?}
availability_zone: ${AVAILABILITY_ZONE}
instance_type: ${INSTANCE_TYPE}
deployment_method: user_data
# CloudWatch統合設定
enable_cloudwatch: true
cloudwatch_region: ${AVAILABILITY_ZONE%?}
# ログ設定
log_level: info
log_file: /var/log/newrelic-infra/newrelic-infra.log
EOF
# サービス開始
systemctl enable newrelic-infra
systemctl start newrelic-infra
# CloudWatch Logsエージェントのインストール(オプション)
yum install -y awslogs
cat > /etc/awslogs/awslogs.conf << EOF
[general]
state_file = /var/lib/awslogs/agent-state
[/var/log/newrelic-infra/newrelic-infra.log]
datetime_format = %Y-%m-%d %H:%M:%S
file = /var/log/newrelic-infra/newrelic-infra.log
buffer_duration = 5000
log_stream_name = {instance_id}/newrelic-infra.log
initial_position = start_of_file
log_group_name = /aws/ec2/newrelic
EOF
systemctl enable awslogsd
systemctl start awslogsd
CloudFormationテンプレート
Infrastructure Agentを含むEC2インスタンスをCloudFormationで展開する例です。
# newrelic-ec2-template.yaml
AWSTemplateFormatVersion: '2010-09-09'
Description: 'EC2 instance with New Relic Infrastructure Agent'
Parameters:
NewRelicLicenseKey:
Type: String
Description: 'New Relic License Key'
NoEcho: true
InstanceType:
Type: String
Default: 't3.medium'
AllowedValues: ['t3.micro', 't3.small', 't3.medium', 't3.large']
KeyPairName:
Type: AWS::EC2::KeyPair::KeyName
Description: 'EC2 Key Pair for SSH access'
Resources:
NewRelicInstanceRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service: ec2.amazonaws.com
Action: sts:AssumeRole
ManagedPolicyArns:
- arn:aws:iam::aws:policy/CloudWatchAgentServerPolicy
Policies:
- PolicyName: NewRelicPolicy
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- 'ec2:DescribeInstances'
- 'ec2:DescribeTags'
- 'cloudwatch:GetMetricStatistics'
- 'cloudwatch:ListMetrics'
Resource: '*'
NewRelicInstanceProfile:
Type: AWS::IAM::InstanceProfile
Properties:
Roles:
- !Ref NewRelicInstanceRole
NewRelicSecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: 'Security group for New Relic monitored instances'
SecurityGroupIngress:
- IpProtocol: tcp
FromPort: 22
ToPort: 22
CidrIp: 0.0.0.0/0
- IpProtocol: tcp
FromPort: 80
ToPort: 80
CidrIp: 0.0.0.0/0
- IpProtocol: tcp
FromPort: 443
ToPort: 443
CidrIp: 0.0.0.0/0
NewRelicInstance:
Type: AWS::EC2::Instance
Properties:
ImageId: ami-0abcdef1234567890 # Amazon Linux 2 AMI
InstanceType: !Ref InstanceType
KeyName: !Ref KeyPairName
IamInstanceProfile: !Ref NewRelicInstanceProfile
SecurityGroupIds:
- !Ref NewRelicSecurityGroup
UserData:
Fn::Base64: !Sub |
#!/bin/bash
yum update -y
# New Relic Infrastructure Agent install
curl -o /etc/yum.repos.d/newrelic-infra.repo https://download.newrelic.com/infrastructure_agent/linux/yum/el/7/x86_64/newrelic-infra.repo
yum -q makecache -y --disablerepo='*' --enablerepo='newrelic-infra'
yum install newrelic-infra -y
# Configuration
cat > /etc/newrelic-infra.yml << EOF
license_key: ${NewRelicLicenseKey}
display_name: ${AWS::StackName}-instance
custom_attributes:
environment: production
stack_name: ${AWS::StackName}
aws_region: ${AWS::Region}
EOF
systemctl enable newrelic-infra
systemctl start newrelic-infra
Tags:
- Key: Name
Value: !Sub '${AWS::StackName}-newrelic-instance'
- Key: Environment
Value: 'production'
- Key: Monitoring
Value: 'newrelic'
Outputs:
InstanceId:
Description: 'Instance ID'
Value: !Ref NewRelicInstance
PublicIp:
Description: 'Public IP address'
Value: !GetAtt NewRelicInstance.PublicIp
AWS統合の設定
New RelicでのAWS統合有効化
New Relicダッシュボードでの設定手順です。
- AWS統合の開始
# AWS CLIでIAMロールを作成
aws iam create-role --role-name NewRelicInfrastructure-Integrations \
--assume-role-policy-document '{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"AWS": "arn:aws:iam::754728514883:root"
},
"Action": "sts:AssumeRole",
"Condition": {
"StringEquals": {
"sts:ExternalId": "YOUR_EXTERNAL_ID"
}
}
}
]
}'
# ポリシーをアタッチ
aws iam attach-role-policy \
--role-name NewRelicInfrastructure-Integrations \
--policy-arn arn:aws:iam::aws:policy/ReadOnlyAccess
- カスタムポリシーの追加
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"cloudwatch:GetMetricStatistics",
"cloudwatch:ListMetrics",
"cloudwatch:GetMetricData",
"ec2:DescribeInstances",
"ec2:DescribeVolumes",
"ec2:DescribeSnapshots",
"rds:DescribeDBInstances",
"rds:DescribeDBClusters",
"elasticloadbalancing:DescribeLoadBalancers",
"elasticloadbalancing:DescribeTargetGroups",
"lambda:ListFunctions",
"lambda:GetFunction",
"s3:ListAllMyBuckets",
"s3:GetBucketLocation",
"s3:GetBucketNotification"
],
"Resource": "*"
}
]
}
Terraformを使用したAWS統合設定
Terraformを使用してAWS統合を自動化する例です。
# main.tf
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
newrelic = {
source = "newrelic/newrelic"
version = "~> 3.0"
}
}
}
# New Relic provider設定
provider "newrelic" {
account_id = var.newrelic_account_id
api_key = var.newrelic_api_key
region = "US" # または "EU"
}
# AWS統合用IAMロール
resource "aws_iam_role" "newrelic_aws_integration" {
name = "NewRelicInfrastructure-Integrations"
assume_role_policy = jsonencode({
Version = "2012-10-17"
Statement = [
{
Action = "sts:AssumeRole"
Effect = "Allow"
Principal = {
AWS = "arn:aws:iam::754728514883:root"
}
Condition = {
StringEquals = {
"sts:ExternalId" = var.newrelic_external_id
}
}
}
]
})
tags = {
Name = "NewRelic AWS Integration Role"
Environment = "production"
}
}
# ReadOnlyAccess ポリシーのアタッチ
resource "aws_iam_role_policy_attachment" "readonly_access" {
role = aws_iam_role.newrelic_aws_integration.name
policy_arn = "arn:aws:iam::aws:policy/ReadOnlyAccess"
}
# New Relic AWS統合の設定
resource "newrelic_cloud_aws_link_account" "aws" {
arn = aws_iam_role.newrelic_aws_integration.arn
metric_collection_mode = "PULL"
name = "AWS Production Account"
}
# 個別サービスの統合有効化
resource "newrelic_cloud_aws_integrations" "aws_integrations" {
linked_account_id = newrelic_cloud_aws_link_account.aws.id
ec2 {
metrics_polling_interval = 300
fetch_tags = true
}
rds {
metrics_polling_interval = 300
fetch_tags = true
}
elb {
metrics_polling_interval = 300
fetch_tags = true
}
lambda {
metrics_polling_interval = 300
fetch_tags = true
}
cloudwatch_logs {
metrics_polling_interval = 300
}
}
# 変数定義
variable "newrelic_account_id" {
description = "New Relic Account ID"
type = string
}
variable "newrelic_api_key" {
description = "New Relic API Key"
type = string
sensitive = true
}
variable "newrelic_external_id" {
description = "New Relic External ID for AWS integration"
type = string
}
CloudWatchとの高度な連携
CloudWatch Logsの統合
CloudWatch LogsをNew Relicに転送する設定です。
# cloudwatch-logs-lambda.yaml
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Parameters:
NewRelicLicenseKey:
Type: String
NoEcho: true
Resources:
NewRelicLogForwarder:
Type: AWS::Serverless::Function
Properties:
CodeUri: newrelic-log-ingestion
Handler: lambda_function.lambda_handler
Runtime: python3.9
Environment:
Variables:
LICENSE_KEY: !Ref NewRelicLicenseKey
LOGGING_ENABLED: 'True'
Events:
CloudWatchLogsEvent:
Type: CloudWatchLogs
Properties:
LogGroupName: /aws/lambda/my-function
FilterPattern: ""
Policies:
- CloudWatchLogsReadOnlyAccess
X-Ray統合設定
AWS X-RayトレースをNew Relicに統合する設定です。
# lambda_function.py - X-Ray統合用Lambda関数
import json
import boto3
import requests
import os
from aws_xray_sdk.core import xray_recorder
@xray_recorder.capture('lambda_handler')
def lambda_handler(event, context):
"""
X-RayトレースをNew Relicに転送する関数
"""
# New Relic設定
newrelic_endpoint = 'https://trace-api.newrelic.com/trace/v1'
license_key = os.environ['NEW_RELIC_LICENSE_KEY']
# X-Rayクライアント
xray_client = boto3.client('xray')
try:
# X-Rayトレース取得
response = xray_client.get_trace_summaries(
TimeRangeType='TraceId',
TraceIds=event.get('trace_ids', [])
)
# New Relicに送信するデータ形式に変換
traces = []
for trace in response['TraceSummaries']:
trace_data = {
'id': trace['Id'],
'timestamp': int(trace['ResponseTime']),
'duration': trace['Duration'],
'name': trace.get('RootServiceName', 'unknown'),
'attributes': {
'aws.xray.trace_id': trace['Id'],
'aws.region': context.invoked_function_arn.split(':')[3]
}
}
traces.append(trace_data)
# New Relicに送信
headers = {
'Content-Type': 'application/json',
'Api-Key': license_key
}
payload = {
'common': {
'attributes': {
'service.name': 'aws-xray-integration'
}
},
'spans': traces
}
response = requests.post(
newrelic_endpoint,
headers=headers,
json=payload
)
return {
'statusCode': 200,
'body': json.dumps(f'Processed {len(traces)} traces')
}
except Exception as e:
print(f'Error processing traces: {str(e)}')
return {
'statusCode': 500,
'body': json.dumps(f'Error: {str(e)}')
}
運用とベストプラクティス
タグベースの監視設定
AWSリソースのタグを活用した効率的な監視設定です。
# AWS リソースタグ設定例
Resources:
ProductionInstance:
Type: AWS::EC2::Instance
Properties:
# ... その他の設定 ...
Tags:
- Key: Environment
Value: production
- Key: Application
Value: web-app
- Key: Team
Value: backend
- Key: NewRelic-Monitor
Value: enabled
- Key: AlertPolicy
Value: critical
Infrastructure Agentでこれらのタグを活用する設定です。
# /etc/newrelic-infra.yml
license_key: YOUR_LICENSE_KEY
display_name: production-web-01
# EC2タグの自動取得と属性化
enable_ec2_tags: true
ec2_tags_include:
- Environment
- Application
- Team
- AlertPolicy
# 条件付きカスタム属性
custom_attributes:
monitoring_tier: premium
backup_enabled: true
コスト最適化設定
AWS統合のコストを最適化するための設定です。
# コスト最適化設定
config:
# メトリクス収集間隔の調整
aws_polling_interval: 600 # 10分間隔(デフォルト: 5分)
# 不要なサービスの無効化
aws_services:
ec2: true
rds: true
elb: true
lambda: false # 使用しない場合は無効化
cloudfront: false # 使用しない場合は無効化
# リージョン限定
aws_regions:
- us-east-1
- ap-northeast-1
# タグフィルタリング
aws_tag_filters:
include:
Environment:
- production
- staging
exclude:
Temporary: "true"
セキュリティ考慮事項
IAMロールの最小権限設定
セキュリティ強化のための最小権限IAMポリシーです。
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"cloudwatch:GetMetricStatistics",
"cloudwatch:ListMetrics",
"ec2:DescribeInstances",
"ec2:DescribeTags"
],
"Resource": "*",
"Condition": {
"StringEquals": {
"aws:RequestedRegion": ["us-east-1", "ap-northeast-1"]
}
}
},
{
"Effect": "Allow",
"Action": [
"rds:DescribeDBInstances"
],
"Resource": "*",
"Condition": {
"StringLike": {
"aws:RequestTag/Environment": ["production", "staging"]
}
}
}
]
}
VPCエンドポイント設定
プライベートサブネットからの安全な通信のためのVPCエンドポイント設定です。
# VPCエンドポイント設定
NewRelicVPCEndpoint:
Type: AWS::EC2::VPCEndpoint
Properties:
VpcId: !Ref VPC
ServiceName: com.amazonaws.vpce.us-east-1.newrelic
VpcEndpointType: Interface
SubnetIds:
- !Ref PrivateSubnet1
- !Ref PrivateSubnet2
SecurityGroupIds:
- !Ref NewRelicEndpointSecurityGroup
PrivateDnsEnabled: true
まとめ
AWS環境でのNew Relic Infrastructure Agent導入とAWS統合設定により、ホストレベルからクラウドサービスレベルまでの包括的な監視が実現できます。適切なIAM設定とタグベースの管理により、セキュリティを保ちながら効率的な運用が可能になります。
CloudWatchとX-Rayとの統合により、AWSネイティブサービスとNew Relicの強力な分析機能を組み合わせた高度な監視環境を構築できるでしょう。次回は、Azure統合設定について詳しく解説します。
関連記事: Kubernetes環境での導入関連記事: Azure統合設定