Mantenha tudo organizado com as coleções
Salve e categorize o conteúdo com base nas suas preferências.
Este documento descreve como usar o
provedor do TerraformGoogle Cloud para editar e excluir
políticas de alertas no seu projeto Google Cloud . O Google Cloud provedor do Terraform
fornece os seguintes recursos para políticas de alerta
e canais de notificação:
O Terraform é uma ferramenta para criar,
alterar e controlar versões de infraestrutura. Ele usa arquivos de configuração para descrever
os componentes necessários para executar um único aplicativo ou toda a infraestrutura.
Para mais informações sobre como usar o Terraform, consulte os seguintes
documentos:
Esse recurso só é compatível com projetos Google Cloud .
Para configurações do App Hub, selecione o projeto host do App Hub ou o projeto de gerenciamento da pasta com app ativado.
Antes de começar
Para receber as permissões necessárias para modificar políticas de alertas usando o Terraform,
peça ao administrador para conceder a você os
seguintes papéis do IAM no seu projeto:
Para editar ou excluir uma política de alertas no seu projeto Google Cloud , faça o seguinte:
Instale e configure o Terraform
para seu projeto. Para configurações do App Hub, selecione o projeto host do App Hub ou o projeto de gerenciamento da pasta com app ativado.
No Cloud Shell,
acesse o diretório que contém sua configuração do Terraform.
Edite o arquivo de configuração, localize o recurso google_monitoring_alert_policy
da sua política de alertas e modifique ou exclua
esse recurso.
No Cloud Shell, insira terraform apply.
Exportar uma configuração de política de alertas para uma configuração do Terraform
É possível exportar uma configuração de política de alertas de Google Cloud
para uma definição do Terraform na sua configuração do Terraform.
Esse processo é útil se você criou uma política de alertas em Google Cloud
depois de criar a configuração do Terraform.
Para exportar sua política de alertas, faça o seguinte:
Instale e configure o Terraform
para seu projeto. Para configurações do App Hub, selecione o projeto host do App Hub ou o projeto de gerenciamento da pasta com app ativado.
No Cloud Shell,
acesse o diretório que contém sua configuração do Terraform.
Adicione um bloco import a um arquivo na
configuração do Terraform.
O bloco de importação tem os seguintes argumentos:
to: o endereço do recurso conforme especificado na sua configuração do Terraform. Esse campo tem o formato
google_monitoring_alert_policy.RESOURCE_NAME,
em que RESOURCE_NAME é um valor escolhido por você.
Recomendamos escolher um nome de recurso que descreva claramente
sua política de alertas.
id: o nome da política de alertas. Esse campo tem o formato project/PROJECT_ID/alertPolicies/ALERT_POLICY_ID.
Por exemplo, se você quiser exportar uma política de alertas que monitora o uso da CPU, defina RESOURCE_NAME como cpu_usage_threshold. Em seguida, defina id como o nome da política de alertas:
import {
to = google_monitoring_alert_policy.cpu_usage_threshold
id = "projects/my-alerting-project/alertPolicies/7160801095019277297"
}
No Cloud Shell, execute este comando:
terraform plan -generate-config-out=generated.tf
O comando anterior cria um arquivo chamado generated.tf, que permite
revisar a definição da política de alertas
antes de adicioná-la à configuração do Terraform. Você pode editar a definição, movê-la para outro arquivo ou deixá-la inalterada.
No Cloud Shell, digite terraform apply para importar a definição da política de alertas para a configuração do Terraform.
Para mais informações sobre como gerar definições de recursos que não fazem parte da configuração do Terraform, consulte Gerar configuração.
[[["Fácil de entender","easyToUnderstand","thumb-up"],["Meu problema foi resolvido","solvedMyProblem","thumb-up"],["Outro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Informações incorretas ou exemplo de código","incorrectInformationOrSampleCode","thumb-down"],["Não contém as informações/amostras de que eu preciso","missingTheInformationSamplesINeed","thumb-down"],["Problema na tradução","translationIssue","thumb-down"],["Outro","otherDown","thumb-down"]],["Última atualização 2025-08-28 UTC."],[],[],null,["# Manage alerting policies with Terraform\n\nThis document describes how to use the\nGoogle Cloud Terraform Provider to edit and delete\nalerting policies in your Google Cloud project. The Google Cloud Terraform Provider\nprovides the following resources for alerting policies\nand notification channels:\n\n- [google_monitoring_alert_policy](https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/monitoring_alert_policy)\n- [google_monitoring_notification_channel](https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/monitoring_notification_channel)\n\n[Terraform](https://www.terraform.io/) is a tool for building,\nchanging, and versioning infrastructure. It uses configuration files to describe\nthe components needed to run a single application or your entire infrastructure.\nFor more information about using Terraform, see the following\ndocuments:\n\n- [Terraform on Google Cloud documentation](/docs/terraform#docs)\n- [Google Cloud Terraform Provider](https://registry.terraform.io/providers/hashicorp/google/latest/docs)\n- [Get Started - Google Cloud](https://developer.hashicorp.com/terraform/tutorials/gcp-get-started)\n\nThis feature is supported only for Google Cloud projects.\nFor [App Hub](/app-hub/docs/overview)\nconfigurations, select the App Hub host project or\nthe app-enabled folder's management project.\n\nBefore you begin\n----------------\n\n\nTo get the permissions that\nyou need to modify alerting policies by using Terraform,\n\nask your administrator to grant you the\nfollowing IAM roles on your project:\n\n- [Monitoring Editor](/iam/docs/roles-permissions/monitoring#monitoring.editor) (`roles/monitoring.editor`)\n- Create and use log-based alerting policies: [Logs Configuration Writer](/iam/docs/roles-permissions/logging#logging.configWriter) (`roles/logging.configWriter`)\n\n\nFor more information about granting roles, see [Manage access to projects, folders, and organizations](/iam/docs/granting-changing-revoking-access).\n\n\nYou might also be able to get\nthe required permissions through [custom\nroles](/iam/docs/creating-custom-roles) or other [predefined\nroles](/iam/docs/roles-overview#predefined).\n| **Note:** The Monitoring Editor role also lets you perform activities like creating dashboards and viewing incidents. If you only need to configure alerting policies with Terraform, then you can use the Monitoring AlertPolicy Editor (`roles/monitoring.alertPolicyEditor`) role instead.\n\nFor more information about Cloud Monitoring roles,\nsee [Control access with Identity and Access Management](/monitoring/access-control).\n\nEdit or delete alerting policies\n--------------------------------\n\nTo edit or delete an alerting policy in your Google Cloud project, do the following:\n\n1. [Install and configure Terraform](/docs/terraform/install-configure-terraform)\n for you project. For [App Hub](/app-hub/docs/overview)\n configurations, select the App Hub host project or\n the app-enabled folder's management project.\n\n2. In the Cloud Shell,\n go to the directory that contains your Terraform configuration.\n\n3. Edit the configuration file, locate the `google_monitoring_alert_policy`\n resource for your alerting policy, and then either modify or delete\n that resource.\n\n4. In the Cloud Shell, enter `terraform apply`.\n\nExport an alerting policy configuration to a Terraform configuration\n--------------------------------------------------------------------\n\nYou can export an alerting policy configuration from Google Cloud\nto a Terraform definition in your Terraform configuration.\nThis process is helpful if you created an alerting policy in Google Cloud\nafter you created your Terraform configuration.\n\nTo export your alerting policy, do the following:\n\n1. [Install and configure Terraform](/docs/terraform/install-configure-terraform)\n for you project. For [App Hub](/app-hub/docs/overview)\n configurations, select the App Hub host project or\n the app-enabled folder's management project.\n\n2. In the Cloud Shell,\n go to the directory that contains your Terraform configuration.\n\n3. Add an [`import`](https://developer.hashicorp.com/terraform/language/import) block to a file in your\n Terraform configuration.\n The import block has the following arguments:\n\n - `to`: The resource address as specified by your\n Terraform configuration. This field has the format of\n `google_monitoring_alert_policy.`\u003cvar translate=\"no\"\u003eRESOURCE_NAME\u003c/var\u003e,\n where \u003cvar translate=\"no\"\u003eRESOURCE_NAME\u003c/var\u003e is a value you choose.\n We recommend choosing a resource name that clearly describes\n your alerting policy.\n\n - `id`: The name of the alerting policy. This field has the format of\n `project/`\u003cvar translate=\"no\"\u003ePROJECT_ID\u003c/var\u003e`/alertPolicies/`\u003cvar translate=\"no\"\u003eALERT_POLICY_ID\u003c/var\u003e.\n\n For example, you want to export an alerting policy that monitors CPU usage,\n so you set \u003cvar translate=\"no\"\u003eRESOURCE_NAME\u003c/var\u003e to\n `cpu_usage_threshold`. You then set `id` as the alerting policy name: \n\n ```\n import {\n to = google_monitoring_alert_policy.cpu_usage_threshold\n id = \"projects/my-alerting-project/alertPolicies/7160801095019277297\"\n }\n ```\n4. In the Cloud Shell, run the following command:\n\n ```\n terraform plan -generate-config-out=generated.tf\n ```\n\n The previous command creates a file named `generated.tf`, which lets you\n review your alerting policy definition\n before you add it to your Terraform configuration. You can edit\n the definition, move it to a different file, or\n leave it unchanged.\n5. In the Cloud Shell, enter `terraform apply` to import your\n alerting policy definition to your Terraform configuration.\n\nFor more information about generating definitions for resources that aren't\npart of your Terraform configuration, see\n[Generating configuration](https://developer.hashicorp.com/terraform/language/import/generating-configuration).\n\nWhat's next\n-----------\n\n- Learn more about [Terraform](https://www.terraform.io/).\n- Try out code samples that use the Google Cloud Terraform Provider with Cloud Monitoring.\n- View the Google Cloud Terraform Provider [repository on GitHub](https://github.com/hashicorp/terraform-provider-google).\n- [File a GitHub issue](https://github.com/hashicorp/terraform-provider-google/issues) to report a bug or ask a question about Terraform."]]