from google.cloud import monitoring_v3
from google.oauth2 import service_account
# 認証情報を指定してクライアントを作成する
credentials = service_account.Credentials.from_service_account_file('<path-to-service-account-key-file>')
client = monitoring_v3.AlertPolicyServiceClient(credentials=credentials)
# Cloud Runサービスのリビジョン名を指定する
service_name = '<your-service-name>'
revision_name = '<your-revision-name>'
# アラートポリシーを作成する
alert_policy = monitoring_v3.types.alert_pb2.AlertPolicy()
alert_policy.display_name = 'Cloud Run Alert Policy'
# インスタンス数の条件を追加する
instance_condition = alert_policy.conditions.add()
instance_condition.display_name = 'High instance count'
instance_condition.condition_threshold.filter = f'metric.type="cloud_run_revision_instance_count" resource.type="cloud_run_revision" resource.label."service_name"="{service_name}" resource.label."revision_name"="{revision_name}"'
instance_condition.condition_threshold.duration = {'seconds': 60}
instance_condition.condition_threshold.threshold_value = 50
# 通知チャネルを設定する
notification = monitoring_v3.types.Notification()
notification.type = 'pubsub'
notification.pubsub_topic = '<your-pubsub-topic>'
alert_policy.notification_channels.add(topic_name=notification.pubsub_topic)
# 通知チャネルの追加情報を設定する
notification_config = monitoring_v3.types.AlertPolicy.NotificationConfig()
teams_channel = monitoring_v3.types.NotificationChannel()
teams_channel.type = 'microsoft_teams'
teams_channel.display_name = 'My Teams Channel'
teams_channel.user_labels['channel_address'] = '<your-teams-channel-webhook-url>'
notification_config.alert_history_window = {'seconds': 3600}
notification_config.channels.append(teams_channel)
alert_policy.notification_config = notification_config
# アラートポリシーを作成する
project_name = f'projects/{project_id}'
alert_policy = monitoring_v3.types.AlertPolicy()
alert_policy.display_name = 'My Alert Policy'
alert_policy.combiner = monitoring_v3.enums.ConditionCombinerType.AND.value
# Set the notification channel
alert_policy.notification_channels = [teams_channel.name]
# Create the alert policy
alert_policy = client.create_alert_policy(project_name, alert_policy)
print('Created alert policy: {}'.format(alert_policy.name))
More than 1 year has passed since last update.
Register as a new user and use Qiita more conveniently
- You get articles that match your needs
- You can efficiently read back useful information
- You can use dark theme