Search code examples
azurepowershellazure-devopsazure-sql-databaseaz

Run Powershell commands on Azure Function with az template


I would like to write a script which pulls Azure SQL database into Azure SQL Elastic Pool. But that should be running from Azure Function

But got this error: ERROR: The specified module 'AzureRM.Compute' was not loaded because no valid module file was found in any module directory.

When I included Azure RM, I'm getting a new error as I cannot use AzureRM and Az commands.

Can I use only AZ commands to connect to my desired subscription?

Following is the code I'm trying:

$resourceGroupName = "<VALUE>"
$location = "<VALUE>"
$PoolName = "<VALUE>"
$adminSqlLogin = "<VALUE>"
$password = "<VALUE>"
$serverName = "<VALUE>.database.windows.net,1433"
$DatabaseName = "<VALUE>"

Set-ExecutionPolicy Unrestricted -Scope CurrentUser


Import-Module Az.Sql

$azureAccountName ="<VALUE>"
$azurePassword = "<VALUE>" | ConvertTo-SecureString -AsPlainText -Force

$psCred = New-Object System.Management.Automation.PSCredential($azureAccountName, $azurePassword)

Login-AzureRmAccount -Credential $psCred -SubscriptionId $subscriptionId

Set-AzSqlDatabase -ResourceGroupName $resourceGroupName `
    -ServerName $serverName `
    -DatabaseName $DatabaseName `
    -ElasticPoolName $PoolName

But getting following error in Azure Function:

Login-AzureRmAccount : Method 'get_SerializationSettings' in type 'Microsoft.Azure.Management.Internal.Resources.ResourceManagementClient' from assembly 'Microsoft.Azure.Commands.ResourceManager.Common, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' does not have an implementation.


Solution

  • You shouldn't mix AZ and ARM cmdlets. I would recommend you to use the new AZ cmdlets only. If you use Managed Identity within your Azure Function, you don't even have to manually connect to your Azure Account since this is already done for you in the profile.ps1:

    if ($env:MSI_SECRET -and (Get-Module -ListAvailable Az.Accounts)) {
        Connect-AzAccount -Identity
    }
    

    Just ensure you add Az to the requirements.psd1:

    @{
        Az = '1.*'
    }