0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Create a condition for request count

0
Last updated at Posted at 2023-05-09
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))


0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?