New Relic GCP統合設定とCloud Operations連携

はじめに

Google Cloud Platform(GCP)環境でのインフラ監視は、Compute Engine上のInfrastructure Agentと、GCPサービスの統合監視を組み合わせることで、包括的な可視性を実現できます。New RelicのGCP統合により、Cloud Monitoring、Cloud SQL、Cloud Functions、GKEなどのGCPサービスの詳細メトリクスを統一されたダッシュボードで監視できます。

本記事では、Infrastructure AgentのGCP環境での設定から、GCP統合の有効化、Cloud Operationsとの連携まで、実践的な設定手順を詳しく解説します。また、サービスアカウントの適切な設定とセキュリティ考慮事項についても併せて説明します。

GCP統合監視の基本概念

Infrastructure AgentとGCP統合の関係

Infrastructure AgentはCompute Engine、Container Instances、オンプレミスサーバーのホストレベル監視を担当し、GCP統合はGCPマネージドサービスの監視を担当します。この2つを組み合わせることで、アプリケーションスタック全体の監視が可能になります。

監視対象の範囲

GCP環境でのNew Relic監視では、以下の情報を収集できます。

Infrastructure Agentによる監視

  • Compute Engineインスタンスのシステムメトリクス
  • アプリケーションプロセスの詳細情報
  • カスタムメトリクスとログ

GCP統合による監視

  • Cloud Monitoringメトリクス
  • Cloud Traceトレース情報
  • Cloud Loggingデータ
  • Cloud SQL、Cloud Functions、GKE等のサービスメトリクス

Compute EngineでのInfrastructure Agent設定

サービスアカウントの作成

GCP統合に必要なサービスアカウントをgcloudコマンドで作成します。

bash
# gcloud CLIでログイン
gcloud auth login

# プロジェクト設定
export PROJECT_ID="your-project-id"
gcloud config set project $PROJECT_ID

# New Relic用サービスアカウントの作成
gcloud iam service-accounts create newrelic-integration \
  --display-name="New Relic Integration" \
  --description="Service account for New Relic GCP integration"

# 必要なロールの付与
gcloud projects add-iam-policy-binding $PROJECT_ID \
  --member="serviceAccount:newrelic-integration@${PROJECT_ID}.iam.gserviceaccount.com" \
  --role="roles/compute.viewer"

gcloud projects add-iam-policy-binding $PROJECT_ID \
  --member="serviceAccount:newrelic-integration@${PROJECT_ID}.iam.gserviceaccount.com" \
  --role="roles/monitoring.viewer"

gcloud projects add-iam-policy-binding $PROJECT_ID \
  --member="serviceAccount:newrelic-integration@${PROJECT_ID}.iam.gserviceaccount.com" \
  --role="roles/cloudsql.client"

# サービスアカウントキーの作成
gcloud iam service-accounts keys create newrelic-key.json \
  --iam-account=newrelic-integration@${PROJECT_ID}.iam.gserviceaccount.com

Startup Script を使用した自動インストール

Compute Engine起動時にInfrastructure Agentを自動インストールするStartup Scriptです。

bash
#!/bin/bash
# startup-script.sh - GCP Compute Engine用インストールスクリプト

NEW_RELIC_LICENSE_KEY="$1"

if [ -z "$NEW_RELIC_LICENSE_KEY" ]; then
    echo "Usage: startup script requires NEW_RELIC_LICENSE_KEY"
    exit 1
fi

# GCP メタデータ取得
METADATA_URL="http://metadata.google.internal/computeMetadata/v1"
HEADERS="Metadata-Flavor: Google"

INSTANCE_NAME=$(curl -s -H "$HEADERS" "$METADATA_URL/instance/name")
ZONE=$(curl -s -H "$HEADERS" "$METADATA_URL/instance/zone" | cut -d'/' -f4)
PROJECT_ID=$(curl -s -H "$HEADERS" "$METADATA_URL/project/project-id")
MACHINE_TYPE=$(curl -s -H "$HEADERS" "$METADATA_URL/instance/machine-type" | cut -d'/' -f4)
INSTANCE_ID=$(curl -s -H "$HEADERS" "$METADATA_URL/instance/id")

