Secure resources in your Azure subscription by simple Powershell script

Today I want to tell you a little bit about Azure locks.
Frequent problem which I observed in some of the organizations is unexpected removal of resources.
Situation is always the same, user created some test resource group and another user remove this resource group. Explanation is always similar to “I thought that is not used anylonger”.
Locks can help with preventing this kind of situation. There are two types of locks:
* CanNotDelete – resource can be read and modified by users, but not deleted
* ReadOnly – users can only read resource, but can not delete or update resource
To manage locks, user must have access to Microsoft.Authorization/* or Microsoft.Authorization/locks/* (Owner or User access administrator in built-in roles)
How to create locks without azure portal? Yes, the answer is Powershell 🙂
Below script shows how to do it for all resources in your subscription.

Select-AzureSubscription -SubscriptionId subscriptionID 
$CIs = Get-AzureRmResource 
foreach($ci in $CIs)
    Write-Host Name: $CI.Name   Type: $CI.ResourceType.Split("/")[1] ResourceGroup:  $CI.ResourceGroupName
    New-AzureRmResourceLock -LockLevel CanNotDelete -LockName LockSite -ResourceName $ci.ResourceName -ResourceType $ci.ResourceType -ResourceGroupName $ci.ResourceGroupName

If you want to adjust it for some specific group, you must only filter $CIs with proper resource group name.
I hope it will be usefull for some of you. Enjoy! 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.