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

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
}

Related

Runbook automation fails but powershell cmd line works fine

I have the following powershell code for suspending azure d/w
$TenantId = "<>"
$SubscriptionId = "<>"
# Get the service principal credentials connected to the automation account.
$SPCredential = Get-AutomationPSCredential -Name "psvar"
# Login to Azure ($null is to prevent output, since Out-Null doesn't work in Azure)
Write-Output "Login to Azure using automation account 'psvar'."
$null = Login-AzureRmAccount -TenantId $TenantId -SubscriptionId $SubscriptionId -Credential $SPCredential
Write-Output "Login Status "
# Select the correct subscription
Write-Output "Selecting subscription '$($SubscriptionId)'."
$null = Select-AzureRmSubscription -SubscriptionID $SubscriptionId
$ResourceGroupName = '<>'
$ServerName = '<>'
$DatabaseName = '<>'
Write-Output "Suspending $($DatabaseName)..."
$null = Suspend-AzureRmSqlDatabase `
-ResourceGroupName $ResourceGroupName`
-DatabaseName $DatabaseName`
-ServerName $ServerName
Write-Output "Done"
Suspend azure rm sqldatabase works fine in PowerShell Azure Command line interface
But in runbook automation it fails with
Suspend-AzureRmSqlDatabase : Run Login-AzureRmAccount to login.
At line:33 char:9
+ $null = Suspend-AzureRmSqlDatabase `
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Suspend-AzureRmSqlDatabase], PSInvalidOperationException
+ FullyQualifiedErrorId :
InvalidOperation,Microsoft.Azure.Commands.Sql.DatabaseActivation.Cmdlet.SuspendAzureSqlDatabase
Any idea what could be wrong. Appreciate any pointers regarding this
I test your script, it works in the runbook.
Navigate to the automation account -> Credentials, make sure your user account name and password are correct.
If it still not work, you could try my solution here, it works.
For Azure Synapse analytics we need to use
Update-AzSynapseSqlPool -WorkspaceName <wsname>-Name <dbname> -Pause

Azure runbook - run Powershell on remote VM

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!!

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

Select-AzureRmSubscription : Please provide a valid tenant or a valid subscription

I have created the Powershell Runbook, and added all the required details and valid values. Still I am facing the error for Select-AzureRmSubscription command. The error I am getting all the time is
Select-AzureRmSubscription : Please provide a valid tenant or a valid subscription.
I am using below connection setting in Powershell runbook:
$connectionName = "AzureRunAsConnection"
try
{
# Get the connection "AzureRunAsConnection "
$servicePrincipalConnection=Get-AutomationConnection -Name $connectionName
"Logging in to Azure..."
Add-AzureRmAccount -ServicePrincipal -TenantId $servicePrincipalConnection.TenantId -ApplicationId
$servicePrincipalConnection.ApplicationId -CertificateThumbprint
$servicePrincipalConnection.CertificateThumbprint
}
catch {
if (!$servicePrincipalConnection)
{
$ErrorMessage = "Connection
$connectionName not found."
throw $ErrorMessage
} else{
Write-Error -Message $_.Exception
throw $_.Exception
}
}
fetch-group-memberships | Select-Object UserName, PrincipalName, GroupName, AzureGroupName |Sort-Object GroupName| Export-Csv -NoTypeInformation -Path
'MEMBERSHIP.csv'
#=======================================================================================
# Select the subscription you are going to work with
#=======================================================================================
Select-AzureRmSubscription -SubscriptionId
"[removed for security purpose]"
#Get-AzureRmSubscription -SubscriptionName "BIG" | Select-AzureRmSubscription
#=======================================================================================
# Set the Current Storage Account to the approperiate location
#=======================================================================================
Set-AzureRmCurrentStorageAccount -StorageAccountName devapacbi01 -ResourceGroupName dev-rgp-apac-01
#=======================================================================================
# Capture the file that is local to automation and save to Storage Blob
#=======================================================================================
Set-AzureStorageBlobContent -Container bi-app-carm-im -File ADGROUP_MEMBERSHIP.csv -Blob _MEMBERSHIP_AL.csv -Force
Even if the subscription id is correct it keeps throwing an error as above.
this means you do not have permissions to do so. you need to assign proper permissions to the account you are using for the runbook
You do not need to Select-AzureRmSubscription because runbook connection is only tied to on subscription.
Also keep in mid the runbook is running on a environment setup to run your script, I prefer to stay away from Set environment commands.
Removing the subscription line and fixing lines below should work.
$storageAccount = Get-AzureRmStorageAccount -StorageAccountName devapacbi01 -ResourceGroupName dev-rgp-apac-01
Set-AzureStorageBlobContent -Container bi-app-carm-im -File ADGROUP_MEMBERSHIP.csv -Blob _MEMBERSHIP_AL.csv -Context $storageAccount.Context -Force
Hope this helps.
Its Solved! You guys were correct, it was an issue with correct permissions with Automation Account only. We should have a access as a contributor on your storage account. After giving right permissions to automation RunAs (contributor on your storage account) it worked and ran successfully. Than you all again.

Azure search Powershell deployment issue

We have set up for over a year automated deployment to azure to do different steps. which has been working great last week one specific step has been failing. It is setting the partition size based on a variable.
this is the PS Code:
$secpasswd = ConvertTo-SecureString $OctopusParameters["AzureSearch.Admin.Password"] -AsPlainText -Force
$creds = New-Object System.Management.Automation.PSCredential ($OctopusParameters["AzureSearch.Admin.User"], $secpasswd)
Add-AzureRmAccount -Credential $creds
$Resource = Get-AzureRmResource -ResourceType "Microsoft.Search/searchServices" -ResourceGroupName $OctopusParameters["Azure.ResourceGroup"] -ResourceName $OctopusParameters["AzureSearch.SearchServiceName"]
$Resource.Properties.partitionCount = $OctopusParameters["AzureSearch.PartitionCount"]
$Resource | Set-AzureRmResource -Force
this is what the error message is now:
$Resource = Get-AzureRmResource -ResourceType "Microsoft.Search/searc ...
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CategoryInfo : CloseError: (:) [Get-AzureRmResource], ErrorResponseMessageException
FullyQualifiedErrorId : DisallowedOperation,Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation.GetAzureResourceCmdlet
is there some changes in Azure that caused this as of last week?
Not sure about the error, but you could use this command Set-AzureRmSearchService to set PartitionCount.
Note: You need to install AzureRM.Search powershell module, run this command Install-Module -Name AzureRM.Search -AllowPrerelease as admin in your powershell, more details see this link.
Command sample:
Set-AzureRmSearchService -ResourceGroupName "<ResourceGroupName>" -Name "<AzureSearchName>" -PartitionCount 2 -ReplicaCount 2
Result:

Resources