通过 Terraform 管理 Azure 资源锁

Hou*_*und 5 azure terraform terraform-provider-azure azure-resource-lock

我计划通过 Terraform 管理 Azure 资源锁。ReadOnly我的想法是在资源级别创建锁。根据 Terraform 文档,以下代码可用于此目的。

resource "azurerm_management_lock" "resource-group-level" {
  name       = "resource-group-level"
  scope      = azurerm_resource_group.example.id
  lock_level = "ReadOnly"
  notes      = "This Resource Group is Read-Only"
}
Run Code Online (Sandbox Code Playgroud)

现在我担心对该资源的任何后续修改。在下一个执行周期中,对资源的任何更改都将失败,因为ReadOnly资源上有锁。我希望删除锁,进行修改并重新添加锁。

如何通过 Terraform 处理这样的场景?

Ans*_*-MT 3

如果您想删除资源组锁定,然后在对资源组进行更改后应用它,那么最好将锁定脚本保留在不同的文件中,并将资源保留在不同的文件中。

\n

我们将使用数据源并为资源创建锁,然后销毁它,您可以来回移动而不影响资源。

\n

示例:我使用不同的 .tf 文件创建了一个资源组,现在我想对其应用只读锁定。

\n

用于锁定的 .tf 文件

\n
provider "azurerm" {\n    features {}\n}\ndata "azurerm_resource_group" "example" {\n  name     = "your resource-group name"\n}\n\nresource "azurerm_management_lock" "rglock" {\n  name       = "resource-group-level"\n  scope      = data.azurerm_resource_group.example.id\n  lock_level = "ReadOnly"\n  notes      = "This Resource Group is Read-Only"\n}\n
Run Code Online (Sandbox Code Playgroud)\n

因此,我们只需要将 terraform 应用于此锁定文件,就会创建锁定,当我们需要删除它时,我们可以执行 terraform destroy 并来回执行。

\n

terraform-apply 的输出

\n

在此输入图像描述

\n

在此输入图像描述

\n

terraform-destroy 的输出

\n

在此输入图像描述

\n

在此输入图像描述\nterraform destroy 命令仅销毁 Lock,因为它\xe2\x80\x99 是我们 terraform 脚本中的一个资源块,而我们的资源组是一个数据块,因此它不会\xe2\x80\x99 对其进行任何更改。

\n