Azure runbook - run Powershell on remote VM - azure

Azure runbook.
The question:
How to run/call powershell scripts on remote Azure VM via runbook? The script is placed on a remote VM.
There is no Azure AD, powershell has Az module installed.
Thank you.

Have your Azure Automation runbook something like shown below. It will accomplish your requirement.
$ServicePrincipalConnection = Get-AutomationConnection -Name 'AzureRunAsConnection'
Add-AzAccount -ServicePrincipal -TenantId $ServicePrincipalConnection.TenantId -ApplicationId $ServicePrincipalConnection.ApplicationId -CertificateThumbprint $ServicePrincipalConnection.CertificateThumbprint
$rgname ="rrrrrrrrrrrrrr"
$vmname ="vvvvvvvvvvvvvv"
$ScriptToRun = "ssssssssssssss"
Out-File -InputObject $ScriptToRun -FilePath ScriptToRun.ps1
Invoke-AzVMRunCommand -ResourceGroupName $rgname -Name $vmname -CommandId 'RunPowerShellScript' -ScriptPath ScriptToRun.ps1
Remove-Item -Path ScriptToRun.ps1
Note: Before you run your runbook, make sure you update "rrrrrrrrrrrrrr" with your resource group name, "vvvvvvvvvvvvvv" with your VM name and "ssssssssssssss" with the path of the script along with script name
For reference, you may refer the source from here.
Hope this helps!! Cheers!!

Related

Start-AzVM : Cannot bind parameter 'DefaultProfile' when running an Azure runbook

I am working on this official tutorial from MS Azure team to run a PowerShell Workflow runbook to start a VM. But when I start the following runbook (from step 6 of the tutorial), I get the error shown below. Question: What I may be missing, and how can we resolve the issue?
Remark: Start-AzVM is from Az.Compute module that I have already imported.
runbook code:
workflow MyFirstRunbook-Workflow
{
# Ensures that you do not inherit an AzContext in your runbook
Disable-AzContextAutosave –Scope Process
$Conn = Get-AutomationConnection -Name AzureRunAsConnection
Connect-AzAccount -ServicePrincipal -Tenant $Conn.TenantID -ApplicationId $Conn.ApplicationID -CertificateThumbprint $Conn.CertificateThumbprint
$AzureContext = Get-AzSubscription -SubscriptionId $Conn.SubscriptionID
Start-AzVM -Name 'vm-cs-web01' -ResourceGroupName 'rg-cs-ansible1' -AzContext $AzureContext
}
Error:
Start-AzVM : Cannot bind parameter 'DefaultProfile'. Cannot convert the "a76c7e8f-210d-45e5-8f5e-525015b1c881" value of
type "Deserialized.Microsoft.Azure.Commands.Profile.Models.PSAzureSubscription" to type
"Microsoft.Azure.Commands.Common.Authentication.Abstractions.Core.IAzureContextContainer".
At MyFirstRunbook-Workflow:11 char:11
+
+ CategoryInfo : InvalidArgument: (:) [Start-AzVM], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.Azure.Commands.Compute.StartAzureVMCommand
Looks like it is a mistake in the doc, in this scenario, it should use Set-AzContext to set the subscription instead of using Get-AzSubscription to get the subscription, change the command like below, it will work fine.
workflow MyFirstRunbook-Workflow
{
# Ensures that you do not inherit an AzContext in your runbook
Disable-AzContextAutosave –Scope Process
$Conn = Get-AutomationConnection -Name AzureRunAsConnection
Connect-AzAccount -ServicePrincipal -Tenant $Conn.TenantID -ApplicationId $Conn.ApplicationID -CertificateThumbprint $Conn.CertificateThumbprint
$AzureContext = Set-AzContext -SubscriptionId $Conn.SubscriptionID
Start-AzVM -Name 'vm-cs-web01' -ResourceGroupName 'rg-cs-ansible1' -AzContext $AzureContext
}

How to create automation schedule for Azure Automation Runbook from PowerShell to be run on Hybrid Worker?

