演示如何批量启用与过滤条件匹配的提醒政策。
深入探索
如需查看包含此代码示例的详细文档,请参阅以下内容:
代码示例
C#
如需向 Monitoring 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证。
static object EnablePolicies(string projectId, string filter, bool enable)
{
var client = AlertPolicyServiceClient.Create();
var request = new ListAlertPoliciesRequest()
{
ProjectName = new ProjectName(projectId),
Filter = filter
};
var response = client.ListAlertPolicies(request);
int result = 0;
foreach (AlertPolicy policy in response)
{
try
{
if (policy.Enabled == enable)
{
Console.WriteLine("Policy {0} is already {1}.",
policy.Name, enable ? "enabled" : "disabled");
continue;
}
policy.Enabled = enable;
var fieldMask = new FieldMask { Paths = { "enabled" } };
client.UpdateAlertPolicy(fieldMask, policy);
Console.WriteLine("{0} {1}.", enable ? "Enabled" : "Disabled",
policy.Name);
}
catch (Grpc.Core.RpcException e)
when (e.Status.StatusCode == StatusCode.InvalidArgument)
{
Console.WriteLine(e.Message);
result -= 1;
}
}
// Return a negative count of how many enable operations failed.
return result;
}
Go
如需向 Monitoring 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证。
// enablePolicies enables or disables all alert policies in the project.
func enablePolicies(w io.Writer, projectID string, enable bool) error {
ctx := context.Background()
client, err := monitoring.NewAlertPolicyClient(ctx)
if err != nil {
return err
}
defer client.Close()
req := &monitoringpb.ListAlertPoliciesRequest{
Name: "projects/" + projectID,
// Filter: "", // See https://cloud.google.com/monitoring/api/v3/sorting-and-filtering.
// OrderBy: "", // See https://cloud.google.com/monitoring/api/v3/sorting-and-filtering.
}
it := client.ListAlertPolicies(ctx, req)
for {
a, err := it.Next()
if err == iterator.Done {
break
}
if err != nil {
return err
}
if a.GetEnabled().GetValue() == enable {
fmt.Fprintf(w, "Policy %q already has enabled=%v", a.GetDisplayName(), enable)
continue
}
a.Enabled = &wrappers.BoolValue{Value: enable}
req := &monitoringpb.UpdateAlertPolicyRequest{
AlertPolicy: a,
UpdateMask: &fieldmask.FieldMask{
Paths: []string{"enabled"},
},
}
if _, err := client.UpdateAlertPolicy(ctx, req); err != nil {
return err
}
}
fmt.Fprintln(w, "Successfully updated alerts.")
return nil
}
Java
如需向 Monitoring 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证。
private static void enablePolicies(String projectId, String filter, boolean enable)
throws IOException {
try (AlertPolicyServiceClient client = AlertPolicyServiceClient.create()) {
ListAlertPoliciesPagedResponse response =
client.listAlertPolicies(
ListAlertPoliciesRequest.newBuilder()
.setName(ProjectName.of(projectId).toString())
.setFilter(filter)
.build());
for (AlertPolicy policy : response.iterateAll()) {
if (policy.getEnabled().getValue() == enable) {
System.out.println(
String.format(
"Policy %s is already %b.", policy.getName(), enable ? "enabled" : "disabled"));
continue;
}
AlertPolicy updatedPolicy =
AlertPolicy.newBuilder()
.setName(policy.getName())
.setEnabled(BoolValue.newBuilder().setValue(enable))
.build();
AlertPolicy result =
client.updateAlertPolicy(
FieldMask.newBuilder().addPaths("enabled").build(), updatedPolicy);
System.out.println(
String.format(
"%s %s",
result.getDisplayName(), result.getEnabled().getValue() ? "enabled" : "disabled"));
}
}
}
Node.js
如需向 Monitoring 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证。
// Imports the Google Cloud client library
const monitoring = require('@google-cloud/monitoring');
// Creates a client
const client = new monitoring.AlertPolicyServiceClient();
async function enablePolicies() {
/**
* TODO(developer): Uncomment the following lines before running the sample.
*/
// const projectId = 'YOUR_PROJECT_ID';
// const enabled = true;
// const filter = 'A filter for selecting policies, e.g. description:"cloud"';
const listAlertPoliciesRequest = {
name: client.projectPath(projectId),
// See https://cloud.google.com/monitoring/alerting/docs/sorting-and-filtering
filter: filter,
};
const [policies] = await client.listAlertPolicies(listAlertPoliciesRequest);
const responses = [];
for (const policy of policies) {
responses.push(
await client.updateAlertPolicy({
updateMask: {
paths: ['enabled'],
},
alertPolicy: {
name: policy.name,
enabled: {
value: enabled,
},
},
})
);
}
responses.forEach(response => {
const alertPolicy = response[0];
console.log(`${enabled ? 'Enabled' : 'Disabled'} ${alertPolicy.name}.`);
});
}
enablePolicies();
PHP
如需向 Monitoring 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证。
use Google\Cloud\Monitoring\V3\Client\AlertPolicyServiceClient;
use Google\Cloud\Monitoring\V3\ListAlertPoliciesRequest;
use Google\Cloud\Monitoring\V3\UpdateAlertPolicyRequest;
use Google\Protobuf\FieldMask;
/**
* Enable or disable alert policies in a project.
*
* @param string $projectId Your project ID
* @param bool $enable Enable or disable the policies.
* @param string $filter Only enable/disable alert policies that match a filter.
* See https://cloud.google.com/monitoring/api/v3/sorting-and-filtering
*/
function alert_enable_policies($projectId, $enable = true, $filter = null)
{
$alertClient = new AlertPolicyServiceClient([
'projectId' => $projectId,
]);
$projectName = 'projects/' . $projectId;
$listAlertPoliciesRequest = (new ListAlertPoliciesRequest())
->setName($projectName)
->setFilter($filter);
$policies = $alertClient->listAlertPolicies($listAlertPoliciesRequest);
foreach ($policies->iterateAllElements() as $policy) {
$isEnabled = $policy->getEnabled()->getValue();
if ($enable == $isEnabled) {
printf('Policy %s is already %s' . PHP_EOL,
$policy->getName(),
$isEnabled ? 'enabled' : 'disabled'
);
} else {
$policy->getEnabled()->setValue((bool) $enable);
$mask = new FieldMask();
$mask->setPaths(['enabled']);
$updateAlertPolicyRequest = (new UpdateAlertPolicyRequest())
->setAlertPolicy($policy)
->setUpdateMask($mask);
$alertClient->updateAlertPolicy($updateAlertPolicyRequest);
printf('%s %s' . PHP_EOL,
$enable ? 'Enabled' : 'Disabled',
$policy->getName()
);
}
}
}
Python
如需向 Monitoring 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证。
def enable_alert_policies(project_name, enable, filter_=None):
"""Enable or disable alert policies in a project.
Arguments:
project_name (str): The Google Cloud Project to use. The project name
must be in the format - 'projects/<PROJECT_NAME>'.
enable (bool): Enable or disable the policies.
filter_ (str, optional): Only enable/disable alert policies that match
this filter_. See
https://cloud.google.com/monitoring/api/v3/sorting-and-filtering
"""
client = monitoring_v3.AlertPolicyServiceClient()
policies = client.list_alert_policies(
request={"name": project_name, "filter": filter_}
)
for policy in policies:
if bool(enable) == policy.enabled:
print(
"Policy",
policy.name,
"is already",
"enabled" if policy.enabled else "disabled",
)
else:
policy.enabled = bool(enable)
mask = field_mask.FieldMask()
mask.paths.append("enabled")
client.update_alert_policy(alert_policy=policy, update_mask=mask)
print("Enabled" if enable else "Disabled", policy.name)
后续步骤
如需搜索和过滤其他 Google Cloud 产品的代码示例,请参阅 Google Cloud 示例浏览器。