# OS判定とパッケージ管理
if [ -f /etc/redhat-release ]; then
    # RHEL/CentOS
    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
elif [ -f /etc/debian_version ]; then
    # Ubuntu/Debian
    curl -fsSL https://download.newrelic.com/infrastructure_agent/gpg/newrelic-infra.gpg | apt-key add -
    echo "deb https://download.newrelic.com/infrastructure_agent/linux/apt $(lsb_release -cs) main" | \
         tee /etc/apt/sources.list.d/newrelic-infra.list
    apt-get update
    apt-get install newrelic-infra -y
fi

# 設定ファイル作成
cat > /etc/newrelic-infra.yml << EOF
license_key: ${NEW_RELIC_LICENSE_KEY}
display_name: ${INSTANCE_NAME}
verbose: 1

# GCP固有設定
custom_attributes:
  environment: production
  gcp_project_id: ${PROJECT_ID}
  gcp_zone: ${ZONE}
  gcp_machine_type: ${MACHINE_TYPE}
  gcp_instance_id: ${INSTANCE_ID}
  deployment_method: startup_script

# Google Cloud Monitoring統合設定
enable_gcp_monitoring: true
gcp_region: ${ZONE%-*}

# ログ設定
log_level: info
log_file: /var/log/newrelic-infra/newrelic-infra.log
EOF

# サービス開始
systemctl enable newrelic-infra
systemctl start newrelic-infra

# Google Cloud Logging エージェントのインストール(オプション)
curl -sSO https://dl.google.com/cloudagents/add-logging-agent-repo.sh
bash add-logging-agent-repo.sh --also-install

# Logging エージェント設定
cat > /etc/google-fluentd/config.d/newrelic.conf << EOF
<source>
  @type tail
  path /var/log/newrelic-infra/newrelic-infra.log
  pos_file /var/lib/google-fluentd/pos/newrelic-infra.log.pos
  tag newrelic.infrastructure
  format json
</source>

<filter newrelic.infrastructure>
  @type record_transformer
  <record>
    project_id ${PROJECT_ID}
    instance_name ${INSTANCE_NAME}
    zone ${ZONE}
  </record>
</filter>
EOF

systemctl restart google-fluentd

echo "New Relic Infrastructure Agent installation completed"

Deployment Manager テンプレート

Infrastructure Agentを含むCompute EngineをDeployment Managerで展開する例です。

yaml
# newrelic-vm-template.yaml
imports:
- path: vm-template.py

resources:
- name: newrelic-vm
  type: vm-template.py
  properties:
    zone: us-central1-a
    machineType: n1-standard-2
    sourceImage: projects/ubuntu-os-cloud/global/images/family/ubuntu-2004-lts
    newRelicLicenseKey: YOUR_LICENSE_KEY
    network: default
    tags:
      - newrelic-monitored
      - http-server
      - https-server
