Hi @Rory_Feng ,
To remotely run linux command like "service tomcat start" in VM via Azure Automation runbook, you may follow one of the below 2 approaches.
- Create an Azure storage account, container and upload a blob i.e., script (say tomcat_service_start.sh file with the content "service tomcat start") and then have below code in Azure Automation PowerShell runbook.
$connectionName = "AzureRunAsConnection"
$servicePrincipalConnection = Get-AutomationConnection -Name $connectionName
$ConnectToAzAccount = Add-AzAccount -ServicePrincipal -TenantId $servicePrincipalConnection.TenantId -ApplicationId $servicePrincipalConnection.ApplicationId -CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint$StorageAccountName = "xxxxxxxxxxxxx"
$StorageAccountKey = "xxxxxxxxxxxxxx=="
$ContainerName = "xxxxxxxxxxxxxxx"
$BlobName_Linux = "tomcat_service_start.sh"
$RG_VM = "xxxxxxxxxxxxxxxxxx"
$VM_Name_Linux = "xxxxxxxxx"
$InvokeCmd_Id_Linux = "RunShellScript"$AzStorage = New-AzStorageContext -StorageAccountName $StorageAccountName -StorageAccountKey $StorageAccountKey
$AzStorageContext = $AzStorage.Context$GetBlobContent_Linux = Get-AzStorageBlobContent -Container $ContainerName -Blob $BlobName_Linux -Destination ($Env:temp+"/tomcat_service_start.sh") -Context $AzStorageContext -Force
$InvokeRunCmdOutput_Linux = Invoke-AzVMRunCommand -ResourceGroupName $RG_VM -VMName $VM_Name_Linux -CommandId $InvokeCmd_Id_Linux -ScriptPath ($Env:temp+"/tomcat_service_start.sh")
$TomcatServiceStart_Output_Linux = $InvokeRunCmdOutput_Linux.Value[0].Message
Write-Output $TomcatServiceStart_Output_Linux
- Save a script (say \home\xxxx\tomcat_service_start.sh) in your VM and have the linux command "service tomcat start" as content in that file and then have below code in Azure Automation PowerShell runbook.
$ServicePrincipalConnection = Get-AutomationConnection -Name 'AzureRunAsConnection'
Add-AzAccount -ServicePrincipal -TenantId $ServicePrincipalConnection.TenantId -ApplicationId $ServicePrincipalConnection.ApplicationId -CertificateThumbprint $ServicePrincipalConnection.CertificateThumbprint
$rgname ="rrrrrrrrrrrrrr"
$vmname ="vvvvvvvvvvvvvv"
$ScriptToRun = "\home\xxxx\tomcat_service_start.sh"
Out-File -InputObject $ScriptToRun -FilePath ScriptToRun.sh
Invoke-AzVMRunCommand -ResourceGroupName $rgname -Name $vmname -CommandId 'RunShellScript' -ScriptPath ScriptToRun.sh
Remove-Item -Path ScriptToRun.sh
Note:
- Before trying any of the above approaches, make sure you import required cmdlets modules in your Azure Automation Account.
- Above approaches are with PowerShell runbook so you may have to tweak them to re-use in PowerShell workflow runbook.
- This / this questions are the source of the above information.