Enable resource logs in Virtual Machine Scale Sets with an Azure Policy
Introduction
The Azure policy reference guide for Azure Virtual Machine Scale Sets recommends to enable logs so that activity trail can be recreated when investigations are required in the event of an incident or a compromise.
In this article we will see how to automate this with an Azure Policy.
This article has been inspired by the following ones :
- An Azure Policy journey where it’s explained how to use deployment scripts in ARM templates within Azure Policies.
- Adding Diagnostic Extensions to an Existing Azure VM Scale Set with Azure CLI.
Policy
The starting point is to clone the Azure Built-in policy Resource logs in Virtual Machine Scale Sets should be enabled that uses the effects : AuditIfNotExists and Disabled.
The job is almost done by this Built-in policy as it will identify the VM Scale Sets that are not compliant, the remaining job is the remediation one, which consists in the following action (the complete policy is available here) :
- Add the action DeployIfNotExists to manage the remediation action.
- Use a deployment script in ARM templates for the the remediation action.
- Prepare the environment with the deployment script User Managed Identity that need to have the necessary permission to generate a SAS Token on a Storage Account (logging purposes) and add log extension on a VM Scale Set.
- Prepare the environment with a Storage Account (logging purposes) and make sure firewall is set to “Allow access from all networks”, otherwise you will have the following message (a feature request has been published here to improve this).
Script
The following script consists in generating a SAS Token Key on a Storage Account, then use it to enable diagnostics in the VM Scale Set.
The script read the following variables
# 1 = Name of the Virtual Machine Set
# 1 = Resource Group Name of the Virtual Machine Set
# 3 = Storage Account Id where the log will be sent
# 4 = End date of the SAS token for the storage account (Universal full date/time pattern)
A nice tip with deployment script and ARM template is to generate the SAS token end time based on the current execution of the script.
Demo
Conclusion
Same conclusion done here in the : An Azure Policy journey → Azure Policy with deployment script in ARM templates is truly the PERFECT COMBO!
See you in the Cloud
Jamesdld