python
# vm-template.py
def GenerateConfig(context):
    resources = []
    
    # Startup script with New Relic agent installation
    startup_script = '''#!/bin/bash
    
# Variables
NEW_RELIC_LICENSE_KEY="{license_key}"
PROJECT_ID=$(curl -s -H "Metadata-Flavor: Google" "http://metadata.google.internal/computeMetadata/v1/project/project-id")
INSTANCE_NAME=$(curl -s -H "Metadata-Flavor: Google" "http://metadata.google.internal/computeMetadata/v1/instance/name")
ZONE=$(curl -s -H "Metadata-Flavor: Google" "http://metadata.google.internal/computeMetadata/v1/instance/zone" | cut -d'/' -f4)

# Install New Relic Infrastructure Agent
curl -fsSL https://download.newrelic.com/infrastructure_agent/gpg/newrelic-infra.gpg | apt-key add -
echo "deb https://download.newrelic.com/infrastructure_agent/linux/apt focal main" | tee /etc/apt/sources.list.d/newrelic-infra.list
apt-get update
apt-get install newrelic-infra -y

# Configuration
cat > /etc/newrelic-infra.yml << EOF
license_key: $NEW_RELIC_LICENSE_KEY
display_name: $INSTANCE_NAME
custom_attributes:
  gcp_project_id: $PROJECT_ID
  gcp_zone: $ZONE
  environment: production
  deployment_method: deployment_manager
EOF

systemctl enable newrelic-infra
systemctl start newrelic-infra
'''.format(license_key=context.properties['newRelicLicenseKey'])
    
    # VM instance configuration
    vm_instance = {
        'name': context.env['name'],
        'type': 'compute.v1.instance',
        'properties': {
            'zone': context.properties['zone'],
            'machineType': 'zones/{}/machineTypes/{}'.format(
                context.properties['zone'],
                context.properties['machineType']
            ),
            'disks': [{
                'deviceName': 'boot',
                'type': 'PERSISTENT',
                'boot': True,
                'autoDelete': True,
                'initializeParams': {
                    'diskName': context.env['name'] + '-disk',
                    'sourceImage': context.properties['sourceImage'],
                    'diskSizeGb': '20'
                }
            }],
            'networkInterfaces': [{
                'network': 'global/networks/{}'.format(context.properties['network']),
                'accessConfigs': [{
                    'name': 'External NAT',
                    'type': 'ONE_TO_ONE_NAT'
                }]
            }],
            'metadata': {
                'items': [{
                    'key': 'startup-script',
                    'value': startup_script
                }]
            },
            'tags': {
                'items': context.properties.get('tags', [])
            },
            'serviceAccounts': [{
                'email': 'default',
                'scopes': [
                    'https://www.googleapis.com/auth/compute.readonly',
                    'https://www.googleapis.com/auth/monitoring.read',
                    'https://www.googleapis.com/auth/logging.write'
                ]
            }]
        }
    }
    
    resources.append(vm_instance)
    
    # Firewall rule for New Relic monitoring
    firewall_rule = {
        'name': context.env['name'] + '-firewall',
        'type': 'compute.v1.firewall',
        'properties': {
            'direction': 'EGRESS',
            'priority': 1000,
            'targetTags': ['newrelic-monitored'],
            'allowed': [{
                'IPProtocol': 'tcp',
                'ports': ['443']
            }],
            'destinationRanges': ['0.0.0.0/0']
        }
    }
    
    resources.append(firewall_rule)
    
    return {'resources': resources}

GCP統合の設定

New RelicでのGCP統合有効化

GCP統合に必要なサービスアカウント認証情報をNew Relicに設定します。

bash
# サービスアカウントキーの内容を確認
cat newrelic-key.json | jq '.'

# 必要な情報:
# - type
# - project_id  
# - private_key_id
# - private_key
# - client_email
# - client_id
# - auth_uri
# - token_uri

gcloud を使用したプロジェクト設定

GCP統合用のプロジェクト設定を自動化するスクリプトです。

bash
#!/bin/bash
# setup-newrelic-gcp-integration.sh

set -e

PROJECT_ID="$1"
NEW_RELIC_ACCOUNT_ID="$2"

if [ -z "$PROJECT_ID" ] || [ -z "$NEW_RELIC_ACCOUNT_ID" ]; then
    echo "Usage: $0 <PROJECT_ID> <NEW_RELIC_ACCOUNT_ID>"
    exit 1
fi

echo "Setting up New Relic GCP integration for project: $PROJECT_ID"

# プロジェクト設定
gcloud config set project $PROJECT_ID

# 必要なAPIの有効化
echo "Enabling required APIs..."
gcloud services enable compute.googleapis.com
gcloud services enable monitoring.googleapis.com
gcloud services enable logging.googleapis.com
gcloud services enable cloudsql.googleapis.com
gcloud services enable container.googleapis.com
gcloud services enable pubsub.googleapis.com
gcloud services enable storage-component.googleapis.com

# サービスアカウント作成
echo "Creating service account..."
gcloud iam service-accounts create newrelic-integration \
  --display-name="New Relic Integration Service Account" \
  --description="Service account for New Relic GCP monitoring integration"

SERVICE_ACCOUNT_EMAIL="newrelic-integration@${PROJECT_ID}.iam.gserviceaccount.com"

# 必要なロールを付与
echo "Assigning roles..."
ROLES=(
    "roles/compute.viewer"
    "roles/monitoring.viewer"
    "roles/cloudsql.viewer"
    "roles/storage.objectViewer"
    "roles/pubsub.viewer"
    "roles/container.viewer"
    "roles/logging.viewer"
)

