Quantcast
Viewing all articles
Browse latest Browse all 30

Azure: Run Windows Custom Script Extension with VM Credentials

By default, the Windows Custom Script Extension in Azure will run as Local System.

Here’s how you can pass your VM credentials from your Azure Resource Manager (ARM) template to the custom script extension and ensure they are not easily visible.

First, in your ARM template’s definition of the Custom Script Extension resource, ensure “commandToExecute” is defined in the “protectedSettings” section of the properties.

Note how the username and password of the VM creation are being passed to the command. The admin password is wrapped in double quotes to ensure special characters are escaped correctly on the command line.

"protectedSettings": { 
  "commandToExecute": "[concat('powershell -ExecutionPolicy Unrestricted -File CustomScripts/MyCustomScriptExtension.ps1 -vmAdminUsername ', parameters('adminUsername'), ' -vmAdminPassword \"', parameters('adminPassword'), '\"')]"
}

Next, in the custom script referenced by the “commandToExecute” above, you use Invoke-Command to run as the user you provided to the script.

#
# MyCustomScriptExtension.ps1
#
param (
  $vmAdminUsername,
  $vmAdminPassword
)
 
$password =  ConvertTo-SecureString $vmAdminPassword -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential("$env:USERDOMAIN\$vmAdminUsername", $password)
 
Write-Verbose -Verbose "Entering Custom Script Extension..."
 
Invoke-Command -Credential $credential -ComputerName $env:COMPUTERNAME -ArgumentList $PSScriptRoot -ScriptBlock {
  param 
  (
    $workingDir
  )
 
  #################################
  # Elevated custom scripts go here 
  #################################
  Write-Verbose -Verbose "Entering Elevated Custom Script Commands..."
}

Note that you can still expose your sensitive information to the execution context if you use elements like Start-Transcript in the script wrapper as it will dump the full command line in clear text to the log.

Hope this helps!


Viewing all articles
Browse latest Browse all 30

Trending Articles