i've been tasked with migrating some PowerShell scripts from AzureRM to azure cli. We have some deep resources that get set on App Services to enable complex logging.
This AzureRM script works fine. Even the Get-AzureRmResouce call works, but the azure cli does not and even the REST api call does not. I get a Resource not found error.
this code works:
New-AzureRmResource -ResourceGroupName $ResourceGroupName `
-ResourceName ($AppName + "/AntMDS/" + $SettingName) `
-ResourceType "Microsoft.Web/serverfarms/firstPartyApps/settings" `
-Properties $SettingProperties `
-ApiVersion 2015-08-01 -Force | Out-Null
this code does not:
$temp = New-TemporaryFile
$SettingProperties | ConvertTo-Json | Out-File $temp.FullName
$result = az resource create --resource-group $ResourceGroupName `
--name "$AppName/AntMDS/$SettingName" `
--resource-type "Microsoft.Web/serverfarms/firstPartyApps/settings" `
--properties "#$($temp.FullName)" `
--api-version "2015-08-01" `
| ConvertFrom-Json
if(-not $result) {
throw "Unable to create resource: ""$AppName/AntMDS/$SettingName"" on group $ResourceGroupName"
}
Remove-Item $temp
says "Resource not found"
Related
I try to setup and deploy Azure Function by using PowerShell script based on this topic: Setup Azure Function from PowerShell
My script looks like this:
#=============Defining All Variables=========
$location = 'Central US'
$resourceGroupName = 'MyResourceGroup'
$subscriptionId = 'MysubscriptionId'
$functionAppName = 'MyfunctionAppName'
$appServicePlanName = 'ASP-test-8b50'
$tier = 'Dynamic'
$archivePath = 'd:\TestAzureFunc.zip'
Connect-AzAccount
#========Creating Azure Resource Group========
$resourceGroup = Get-AzResourceGroup | Where-Object { $_.ResourceGroupName -eq $resourceGroupName }
if ($resourceGroup -eq $null)
{
New-AzResourceGroup -Name $resourceGroupName -Location $location -force
}
#selecting default azure subscription by name
Select-AzSubscription -SubscriptionID $subscriptionId
Set-AzContext $subscriptionId
#========Creating App Service Plan============
New-AzAppServicePlan -ResourceGroupName $resourceGroupName -Name $appServicePlanName -Location $location -Tier $tier
$functionAppSettings = #{
ServerFarmId="/subscriptions/$subscriptionId/resourceGroups/$resourceGroupName/providers/Microsoft.Web/serverfarms/$appServicePlanName";
alwaysOn=$True;
}
#========Creating Azure Function========
$functionAppResource = Get-AzResource | Where-Object { $_.ResourceName -eq $functionAppName -And $_.ResourceType -eq "Microsoft.Web/Sites" }
if ($functionAppResource -eq $null)
{
New-AzResource -ResourceType 'Microsoft.Web/Sites' -ResourceName $functionAppName -kind 'functionapp' -Location $location -ResourceGroupName $resourceGroupName -Properties $functionAppSettings -force
}
#========Defining Azure Function Settings========
$AppSettings =#{}
$AppSettings =#{'FUNCTIONS_EXTENSION_VERSION' = '~2';
'FUNCTIONS_WORKER_RUNTIME' = 'dotnet';}
Set-AzWebApp -Name $functionAppName -ResourceGroupName $resourceGroupName -AppSettings $AppSettings
#========Deploy Azure Function from zip========
Publish-AzWebapp -ResourceGroupName $resourceGroupName -Name $functionAppName -ArchivePath $archivePath
The script works without errors. Resource group and Function App created as needed. But the list of functions of the Function App is empty.
Function details here:
My intuition tells me that I've forgotten something. But I don't know what.
Could you advise me on how to deploy my Azure function properly?
One of the workaround you can follow ,
Looking at your script we need to ensure that we are providing function app configuration as below cmdlts the link you followed:-
$AzFunctionAppSettings = #{
APPINSIGHTS_INSTRUMENTATIONKEY = $AppInsightsKey;
AzureWebJobsDashboard = $AzFunctionAppStorageAccountConnectionString;
AzureWebJobsStorage = $AzFunctionAppStorageAccountConnectionString;
FUNCTIONS_EXTENSION_VERSION = "~4";
FUNCTIONS_WORKER_RUNTIME = "dotnet";
}
And also make sure that the storage account connection string you provided in the function is same as here providing.
And then you can navigate to Kudu API to check the wwwroot folder is exist or not.
For more information please refer the below links:-
SO THREAD|Powershell command Publish-AzWebApp not publishing apllication
BLOG|How to Deploy Azure Function Apps With Powershell.
I'm trying to update an existing version in a versionset inside an Azure API Management service with a new specification using Azure CLI.
I know it does support importing it as an API without a versionset:
az apim api import `
--path "/as" `
--resource-group "myResourceGroup" `
--service-name "test-apim" `
--api-id "test-apim" `
--specification-format "OpenApiJson" `
--specification-path "..\swagger.json"
And I also know that you can use the Azure Powershell modules to fetch a version set and use this to upload a new specification:
$apiMgmtContext = New-AzApiManagementContext `
-ResourceGroupName "myResourceGroup" `
-ServiceName "test-apim"
$versionSet = Get-AzApiManagementApiVersionSet -Context $apiMgmtContext |
Where-Object { $_.DisplayName -eq "my-version-set" } |
Sort-Object -Property ApiVersionSetId -Descending |
Select-Object -first 1
Import-AzApiManagementApi `
-Context $apiMgmtContext `
-ApiVersionSetId $versionSet.ApiVersionSetId `
-ServiceUrl "http" `
-SpecificationFormat "OpenApiJson" `
-SpecificationPath "..\swagger.json" `
-Path "/as" `
-ApiId "test-apim"
But does anyone know if this can be done with the az cli as the powershell modules will eventually become obsolete?
Looking at the documentation, it supports version set.
You need to use the parameter --api-version-set-id:
az apim api import `
--path "/as" `
--resource-group "myResourceGroup" `
--service-name "test-apim" `
--api-id "test-apim" `
--specification-format "OpenApiJson" `
--specification-path "..\swagger.json" `
--api-version-set-id "my-version-set-id"
Also there is no indication that Az Powershell will become obsolete for the moment.
I can able to connect the Azure VM to the log analytics workspace using the ARM template(https://learn.microsoft.com/en-us/azure/azure-monitor/agents/resource-manager-agent) but I want to connect the multiple VMs at a time in one subscription and different resource groups to the log analytics workspace.
Is there any way to work around this?
If you want to add a bunch of VMs in a subscription to a log analytics workspace in Azure, we can use PowerShell command Set-AzVMExtension to implement it.
For example
# all windows VMs in the subscription (which you set via Set-AzContext)
$PublicSettings = #{ "workspaceId" = "" }
$ProtectedSettings = #{ "workspaceKey" = "" }
# Using -Status switch to get the status too
Get-AzVM -Status | Where-Object{ $_.Powerstate -eq "VM running" -and $_.StorageProfile.OsDisk.OsType -eq "Windows" } | ForEach-Object {
$VMName = $_.Name
$ResourceGroupName = $_.ResourceGroupName
$Location = $_.Location
Write-Host "Processing $VMName"
Set-AzVMExtension -ExtensionName "MicrosoftMonitoringAgent" `
-ResourceGroupName "$ResourceGroupName" `
-VMName "$VMName" `
-Publisher "Microsoft.EnterpriseCloud.Monitoring" `
-ExtensionType "MicrosoftMonitoringAgent" `
-TypeHandlerVersion 1.0 `
-Settings $PublicSettings `
-ProtectedSettings $ProtectedSettings `
-Location "$Location"
}
For more details, please refer to here and here.
I'm trying to set a Tag on all virtual machines in my subscription but I keep getting errors when running the Runbook.
The error is the following:
Get-AzureRmVM : Cannot process command because of one or more missing mandatory parameters: ResourceGroupName. At line:30
Here is my Runbook:
$azureConnection = Get-AutomationConnection -Name 'AzureRunAsConnection'
#Authenticate
try {
Clear-Variable -Name params -Force -ErrorAction Ignore
$params = #{
ServicePrincipal = $true
Tenant = $azureConnection.TenantID
ApplicationId = $azureConnection.ApplicationID
CertificateThumbprint = $azureConnection.CertificateThumbprint
}
$null = Add-AzureRmAccount #params
}
catch {
$errorMessage = $_
Throw "Unable to authenticate with error: $errorMessage"
}
# Discovery of all Azure VM's in the current subscription.
$azurevms = Get-AzureRmVM | Select-Object -ExpandProperty Name
Write-Host "Discovering Azure VM's in the following subscription $SubscriptionID Please hold...."
Write-Host "The following VM's have been discovered in subscription $SubscriptionID"
$azurevms
foreach ($azurevm in $azurevms) {
Write-Host "Checking for tag $vmtagname on $azurevm"
$tagRGname = Get-AzureRmVM -Name $azurevm | Select-Object -ExpandProperty ResourceGroupName
$tags = (Get-AzureRmResource -ResourceGroupName $tagRGname -Name $azurevm).Tags
If ($tags.UpdateWindow){
Write-Host "$azurevm already has the tag $vmtagname."
}
else
{
Write-Host "Creating Tag $vmtagname and Value $tagvalue for $azurevm"
$tags.Add($vmtagname,$tagvalue)
Set-AzureRmResource -ResourceGroupName $tagRGname -ResourceName $azurevm -ResourceType Microsoft.Compute/virtualMachines -Tag $tags -Force `
}
}
Write-Host "All tagging is done"
I tried importing the right modules but this doesn't seem to affect the outcome.
Running the same commands in Cloud Shell does work correctly.
I can reproduce your issue, the error was caused by this part Get-AzureRmVM -Name $azurevm, when running this command, the -ResourceGroupName is needed.
You need to use the Az command Get-AzVM -Name $azurevm, it will work.
Running the same commands in Cloud Shell does work correctly.
In Cloud shell, azure essentially uses the new Az module to run your command, you can understand it runs the Enable-AzureRmAlias before the command, you could check that via debug mode.
Get-AzureRmVM -Name joyWindowsVM -debug
To solve your issue completely, I recommend you to use the new Az module, because the AzureRM module was deprecated and will not be updated.
Please follow the steps below.
1.Navigate to your automation account in the portal -> Modules, check if you have imported the modules Az.Accounts, Az.Compute, Az.Resources, if not, go to Browse Gallery -> search and import them.
2.After import successfully, change your script to the one like below, then it should work fine.
$azureConnection = Get-AutomationConnection -Name 'AzureRunAsConnection'
#Authenticate
try {
Clear-Variable -Name params -Force -ErrorAction Ignore
$params = #{
ServicePrincipal = $true
Tenant = $azureConnection.TenantID
ApplicationId = $azureConnection.ApplicationID
CertificateThumbprint = $azureConnection.CertificateThumbprint
}
$null = Connect-AzAccount #params
}
catch {
$errorMessage = $_
Throw "Unable to authenticate with error: $errorMessage"
}
# Discovery of all Azure VM's in the current subscription.
$azurevms = Get-AzVM | Select-Object -ExpandProperty Name
Write-Host "Discovering Azure VM's in the following subscription $SubscriptionID Please hold...."
Write-Host "The following VM's have been discovered in subscription $SubscriptionID"
$azurevms
foreach ($azurevm in $azurevms) {
Write-Host "Checking for tag $vmtagname on $azurevm"
$tagRGname = Get-AzVM -Name $azurevm | Select-Object -ExpandProperty ResourceGroupName
$tags = (Get-AzResource -ResourceGroupName $tagRGname -Name $azurevm).Tags
If ($tags.UpdateWindow){
Write-Host "$azurevm already has the tag $vmtagname."
}
else
{
Write-Host "Creating Tag $vmtagname and Value $tagvalue for $azurevm"
$tags.Add($vmtagname,$tagvalue)
Set-AzResource -ResourceGroupName $tagRGname -ResourceName $azurevm -ResourceType Microsoft.Compute/virtualMachines -Tag $tags -Force `
}
}
Write-Host "All tagging is done"
I am trying to scale the CosmosDB Container using Powershell but couldn't find anything in the docs. I tried the following script which didn't work.
$resourceName = $CosmosDB + "/sql/" + $CosmosDatabase + "/" + $CosmosContainer
$ContainerProperties = #{
"resource"=#{
"id"=$CosmosContainer;
"partitionKey"=#{
"paths"=#("/DefaultKey");
"kind"="Hash"
}
};
"options"=#{ "Throughput"=$CosmosScale }
}
Set-AzResource -ResourceType "Microsoft.DocumentDb/databaseAccounts/apis/databases/containers" -ApiVersion "2015-04-08" -ResourceGroupName $resourceGroup -Name $resourceName -PropertyObject $ContainerProperties -Force
Any insights are appreciated.
Here is a PS script that will update throughput on either a database or container for a SQL (Core) API account.
# Update RU for an Azure Cosmos DB SQL (Core) API database or container
$resourceGroupName = "myResourceGroup"
$accountName = "mycosmosaccount"
$databaseName = "database1"
$containerName = "container1"
$databaseResourceName = $accountName + "/sql/" + $databaseName + "/throughput"
$containerResourceName = $accountName + "/sql/" + $databaseName + "/" + $containerName + "/throughput"
$throughput = 500
$updateResource = "database" # or "container"
$properties = #{
"resource"=#{"throughput"=$throughput}
}
if($updateResource -eq "database"){
Set-AzResource -ResourceType "Microsoft.DocumentDb/databaseAccounts/apis/databases/settings" `
-ApiVersion "2015-04-08" -ResourceGroupName $resourceGroupName `
-Name $databaseResourceName -PropertyObject $properties
}
elseif($updateResource -eq "container"){
Set-AzResource -ResourceType "Microsoft.DocumentDb/databaseAccounts/apis/databases/containers/settings" `
-ApiVersion "2015-04-08" -ResourceGroupName $resourceGroupName `
-Name $containerResourceName -PropertyObject $properties
}
else {
Write-Host("Must select database or container")
}
I have used this to update the Azure CosmosDb (SQL API) Collections on automation account but which gets timed Out with the cmdlet Set-AzResource - sometimes it works
Get-AzResource -ResourceType Microsoft.DocumentDB/databaseAccounts
$containerResourceType = "Microsoft.DocumentDb/databaseAccounts/apis/databases/containers/settings"
Using Set command with API Version in Runbook which got failed with ‘Operation failed because a request timed out.’
Set-AzResource -ResourceType $containerResourceType ***
Reference:
https://serverfault.com/questions/967942/scaling-cosmosdb-container-using-powershell