for ROLE in "${ROLES[@]}"; do
    gcloud projects add-iam-policy-binding $PROJECT_ID \
        --member="serviceAccount:${SERVICE_ACCOUNT_EMAIL}" \
        --role="$ROLE"
    echo "Assigned role: $ROLE"
done

# サービスアカウントキーの作成
echo "Creating service account key..."
gcloud iam service-accounts keys create "newrelic-${PROJECT_ID}-key.json" \
    --iam-account="$SERVICE_ACCOUNT_EMAIL"

echo "Service account key created: newrelic-${PROJECT_ID}-key.json"
echo ""
echo "Next steps:"
echo "1. Upload the service account key to New Relic"
echo "2. Configure GCP integration in New Relic dashboard"
echo "3. Select the services you want to monitor"

# サービスアカウントキー情報の表示
echo ""
echo "Service Account Information:"
echo "Project ID: $PROJECT_ID"
echo "Service Account Email: $SERVICE_ACCOUNT_EMAIL"
echo "Key File: newrelic-${PROJECT_ID}-key.json"

Terraform を使用したGCP統合設定

TerraformでGCP統合を自動化する設定例です。

hcl
# main.tf
terraform {
  required_providers {
    google = {
      source  = "hashicorp/google"
      version = "~> 4.0"
    }
    newrelic = {
      source  = "newrelic/newrelic"
      version = "~> 3.0"
    }
  }
}

# Google Provider設定
provider "google" {
  project = var.gcp_project_id
  region  = var.gcp_region
}

# New Relic Provider設定
provider "newrelic" {
  account_id = var.newrelic_account_id
  api_key    = var.newrelic_api_key
  region     = "US"
}

# 必要なAPIの有効化
resource "google_project_service" "required_apis" {
  for_each = toset([
    "compute.googleapis.com",
    "monitoring.googleapis.com",
    "logging.googleapis.com",
    "cloudsql.googleapis.com",
    "container.googleapis.com",
    "pubsub.googleapis.com",
    "storage.googleapis.com"
  ])
  
  project = var.gcp_project_id
  service = each.value
  
  disable_on_destroy = false
}

# New Relic統合用サービスアカウント
resource "google_service_account" "newrelic_integration" {
  account_id   = "newrelic-integration"
  display_name = "New Relic Integration Service Account"
  description  = "Service account for New Relic GCP monitoring integration"
  project      = var.gcp_project_id
}

# サービスアカウントキー
resource "google_service_account_key" "newrelic_key" {
  service_account_id = google_service_account.newrelic_integration.name
  public_key_type    = "TYPE_X509_PEM_FILE"
}

# IAMロールの付与
resource "google_project_iam_member" "newrelic_roles" {
  for_each = toset([
    "roles/compute.viewer",
    "roles/monitoring.viewer",
    "roles/cloudsql.viewer",
    "roles/storage.objectViewer",
    "roles/pubsub.viewer",
    "roles/container.viewer",
    "roles/logging.viewer"
  ])
  
  project = var.gcp_project_id
  role    = each.value
  member  = "serviceAccount:${google_service_account.newrelic_integration.email}"
}

# New Relic GCP統合
resource "newrelic_cloud_gcp_link_account" "gcp" {
  account_id = var.newrelic_account_id
  project_id = var.gcp_project_id
  name       = "GCP Production Account"
  
  depends_on = [
    google_project_service.required_apis,
    google_project_iam_member.newrelic_roles
  ]
}

# GCPサービス統合の有効化
resource "newrelic_cloud_gcp_integrations" "gcp_integrations" {
  account_id        = var.newrelic_account_id
  linked_account_id = newrelic_cloud_gcp_link_account.gcp.id

  # App Engine
  app_engine {
    metrics_polling_interval = 300
  }

  # Big Query
  big_query {
    metrics_polling_interval = 300
    fetch_tags              = true
  }

  # Cloud Functions
  cloud_functions {
    metrics_polling_interval = 300
  }

  # Cloud Load Balancing
  cloud_load_balancing {
    metrics_polling_interval = 300
  }

  # Cloud SQL
  cloud_sql {
    metrics_polling_interval = 300
  }

  # Cloud Storage
  cloud_storage {
    metrics_polling_interval = 300
    fetch_tags              = true
  }

  # Compute Engine
  compute {
    metrics_polling_interval = 300
    fetch_tags              = true
  }

  # Google Kubernetes Engine
  gke {
    metrics_polling_interval = 300
    fetch_tags              = true
  }

  # Pub/Sub
  pubsub {
    metrics_polling_interval = 300
    fetch_tags              = true
  }
}

