만료되는 인증 기관 모니터링

관리형 CA가 만료되기 30일 전에 알리는 모니터링 정책을 만듭니다.

코드 샘플

Java

CA Service에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


import com.google.cloud.monitoring.v3.AlertPolicyServiceClient;
import com.google.cloud.monitoring.v3.NotificationChannelServiceClient;
import com.google.monitoring.v3.AlertPolicy;
import com.google.monitoring.v3.AlertPolicy.Condition;
import com.google.monitoring.v3.AlertPolicy.Condition.MonitoringQueryLanguageCondition;
import com.google.monitoring.v3.AlertPolicy.ConditionCombinerType;
import com.google.monitoring.v3.NotificationChannel;
import com.google.monitoring.v3.ProjectName;
import java.io.IOException;

public class MonitorCertificateAuthority {

  public static final String POLICY_NAME = "policy-name";

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String project = "your-project-id";
    createCaMonitoringPolicy(project);
  }

  // Creates a monitoring policy that notifies you 30 days before a managed CA expires.
  public static String createCaMonitoringPolicy(String project) throws IOException {
    /* Initialize client that will be used to send requests. This client only needs to be created
    once, and can be reused for multiple requests. After completing all of your requests, call
    the `client.close()` method on the client to safely
    clean up any remaining background resources. */
    try (AlertPolicyServiceClient client = AlertPolicyServiceClient.create();
        NotificationChannelServiceClient notificationClient =
            NotificationChannelServiceClient.create()) {

      /* Query which indicates the resource to monitor and the constraints.
      Here, the alert policy notifies you 30 days before a managed CA expires.
      For more info on creating queries, see: https://cloud.google.com/monitoring/mql/alerts */
      String query =
          "fetch privateca.googleapis.com/CertificateAuthority"
              + "| metric 'privateca.googleapis.com/ca/cert_chain_expiration'"
              + "| group_by 5m,"
              + "[value_cert_chain_expiration_mean: mean(value.cert_chain_expiration)]"
              + "| every 5m"
              + "| condition val() < 2.592e+06 's'";

      // Create a notification channel.
      NotificationChannel notificationChannel =
          NotificationChannel.newBuilder()
              .setType("email")
              .putLabels("email_address", "java-docs-samples-testing@google.com")
              .build();
      NotificationChannel channel =
          notificationClient.createNotificationChannel(
              ProjectName.of(project), notificationChannel);

      // Set the query and notification channel.
      AlertPolicy alertPolicy =
          AlertPolicy.newBuilder()
              .setDisplayName(POLICY_NAME)
              .addConditions(
                  Condition.newBuilder()
                      .setDisplayName("ca-cert-chain-expiration")
                      .setConditionMonitoringQueryLanguage(
                          MonitoringQueryLanguageCondition.newBuilder().setQuery(query).build())
                      .build())
              .setCombiner(ConditionCombinerType.AND)
              .addNotificationChannels(channel.getName())
              .build();

      AlertPolicy policy = client.createAlertPolicy(ProjectName.of(project), alertPolicy);

      System.out.println("Monitoring policy successfully created !" + policy.getName());
      return policy.getName();
    }
  }
}

Python

CA Service에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

import google.cloud.monitoring_v3 as monitoring_v3


def create_ca_monitor_policy(project_id: str) -> None:
    """
    Create a monitoring policy that notifies you 30 days before a managed CA expires.

    Args:
        project_id: project ID or project number of the Cloud project you want to use.
    """

    alertPolicyServiceClient = monitoring_v3.AlertPolicyServiceClient()
    notificationChannelServiceClient = monitoring_v3.NotificationChannelServiceClient()

    # Query which indicates the resource to monitor and the constraints.
    # Here, the alert policy notifies you 30 days before a managed CA expires.
    # For more information on creating queries, see: https://cloud.google.com/monitoring/mql/alerts
    query = (
        "fetch privateca.googleapis.com/CertificateAuthority"
        "| metric 'privateca.googleapis.com/ca/cert_chain_expiration'"
        "| group_by 5m,"
        "[value_cert_chain_expiration_mean: mean(value.cert_chain_expiration)]"
        "| every 5m"
        "| condition val() < 2.592e+06 's'"
    )

    # Create a notification channel.
    notification_channel = monitoring_v3.NotificationChannel(
        type_="email",
        labels={"email_address": "python-docs-samples-testing@google.com"},
    )
    channel = notificationChannelServiceClient.create_notification_channel(
        name=notificationChannelServiceClient.common_project_path(project_id),
        notification_channel=notification_channel,
    )

    # Set the query and notification channel.
    alert_policy = monitoring_v3.AlertPolicy(
        display_name="policy-name",
        conditions=[
            monitoring_v3.AlertPolicy.Condition(
                display_name="ca-cert-chain-expiration",
                condition_monitoring_query_language=monitoring_v3.AlertPolicy.Condition.MonitoringQueryLanguageCondition(
                    query=query,
                ),
            )
        ],
        combiner=monitoring_v3.AlertPolicy.ConditionCombinerType.AND,
        notification_channels=[channel.name],
    )

    policy = alertPolicyServiceClient.create_alert_policy(
        name=notificationChannelServiceClient.common_project_path(project_id),
        alert_policy=alert_policy,
    )

    print("Monitoring policy successfully created!", policy.name)

다음 단계

다른 Google Cloud 제품의 코드 샘플을 검색하고 필터링하려면 Google Cloud 샘플 브라우저를 참조하세요.