adaptive.run TECH BLOG

Cloud can be tricky sometimes. Find out what scenarios we've ran into that are worth being mentioned and explained.

Do Configuration Management on VM in Azure with Bicep and Run Commands

Level: 300
Publishing date: 31-Jan-2023
Author: Catalin Popa

Bicep, the IaC language created by Microsoft for Azure, does not have built-in capabilities for configuration management of virtual machines. However, it can be achieved on the OS level using Run Commands, an Azure service for running scripts on VMs.
Here is how to use Run Commands in a Bicep template to deploy a virtual machine and run a script post-deployment.

First, the Bicep template creates a virtual machine, NIC, and public IP address. Then, the Run Commands resource is added to the bottom of the template. The resource requires a name, location, and two properties: the parent virtual machine and the script to run. The parent virtual machine is specified to ensure the creation of the virtual machine before running the script.

Here is the code for the Bicep template with Run Commands:

resource runCommandsVM 'Microsoft.Compute/virtualMachines/runCommands' = {
name: 'runCommandsVM',
location: resourceGroup().location,
properties: {
commands: [
{
script: 'Write-Output "Set registry keys"'
commandId: 'SetRegistryKeys',
properties: {
registry: [
{
key: 'HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Server',
valueName: 'DisabledByDefault',
valueData: '0xffffffff',
valueType: 'Dword'
}
]
}
}
],
vm: {
id: vm.id
}
}

The script used in this example is a PowerShell script that sets registry keys for Azure AD Application Proxy. It is written as a multi-line string in the template but can also be uploaded to a storage account and specified in the template using the property ScriptUri.
And here is the code with the script uploaded to a storage account:

resource runCommandsVM 'Microsoft.Compute/virtualMachines/runCommands' = {
name: 'runCommandsVM',
location: resourceGroup().location,
properties: {
commands: [
{
scriptUri: 'https://{storageAccountName}.blob.core.windows.net/{containerName}/{scriptName}.ps1?{SAS-token}',
commandId: 'SetRegistryKeys'
}
],
vm: {
id: vm.id
}
}

To deploy the template, use PowerShell and the AZ module. The deployment should look good in the terminal and all resources, including the Run Commands resource, should be created in the Azure portal.
To verify that the script ran, RDP into the virtual machine and check the registry for the set key.

adaptive.run

Transform your business.
Run adaptive.

Contact

Phone: +40 73 523 0005
Email: hello@adaptive.run

© Copyright  2019-2024 adaptive.run- All Rights Reserved