Azure PowerShell: Deploy Linux Custom Script Extension

Here’s how you can deploy an Azure VM Extension via PowerShell:

# Before running this, upload your bash script to an Azure storage account container, grab its name and key via PowerShell or the Azure portal
 
Login-AzureRmAccount 
 
$Subscription = "MySubscription"
$ResourceGroupName = "MyResourceGroup"
$VMName = "myvm"
$Location = "eastus"
$OldCseName = "PreviousCSE"
$NewCseName = "NewCSE"
$StorageAccountName = "storageaccountname"
$StorageAccountKey = "longstorageaccountkey"
$StorageContainerName = "storageaccountcontainername"
$ScriptName = "myscript.sh"
 
Select-AzureRmSubscription -Subscription $Subscription
 
# You can only have one extension of each type - remove the existing one before you deploy
Remove-AzureRmVMExtension -ResourceGroupName $ResourceGroupName -VMName $VMName -Name $OldCseName -Force
 
# Now, set the new extension
Set-AzureRmVMExtension `
  -ResourceGroupName $ResourceGroupName `
  -VMName $VMName `
  -Location $Location `
  -Name $NewCseName `
  -Publisher "Microsoft.OSTCExtensions" `
  -ExtensionType "CustomScriptForLinux" `
  -TypeHandlerVersion "1.5" `
  -Settings @{"fileUris" = [Object[]]"https://$StorageAccountName.blob.core.windows.net/$StorageContainerName/$ScriptName";"commandToExecute" = "bash $ScriptName"} `
  -ProtectedSettings @{"storageAccountName" = $StorageAccountName;"storageAccountKey" = $StorageAccountKey}
 
# If your script isn't idempotent, remove it after success
Remove-AzureRmVMExtension -ResourceGroupName $ResourceGroupName -VMName $VMName -Name $NewCseName -Force

Hope this helps!

This entry was posted in Azure, Bash, PowerShell. Bookmark the permalink.

Leave a Reply

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