如何使用terraform为Azure锁创建循环

dced5bon  于 2023-01-02  发布在  其他
关注(0)|答案(1)|浏览(129)

我尝试将锁应用到Azure环境中的所有资源组。一些资源组将具有只读锁,一些将具有删除锁,而一些根本不会具有锁(意味着terraform块不应执行)。
我试过写下面的代码(我知道我不擅长它的原因难以找到解决方案,所以给一些代码,我已经尝试).要求是我们需要只有一个terraform资源块.那么,我如何才能实现部署锁定到所有资源组在第一段提到的条件下?
我们可以使用模块,计数,为每个。范围应与resouregroupbool内联,例如,当资源块与变量"deploy_network_rg_lock"一起执行时,它应与"网络资源组的资源ID"匹配。但我需要声明范围的变量,但我不知道它如何与resourcegroupbool内联。
有人能帮忙找找吗?

#resource block for lock
resource "azurerm_management_lock" "locks" {
  count     = var.resourcegroupbool ? 1 : 0  #here also I want to use variables, currently shown is bool and need to have group of boolean        
  name      = var.env == "dev" ? "Read-lock" : "Delete-lock"  
  scope     = #here I want to use variables based on resource group but I didn't get it
  lock_type = var.env == "dev" ? "ReadOnly" : "CanNotDelete"
}
#varibles I declared
variable "resourcegroupbool" {
  description = "List of resource group whether need to apply lock"
  type = object({
    deploy_network_rg_lock     = bool
    deploy_liveadls_rg_lock    = bool
    deploy_privatelink_rg_lock = bool
    deploy_keyvault_rg_lock    = bool
  })
}

variable "env" {
  type = "string"
  description = "Environment of lock needs to be applied"
#Varible values in .tfvars
resourcegroupbool = {
  #If true, lock will be applied. If false, lock will be removed if it's exists.
   deploy_network_rg_lock     = false   
   deploy_liveadls_rg_lock    = true   
   deploy_privatelink_rg_lock = true   
   deploy_keyvault_rg_lock    = true   
}

env = "dev"
2izufjch

2izufjch1#

从我的理解来看,似乎要求有一个变量来定义哪些资源组应该受到锁的约束。
与其为每个资源组定义一个带有布尔字段的对象变量resourcegroupbool,为什么不使用包含要锁定的资源组名称的变量呢?
变量可以是:

variable "locked_resource_groups" {
  type        = set(string)
  description = "Name of the resource groups to which apply a lock"
}

然后,您可以使用数据源来获取每个资源组的ID,如下所示:

data "azurerm_resource_group" "locked" {
  for_each = var.locked_resource_groups

  name = each.value
}

最后,可以使用for_each迭代数据源并在每个资源组上创建锁:

resource "azurerm_management_lock" "locks" {
  for_each = data.azurerm_resource_group.locked

  name      = var.env == "dev" ? "Read-lock" : "Delete-lock"
  scope     = each.value.id
  lock_type = var.env == "dev" ? "ReadOnly" : "CanNotDelete"
}

相关问题