I want to create automation schedule for Azure Automation Runbook from PowerShell. I don't want it to be run by default on Azure, but on Hybrid Worker, which is present in my Hybrid worker groups.
So I have that commands:
Import-AzureRmAutomationRunbook -Name $runbookName `
-Path $scriptPath `
-ResourceGroupName $automationResourceGroupName `
-AutomationAccountName $automationAccountName `
-Type PowerShellWorkflow
Publish-AzureRmAutomationRunbook -Name $runbookName `
-AutomationAccountName $automationAccountName `
-ResourceGroupName $automationResourceGroupName
New-AzureRmAutomationSchedule -Name $runbookName `
-AutomationAccountName $automationAccountName `
-StartTime $StartTime `
-ExpiryTime $EndTime `
-DayInterval 1 `
-ResourceGroupName $automationResourceGroupName
It can be done manually from the Azure portal:
but I need it to be done from PowerShell. I couldn't find it on MS docs.
If you are using the AzureRm module, just use the Start-AzureRmAutomationRunbook, specify the -RunOn parameter with the name of your Hybrid Worker group.
Start-AzureRmAutomationRunbook –AutomationAccountName "MyAutomationAccount" –Name "Test-Runbook" -RunOn "MyHybridGroup"
Reference(it uses the new Az command) - https://learn.microsoft.com/en-us/azure/automation/automation-hrw-run-runbooks#start-a-runbook-on-a-hybrid-runbook-worker
Update:
To schedule the runbook, you could use Register-AzureRmAutomationScheduledRunbook, specify the -RunOn parameter.
Register-AzureRmAutomationScheduledRunbook -AutomationAccountName "Contoso17" -Name "Runbk01" -ScheduleName "Sched01" -ResourceGroupName "ResourceGroup01" -RunOn "MyHybridGroup"

How to remove a storage account from Azure through Azure DevOps

When I run the Remove-AzureRmStorageAccount command in the Azure PowerShell task I get this error:
2019-01-24T13:07:29.0148404Z ==============================================================================
2019-01-24T13:07:29.0148533Z Task : Azure PowerShell
2019-01-24T13:07:29.0148602Z Description : Run a PowerShell script within an Azure environment
2019-01-24T13:07:29.0148688Z Version : 3.1.18
2019-01-24T13:07:29.0148847Z Author : Microsoft Corporation
2019-01-24T13:07:29.0148947Z Help : [More Information](https://go.microsoft.com/fwlink/?LinkID=613749)
2019-01-24T13:07:29.0149050Z ==============================================================================
2019-01-24T13:07:30.2233628Z ##[command]Import-Module -Name C:\Program Files\WindowsPowerShell\Modules\AzureRM\6.13.1\AzureRM.psd1 -Global
2019-01-24T13:07:42.1447157Z ##[command]Clear-AzureRmContext -Scope Process
2019-01-24T13:07:42.7204663Z ##[command]Disable-AzureRmContextAutosave -ErrorAction SilentlyContinue
2019-01-24T13:07:43.0466903Z ##[command]Add-AzureRMAccount -ServicePrincipal -Tenant *** -Credential System.Management.Automation.PSCredential -Environment AzureCloud #processScope
2019-01-24T13:07:44.1568578Z ##[command] Select-AzureRMSubscription -SubscriptionId XXXXX -TenantId ***
2019-01-24T13:07:44.5546953Z ##[command]& 'D:\a\_temp\XXXXX.ps1'
2019-01-24T13:07:44.6950579Z ##[command]Disconnect-AzureRmAccount -Scope Process
2019-01-24T13:07:45.1149833Z ##[command]Clear-AzureRmContext -Scope Process
2019-01-24T13:07:45.5569262Z ##[error]Windows PowerShell is in NonInteractive mode. Read and Prompt functionality is not available.
This is the script I run:
Remove-AzureRmStorageAccount `
-ResourceGroupName "myResourceGroupName" `
-AccountName "mystorageaccountname"
-Force
Note that I can create the storage account and the blob container in the same way without errors. This script works without any errors:
if(Get-AzureRmStorageAccountNameAvailability -Name "mystorageaccountname")
{
New-AzureRmStorageAccount `
-ResourceGroupName "myResourceGroupName" `
-AccountName "mystorageaccountname" `
-Location "West Europe" `
-SkuName "Standard_LRS"
New-AzureRmStorageContainer `
-ResourceGroupName "myResourceGroupName" `
-AccountName "mystorageaccountname" `
-ContainerName "my-blob-container" `
-PublicAccess "Blob"
}
How do I get the remove to work without errors through the Azure DevOps pipeline?
that happens because its asking to confirm deletion (##[error]Windows PowerShell is in NonInteractive mode. Read and Prompt functionality is not available), you are missing: `.
Remove-AzureRmStorageAccount `
-ResourceGroupName "myResourceGroupName" `
-AccountName "mystorageaccountname" ` <<<<< here
-Force
just retested it, it works without prompts if you supply -Force

How to create Azure Automation runbook that will start VM and then execute (local or Azure) script on the VM?

I wan't to create a Runbook that will start a specific (or parameter controlled) VM, and then run a script (locally or from blob storage) on the VM.
I have checked a lot of documentation, but so far without luck in getting it to work.
What I got so far under the same Resource Group:
VM created
Automation account created incl. Run As account
Azure Automation solution (OMS)
Credential (to my own account) under the automation account
Used several Runbook galleries and other code examples using functions as e.g.
Start-AzureVM ...
Invoke-Command ...
Anyone of you good people out there who can sample a guideline on what is needed depending on methods being used?
The VM start part is working, but I cannot get the login + executing of script to work!
I'm not a high skilled developer, and I have even doubts about choosing between the script languages in Azure.
Any help will be highly appreciated.
Thanks,
Tom
Invoke-Command
Invoke-AzureRmVMRunCommand
Set-AzureRmVMCustomScriptExtension
New-SSHSession + Invoke-SSHCommand
Code taken from e.g. gallary "Connect-AzureVM"
the parameter -ScriptPath of Invoke-AzureRmVMRunCommand should not point to the path in the remote computer, but should point to the local path of runbook environment.
Sample code like below(create a file named atestfile.txt in the remote vm):
$ServicePrincipalConnection = Get-AutomationConnection -Name 'AzureRunAsConnection'
Add-AzureRmAccount `
-ServicePrincipal `
-TenantId $ServicePrincipalConnection.TenantId `
-ApplicationId $ServicePrincipalConnection.ApplicationId `
-CertificateThumbprint $ServicePrincipalConnection.CertificateThumbprint
#define resource group and vm name
$resourceGroup ="xxx"
$VmName ="xxx"
#define the scripts in $scriptblock, and add the content of $scriptblock to aa.ps1 in current directory of runbook
write-output "create test file"
$scriptblock = "New-Item -path c:\test -name atestfile.txt -itemtype file -force"
Out-File -FilePath aa.ps1 -InputObject $scriptblock
#Note that the -ScriptPath should not point to the remote path(in remote vm), it should point to the local path where you execute the command Invoke-AzureRmVMRunCommand
Invoke-AzureRmVMRunCommand -ResourceGroupName $resourceGroup -Name $VmName -CommandId 'RunPowerShellScript' -ScriptPath aa.ps1
#after execution, you can remove the file
Remove-Item -Path aa.ps1
write-output "done now"
Test result:

checking the stopped VM's with different resources by Powershell script

How to check stopped virtual Machines with different resources by azure powershell script
iam tried to do that script please help me
To get status of the vm’s you can try the below script:
#login
Connect-AzureRmAccount
Select-AzureRmSubscription –SubscriptionName 'subscription-name'
Get-AzureRmVM -Status | Format-Table
If you want ResourceGroup group wise you try this script:
Connect-AzureRmAccount
Select-AzureRmSubscription –SubscriptionName 'subscription-name'
$RG = "ResourceGroupName"
$VM = "vmname"
$VMStats = (Get-AzureRmVM -Name $VM -ResourceGroupName $RG -Status).Statuses
($VMStats | Where Code -Like 'PowerState/*')[0].DisplayStatus

Resources