# 変数定義
variable "gcp_project_id" {
  description = "GCP Project ID"
  type        = string
}

variable "gcp_region" {
  description = "GCP Region"
  type        = string
  default     = "us-central1"
}

variable "newrelic_account_id" {
  description = "New Relic Account ID"
  type        = string
}

variable "newrelic_api_key" {
  description = "New Relic API Key"
  type        = string
  sensitive   = true
}

# 出力
output "service_account_email" {
  description = "New Relic integration service account email"
  value       = google_service_account.newrelic_integration.email
}

output "service_account_key" {
  description = "Service account private key (base64 encoded)"
  value       = google_service_account_key.newrelic_key.private_key
  sensitive   = true
}

Cloud Operations との高度な連携

Cloud Logging 統合

Cloud LogsをNew Relicに転送するCloud Functionの設定です。

javascript
// Cloud Function - Cloud Logging to New Relic forwarder
const { PubSub } = require('@google-cloud/pubsub');
const axios = require('axios');

const pubsub = new PubSub();
const newRelicEndpoint = 'https://log-api.newrelic.com/log/v1';
const licenseKey = process.env.NEW_RELIC_LICENSE_KEY;

exports.forwardLogsToNewRelic = async (message, context) => {
  if (!licenseKey) {
    console.error('NEW_RELIC_LICENSE_KEY environment variable not set');
    return;
  }

  try {
    // Pub/Sub メッセージからログデータを取得
    const logData = JSON.parse(Buffer.from(message.data, 'base64').toString());
    
    // New Relic形式に変換
    const transformedLogs = {
      timestamp: new Date(logData.timestamp).getTime(),
      message: logData.textPayload || logData.jsonPayload?.message || '',
      attributes: {
        'gcp.project_id': logData.resource?.labels?.project_id,
        'gcp.resource_type': logData.resource?.type,
        'gcp.log_name': logData.logName,
        'gcp.severity': logData.severity,
        'gcp.insert_id': logData.insertId,
        'gcp.trace': logData.trace,
        'gcp.span_id': logData.spanId,
        'gcp.operation_id': logData.operation?.id,
        'gcp.operation_producer': logData.operation?.producer,
        // Cloud Run specific
        'gcp.service_name': logData.resource?.labels?.service_name,
        'gcp.revision_name': logData.resource?.labels?.revision_name,
        'gcp.configuration_name': logData.resource?.labels?.configuration_name,
        // GKE specific  
        'gcp.cluster_name': logData.resource?.labels?.cluster_name,
        'gcp.namespace_name': logData.resource?.labels?.namespace_name,
        'gcp.pod_name': logData.resource?.labels?.pod_name,
        'gcp.container_name': logData.resource?.labels?.container_name
      }
    };

    // JSONペイロードの処理
    if (logData.jsonPayload) {
      Object.keys(logData.jsonPayload).forEach(key => {
        if (key !== 'message') {
          transformedLogs.attributes[`json.${key}`] = logData.jsonPayload[key];
        }
      });
    }

    // ラベルの処理
    if (logData.labels) {
      Object.keys(logData.labels).forEach(key => {
        transformedLogs.attributes[`label.${key}`] = logData.labels[key];
      });
    }

    // New Relic にログを送信
    const headers = {
      'Content-Type': 'application/json',
      'X-License-Key': licenseKey
    };

    const response = await axios.post(
      newRelicEndpoint,
      { logs: [transformedLogs] },
      { headers }
    );

    console.log('Successfully forwarded log to New Relic');
    
  } catch (error) {
    console.error('Error processing log:', error);
    throw error;
  }
};

Cloud Trace 統合

Cloud TraceからNew Relicへのトレース転送設定です。

python
# Cloud Function - Cloud Trace to New Relic forwarder
import json
import os
import requests
from google.cloud import trace_v1
from datetime import datetime, timedelta

