2
votes

Through Terraform I am planning to manage Azure resource locks. My idea is to create a ReadOnly lock at the resource level. As per the Terraform documentation, below code can be used for that purpose.

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"
}

Now I am concerned about any subsequent modification to the resource. During the next execution cycle, any changes to the resource will fail since there is a ReadOnly lock on the resource. What I am hoping for is to delete the lock, do the modification and add the lock back.

How to handle such a scenario through Terraform?

1

1 Answers

1
votes

If you want to delete the resource group lock and then apply it after doing changes in your resource group , then its better to keep the lock script in a different file and your resources in a different file.

We will use data source and create a lock for resource and then destroy it and you can move back and forth without affecting the resources .

Example: I have created a resource group using a different .tf file and now I want to apply a read only lock on it .

.tf file for lock

provider "azurerm" {
    features {}
}
data "azurerm_resource_group" "example" {
  name     = "your resource-group name"
}

resource "azurerm_management_lock" "rglock" {
  name       = "resource-group-level"
  scope      = data.azurerm_resource_group.example.id
  lock_level = "ReadOnly"
  notes      = "This Resource Group is Read-Only"
}

So , Just we need to do terraform apply to this lock file and the lock will be created and when we need to delete it we can perform terraform destroy and back and forth.

Output for terraform-apply

enter image description here

enter image description here

Output for terraform-destroy

enter image description here

enter image description here The terraform destroy command only destroys Lock as it’s a resource block in our terraform script and our resource group is a data block so it won’t change anything to it .