def forward_traces_to_newrelic(request):
    """
    Cloud TraceからNew Relicにトレースを転送する関数
    """
    
    # New Relic設定
    newrelic_endpoint = 'https://trace-api.newrelic.com/trace/v1'
    license_key = os.environ.get('NEW_RELIC_LICENSE_KEY')
    
    if not license_key:
        return {'error': 'NEW_RELIC_LICENSE_KEY not set'}, 400
    
    try:
        # Cloud Trace クライアント
        client = trace_v1.TraceServiceClient()
        project_id = os.environ.get('GCP_PROJECT', os.environ.get('GOOGLE_CLOUD_PROJECT'))
        
        # 過去5分間のトレースを取得
        end_time = datetime.utcnow()
        start_time = end_time - timedelta(minutes=5)
        
        # トレース取得のリクエスト
        request_body = {
            "project_id": project_id,
            "view": trace_v1.ListTracesRequest.ViewType.COMPLETE,
            "page_size": 100,
            "start_time": start_time,
            "end_time": end_time
        }
        
        # トレース一覧を取得
        traces = client.list_traces(request=request_body)
        
        # New Relicに送信するデータ形式に変換
        spans = []
        for trace in traces:
            for span in trace.spans:
                span_data = {
                    'id': span.span_id,
                    'trace.id': trace.trace_id,
                    'timestamp': int(span.start_time.timestamp() * 1000),
                    'duration': int((span.end_time.timestamp() - span.start_time.timestamp()) * 1000),
                    'name': span.display_name.value,
                    'attributes': {
                        'gcp.project_id': project_id,
                        'gcp.trace_id': trace.trace_id,
                        'gcp.span_id': span.span_id,
                        'gcp.parent_span_id': span.parent_span_id,
                        'gcp.span_kind': str(span.kind),
                        'service.name': 'gcp-trace-integration'
                    }
                }
                
                # ラベルの追加
                for key, value in span.labels.items():
                    span_data['attributes'][f'gcp.label.{key}'] = value
                
                spans.append(span_data)
        
        # New Relicに送信
        headers = {
            'Content-Type': 'application/json',
            'Api-Key': license_key
        }
        
        payload = {
            'common': {
                'attributes': {
                    'service.name': 'gcp-trace-integration',
                    'service.version': '1.0.0'
                }
            },
            'spans': spans
        }
        
        response = requests.post(
            newrelic_endpoint,
            headers=headers,
            json=payload
        )
        
        return {
            'status': 'success',
            'traces_processed': len(spans),
            'response_status': response.status_code
        }
        
    except Exception as e:
        print(f'Error processing traces: {str(e)}')
        return {'error': str(e)}, 500

運用とベストプラクティス

ラベルベースの監視設定

GCPリソースのラベルを活用した効率的な監視設定です。

yaml
# Infrastructure Agent でのGCPラベル活用設定
license_key: YOUR_LICENSE_KEY
display_name: production-instance-01

# GCP ラベルの自動取得
enable_gcp_labels: true
gcp_labels_include:
  - environment
  - application
  - team
  - cost-center
  - owner

# ラベルベースの条件付き設定
conditional_config:
  - condition: "labels.environment == 'production'"
    config:
      verbose: 0
      metrics_process_sample_rate: 15
  - condition: "labels.environment == 'development'"
    config:
      verbose: 1
      metrics_process_sample_rate: 60

コスト最適化設定

GCP統合のコストを最適化するための設定です。

hcl
# コスト最適化されたGCP統合設定
resource "newrelic_cloud_gcp_integrations" "cost_optimized" {
  account_id        = var.newrelic_account_id
  linked_account_id = newrelic_cloud_gcp_link_account.gcp.id

  # 重要なサービスのみ有効化
  compute {
    metrics_polling_interval = 600  # 10分間隔
    fetch_tags              = true
  }

  gke {
    metrics_polling_interval = 600
    fetch_tags              = true
  }

  cloud_sql {
    metrics_polling_interval = 900  # 15分間隔
  }

  # 開発環境のプロジェクトは除外
  # 使用しないサービスは設定から除外
}

Cloud Monitoring ダッシュボード統合

Cloud MonitoringとNew Relicの相互運用性を高める設定です。

python
# Cloud Monitoring カスタムメトリクスをNew Relicに送信
from google.cloud import monitoring_v3
import requests
import json
import os

def sync_custom_metrics():
    """
    Cloud Monitoring カスタムメトリクスをNew Relicに同期
    """
    
    # クライアント初期化
    client = monitoring_v3.MetricServiceClient()
    project_name = f"projects/{os.environ['GCP_PROJECT']}"
    
    # New Relic設定
    newrelic_endpoint = 'https://metric-api.newrelic.com/metric/v1'
    license_key = os.environ['NEW_RELIC_LICENSE_KEY']
    
    # カスタムメトリクスの取得
    metrics = client.list_metric_descriptors(name=project_name)
    
    for metric in metrics:
        if metric.type.startswith('custom.googleapis.com/'):
            # メトリクスデータの取得と変換
            # ...変換ロジック...
            
            # New Relicに送信
            headers = {
                'Content-Type': 'application/json',
                'Api-Key': license_key
            }
            
            # 送信処理
            response = requests.post(newrelic_endpoint, headers=headers, json=metric_data)

セキュリティ考慮事項

最小権限の原則

より厳密な権限設定を適用するカスタムロール定義です。

yaml
# カスタムロール定義 (custom-role.yaml)
title: "New Relic Integration Minimal Role"
description: "Minimal permissions for New Relic GCP integration"
stage: "GA"
includedPermissions:
  # Compute Engine
  - "compute.instances.get"
  - "compute.instances.list"
  - "compute.zones.get"
  - "compute.zones.list"
  
  # Monitoring
  - "monitoring.metricDescriptors.list"
  - "monitoring.timeSeries.list"
  
  # Cloud SQL
  - "cloudsql.instances.get"
  - "cloudsql.instances.list"
  
  # Container/GKE
  - "container.clusters.get"
  - "container.clusters.list"
  
  # Storage
  - "storage.buckets.get"
  - "storage.buckets.list"
  
  # Logging (読み取り専用)
  - "logging.entries.list"
  - "logging.logs.list"
bash
# カスタムロールの作成
gcloud iam roles create newrelicIntegrationRole \
  --project=$PROJECT_ID \
  --file=custom-role.yaml

VPC セキュリティ設定

プライベートネットワークでの安全な通信設定です。

hcl
# VPC とファイアウォール設定
resource "google_compute_network" "newrelic_vpc" {
  name                    = "newrelic-monitoring-vpc"
  auto_create_subnetworks = false
}

resource "google_compute_subnetwork" "newrelic_subnet" {
  name          = "newrelic-monitoring-subnet"
  ip_cidr_range = "10.0.1.0/24"
  region        = var.gcp_region
  network       = google_compute_network.newrelic_vpc.id
  
  private_ip_google_access = true
}

# New Relic エンドポイントへのアクセス許可
resource "google_compute_firewall" "newrelic_egress" {
  name    = "newrelic-egress"
  network = google_compute_network.newrelic_vpc.name
  
  allow {
    protocol = "tcp"
    ports    = ["443"]
  }
  
  direction          = "EGRESS"
  target_tags        = ["newrelic-monitored"]
  destination_ranges = ["0.0.0.0/0"]
}

# 内部通信の許可
resource "google_compute_firewall" "internal_communication" {
  name    = "allow-internal"
  network = google_compute_network.newrelic_vpc.name
  
  allow {
    protocol = "tcp"
    ports    = ["22", "80", "443"]
  }
  
  allow {
    protocol = "icmp"
  }
  
  source_ranges = ["10.0.1.0/24"]
  target_tags   = ["newrelic-monitored"]
}

まとめ

GCP環境でのNew Relic Infrastructure Agent導入とGCP統合設定により、Compute EngineからGCPマネージドサービスまでの包括的な監視が実現できます。適切なサービスアカウント設定とラベルベースの管理により、セキュリティを保ちながら効率的な運用が可能になります。

Terraform やDeployment Managerを活用したInfrastructure as Codeアプローチにより、一貫性のある監視環境を大規模に展開できるでしょう。次回は、設定ファイルの完全リファレンスについて詳しく解説します。


関連記事: Azure統合設定関連記事: 設定ファイル完全リファレンス