Azure: create a new API Management service without a service URL - azure

My intent is to configure an API (e.g. an Azure Function) into an API Manegement service using only policies. I don't want to specify a Service URL.
This is possible using Portal UI:
but not using PowerShell Az module.
Following code:
New-AzApiManagementApi -Context $context -Name $fullName -Protocols #('https') `
-Path $path -ProductIds #($product) `
-ApiVersionSetId $apiMgmtVersion.ApiVersionSetId
raises this exception:
Error : Unable to create 'news' managed API version 1.
Cannot validate argument on parameter 'ServiceUrl'. The argument is null or empty. Provide an argument that is not null or empty, and then try the
command again.
At C:\Projects\Intranet.ai\component_tools\Install-ApiMgmt.ps1:105 char:76
+ ... able to create '$fullName' managed API version $version.`n$_" | Error
+ ~~~~~
+ CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException
+ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Error
Is there a way to define an API without a service URL? Maybe using directly New-AzResource?
Thanks to anyone who will help!

Is there a way to define an API without a service URL? Maybe using directly New-AzResource?
The New-AzApiManagementApi seems not support that, you could use the New-AzResource directly, please try the sample below, it works on my side.
$PropertiesObject = #{
"name" = "test22"
"serviceUrl" = $null
"path" = "testaaa"
"protocols" = #("https")
}
New-AzResource -PropertyObject $PropertiesObject -ResourceGroupName <Group-name> -ResourceType Microsoft.ApiManagement/service/apis -ResourceName "<API-management-servie-name>/test22" -ApiVersion 2018-01-01 -Force
Check in the portal:
Update:
If you want to include the apiVersionSetId, please try the one below.
$versionSet = Get-AzApiManagementApiVersionSet -Context $context -ApiVersionSetId "d41e7f92-9cf8-48fb-8552-d9ae5d4690d3"
$Id = $versionSet.Id -replace "apiVersionSets","api-version-sets"
$PropertiesObject = #{
"name" = "test22"
"serviceUrl" = $null
"path" = "testaaa"
"protocols" = #("https")
"apiVersionSetId" = $Id
}
New-AzResource -PropertyObject $PropertiesObject -ResourceGroupName <Group-name> -ResourceType Microsoft.ApiManagement/service/apis -ResourceName "<API-management-servie-name>/test22" -ApiVersion 2018-01-01 -Force

Related

Azure Powershell Script Force FTPS Set-AzWebApp : Cannot convert 'System.Object[]' to the type 'System.String' required by parameter

I am currently trying to run a script in Azure that would go through all of our Web Apps and turn on FTPS.
This is what I currently have
$Subscriptions = Get-AzSubscription
foreach ($sub in $Subscriptions) {
Get-AzSubscription -SubscriptionName $sub.Name | Set-AzContext
$GetName = (Get-AzWebApp).Name
$GetRG = (Get-AzWebApp).ResourceGroup
Set-AzWebapp -Name $GetName -ResourceGroupName $GetRG -FtpsState FtpsOnly
}
Set-AzWebApp : Cannot convert 'System.Object[]' to the type 'System.String' required by parameter 'Name'. Specified
method is not supported.
I currently am getting this error, which I dont understand as .Name and .ResourceGroup, from my understanding are already strings. I am very new to powershell so any help would be greatly appreciated. Thanks everyone!
Your example calls Az-WebApp with no parameters, which gets all apps in the subscription - this is a collection - and then tries to get the Name of that result, which is what causes your error.
You need to loop through each app in the subscription as well as looping through each subscription, as in:
# Get all subscriptions and iterate them
Get-AzSubscription | ForEach-Object {
Set-AzContext -SubscriptionName $_.Name
# Get all web apps in the subscription and iterate them
Get-AzWebApp | ForEach-Object {
Set-AzWebApp -Name $_.Name -ResourceGroupName $_.ResourceGroup -FtpsState FtpsOnly
}
}

How to add event subscription to Azure storage using New-AzEventGridSubscription?

I am trying to add subscription to storage account using New-AzEventGridSubscription. The subscription should be triggered by blob modification in a container and put message to a certain queue. I created the following script:
$ResourceGroup = "test"
$includedEventTypes = "Microsoft.Storage.BlobCreated", "Microsoft.Storage.BlobDeleted"
New-AzEventGridSubscription `
-ResourceId "/subscriptions/[id]/resourceGroups/[group]/providers/Microsoft.Storage/storageAccounts/[name]" `
-EventSubscriptionName DummyName `
-Endpoint "/subscriptions/[id]/resourceGroups/[group]/providers/Microsoft.Storage/storageAccounts/[name]/queueServices/default/queues/my-queue" `
-ResourceGroup $ResourceGroup `
-EndpointType "storagequeue" `
-SubjectBeginsWith "prefix" `
-SubjectEndsWith "suffix"
but it throws an error:
New-AzEventGridSubscription : Parameter set cannot be resolved using the specified named parameters.
At line:1 char:1
+ New-AzEventGridSubscription `
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [New-AzEventGridSubscription], ParameterBindingException
+ FullyQualifiedErrorId : AmbiguousParameterSet,Microsoft.Azure.Commands.EventGrid.NewAzureEventGridSubscription
I made similar command to add subscription to a custom topic, which worked well:
New-AzEventGridSubscription `
-ResourceGroup $ResourceGroup `
-EventSubscriptionName SubscriptionName `
-TopicName MyCustomTopic `
-EndpointType "storagequeue" `
-Endpoint "/subscriptions/[id]/resourceGroups/[group]/providers/Microsoft.Storage/storageAccounts/[account]/queueServices/default/queues/my-queue" `
-SubjectBeginsWith "prefix" `
-SubjectEndsWith "suffix"
I tried several modifications, but to no avail. What am I doing wrong?
After throwing out "ResourceGroup" parameter, reordering other parameters, and putting some arguments into variables, I finally managed to get my script up and running... If anyone ever needs similar stuff, here it is:
$subscriptionId = "<id>"
$ResourceGroup = "<group>"
$includedEventTypes = "Microsoft.Storage.BlobCreated", "Microsoft.Storage.BlobDeleted"
$storageAccount = "<account name>"
$endpoint = "/subscriptions/"+$subscriptionId+"/resourceGroups/"+$ResourceGroup+"/providers/Microsoft.Storage/storageAccounts/"+$storageAccount+"/queueServices/default/queues/my-queue"
$resourceId = "/subscriptions/"+$subscriptionId+"/resourceGroups/"+$ResourceGroup+"/providers/Microsoft.Storage/storageAccounts/"+$storageAccount
$subject = "prefix"
New-AzEventGridSubscription `
-EventSubscriptionName MySubscriptionName `
-Endpoint $endpoint `
-ResourceId $resourceId `
-EndpointType "storagequeue" `
-SubjectBeginsWith $subject `
-SubjectEndsWith "suffix" `
-IncludedEventType $includedEventTypes

Set-AzVMCustomScriptExtension in catch?

Attempting to add an extension when not detected but keep failing to find the secret sauce to get this to work. Mind you I am a BASH guy and this is a first foray into PowerShell..
#requires -version 2
# Required parameter $subscription: name of the subscription to enable Custom Script Extensions in
param (
# NOTE: See below for reason...
# [Parameter(Mandatory = $true)] [String] $subscription
# NOTE: Prompting is great for using the script interactively, but if this will also be executed
# from a build server or ...
# NOTE: Once the parameter is marked as mandatory PowerShell it will prompt for value. That said,
# if you remove the mandatory attribute then you can set a default value as a T_THROW ...
# NOTE: This _does_ contain shortcomings if this will be used as a pipeline param ...
# https://stackoverflow.com/questions/33600279/is-it-possible-to-force-powershell-script-to-throw-if-a-required-pipeline-para
[Parameter()]
[ValidateNotNullOrEmpty()]
[String]$SubscriptionName=$(Throw "`SubscriptionName` is mandatory, please provide a value...")
)
# Connect to the current Azure account
Write-Output "Pulling Azure account credentials..."
Start-Process "https://microsoft.com/devicelogin" # steals focus...
# Login to Azure account
Connect-AzAccount
# Set the active subscription
$null = Get-AzSubscription -SubscriptionName "$SubscriptionName" |Set-AzContext
# TODO: error handling
$vms = Get-AzVM
$cseName = "VulnerabilityManagementTools"
ForEach ($vm in $vms) {
try {
$cseStatus = Get-AzVMCustomScriptExtension `
-ResourceGroupName $vm.ResourceGroupName `
-VMName $vm.Name `
-Name $cseName `
-Status
}
catch {
Write-Output "Enabling Custom Script Extension for $vm."
Set-AzVMCustomScriptExtension `
-ResourceGroupName $vm.ResourceGroup `
-Location $vm.Location `
-VMName $vm.Name `
-Name $cseName `
-TypeHandlerVersion "1.1" `
-StorageAccountName "VulnerabilityManagementTools" `
-FileName "VulnerabilityManagementInstaller.ps1" `
-ContainerName "VulnerabilityManagementTools"
}
}
End up err'ing out with
PS /.../automation-scripts> ./EnableCustomScriptExtension.ps1 SubscriptionName
Pulling Azure account credentials...
WARNING: To sign in, use a web browser to open the page https://microsoft.com/devicelogin and enter the code XXXXXX to authenticate.
Account SubscriptionName TenantId Environment
------- ---------------- -------- -----------
XXXX#analytics.com SubName XXXXXX-XXXX AzureCloud
Get-AzVMCustomScriptExtension : The Resource 'Microsoft.Compute/virtualMachines/XXXX/extensions/VulnerabilityManagementTools' under resource group '{NAME}' was not found.
ErrorCode: ResourceNotFound
ErrorMessage: The Resource 'Microsoft.Compute/virtualMachines/XXXX/extensions/VulnerabilityManagementTools' under resource group '{NAME}' was not found.
ErrorTarget:
StatusCode: 404
ReasonPhrase: Not Found
At /.../automation-scripts/EnableCustomScriptExtension.ps1:59 char:18
+ $cseStatus = Get-AzVMCustomScriptExtension `
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [Get-AzVMCustomScriptExtension], ComputeCloudException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.Compute.GetAzureVMCustomScriptExtensionCommand
Get-AzVMCustomScriptExtension : The Resource 'Microsoft.Compute/virtualMachines/XXXXX/extensions/VulnerabilityManagementTools' under resource group '{RESOURCE_GROUPNAME}' was not found.
ErrorCode: ResourceNotFound
ErrorMessage: The Resource 'Microsoft.Compute/virtualMachines/XXXX/extensions/VulnerabilityManagementTools' under resource group '{RESOURCE_GROUPNAME}' was not found.
ErrorTarget:
StatusCode: 404
ReasonPhrase: Not Found
At /.../automation-scripts/EnableCustomScriptExtension.ps1:59 char:18
+ $cseStatus = Get-AzVMCustomScriptExtension `
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [Get-AzVMCustomScriptExtension], ComputeCloudException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.Compute.GetAzureVMCustomScriptExtensionCommand
Get-AzVMCustomScriptExtension : The Resource 'Microsoft.Compute/virtualMachines/{VMName}/extensions/VulnerabilityManagementTools' under resource group '{RESOURCEX_GROUPNAME}' was not found.
ErrorCode: ResourceNotFound
ErrorMessage: The Resource 'Microsoft.Compute/virtualMachines/{VMName}/extensions/VulnerabilityManagementTools' under resource group '{RESOURCEX_GROUPNAME}' was not found.
ErrorTarget:
StatusCode: 404
ReasonPhrase: Not Found
At /.../automation-scripts/EnableCustomScriptExtension.ps1:59 char:18
+ $cseStatus = Get-AzVMCustomScriptExtension `
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [Get-AzVMCustomScriptExtension], ComputeCloudException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.Compute.GetAzureVMCustomScriptExtensionCommand`
In your case, you just need to use the if(){}else{} statement, try the script as below instead of the ForEach part of yours, it works fine on my side.
ForEach ($vm in $vms) {
$cseStatus = Get-AzVMCustomScriptExtension `
-ResourceGroupName $vm.ResourceGroupName `
-VMName $vm.Name `
-Name $cseName `
-Status `
-ErrorAction SilentlyContinue
if ($cseStatus){
Write-Host "The extension has been set for" $vm.Name
}else{
Write-Host "Enabling Custom Script Extension for" $vm.Name
Set-AzVMCustomScriptExtension `
-ResourceGroupName $vm.ResourceGroup `
-Location $vm.Location `
-VMName $vm.Name `
-Name $cseName `
-TypeHandlerVersion "1.1" `
-StorageAccountName "VulnerabilityManagementTools" `
-FileName "VulnerabilityManagementInstaller.ps1" `
-ContainerName "VulnerabilityManagementTools"
}
}
Test result:
You'll need to create an Azure AD Service Principal using password authentication and use the credentials of this to pass to the Connect-AzAccount cmdlet as follows:
$credentials = Get-Credential
Connect-AzAccount -ServicePrincipal -Credentials $credentials
The service account will need to have the necessary permissions to use the Set-AzVMCustomScriptExtensions cmdlet.
More information on creating the service account here:
https://learn.microsoft.com/en-us/powershell/azure/create-azure-service-principal-azureps?view=azps-2.8.0

Why isn't VScode pwsh terminal able to see my azure resource groups?

I'm trying to tag all my running VMs from azure with tags from a CSV file but my PowerShell script is failing when being run from VSCode PowerShell core terminal.
I double-checked and I have set the correct active subscription (we have multiple tenants and subscriptions), but the output says that it can't find my resource groups (they are there for sure).
Enable-AzureRmAlias
$csv = import-csv "C:\Users\popes\Desktop\Jedox\Powershell scripts\Tagging\Tagging.csv"
$csv | ForEach-Object {
# Retrieve existing tags
$tags = (Get-AzResource -ResourceGroupName $_.RG -ResourceType "Microsoft.Compute/virtualMachines" -Name $_.VM).Tags
# Define new value pairs from CSV
$newTags = #{
company = $_.Company
dns = $_.DNS
type = $_.Type
CN = $_.CN
}
# Add new tags to existing set (overwrite conflicting tag names)
foreach($CN in $newTags.Keys){
$tags[$_] = $newTags[$_]
}
# Update resource with new tag set
Set-AzResource -ResourceGroupName $_.RG -Name $_.VM -Tag $tags -ResourceType "Microsoft.Compute/virtualMachines"
}
The output:
Get-AzResource : Resource group 'machine774_rg' could not be found.
At line:3 char:14
+ ... $tags = (Get-AzResource -ResourceGroupName $_.RG -ResourceType "Mi ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [Get-AzResource], CloudException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation.GetAzureResourceCmdlet
Cannot index into a null array.
At line:15 char:9
+ $tags[$_] = $newTags[$_]
+ ~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : NullArray
Try to use Clear-AzContext, then login with specific tenant and subscription, Connect-AzAccount -Tenant "xxxx-xxxx-xxxx-xxxx" -SubscriptionId "yyyy-yyyy-yyyy-yyyy".

Cannot create Azure HDInsight cluster with Hive metastore using Powershell

I get error when I try to create Azure HDInsight cluster using powershell cmdlet:
New-AzureRmHDInsightClusterConfig `
| Add-AzureRmHDInsightMetastore `
-SqlAzureServerName "$sqlDatabaseServerName.database.windows.net" `
-DatabaseName $hiveMetaStoreDBName `
-Credential $sqlServerCred `
-MetastoreType HiveMetaStore `
| New-AzureRmHDInsightCluster `
-ResourceGroupName $resourceGroupName `
-HttpCredential $clusterCreds `
-ClusterName $clusterName `
-Location $location `
-ClusterType $clusterType `
-OSType $OSType `
-Version "$hdVersion" `
-SshCredential $clusterCreds `
-DefaultStorageAccountName "$storageAccountName.blob.core.windows.net" `
-DefaultStorageAccountKey $storageAccountKey `
-ClusterSizeInNodes $clusterNodes
Looks like parameters are not recognized by powershell because it asks to input them (see below). I input required parameters (Location, ClusterName, ClusterSizeInNodes) and then error occurs.
cmdlet New-AzureRmHDInsightCluster at command pipeline position 3
Supply values for the following parameters:
(Type !? for Help.)
Location: West Europe
ClusterName: xxxxxxxxx
ClusterSizeInNodes: 1
New-AzureRmHDInsightCluster : BadRequest: ParameterNullOrEmpty,Parameter 'ASVAccount.AccountName' cannot be null or
empty.
At line:117 char:11
+ | New-AzureRmHDInsightCluster `
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [New-AzureRmHDInsightCluster], CloudException
+ FullyQualifiedErrorId : Hyak.Common.CloudException,Microsoft.Azure.Commands.HDInsight.NewAzureHDInsightClusterCom
mand
Does somebody know why its happens or what is wrong in smdlet?
From the error message, it seems like your $storageAccountName parameter to the New-AzureRmHDInsightCluster cmdlet is Null or Empty, you may want to inspect further on this.
Besides, I would also strongly recommend you to specify the -DefaultStorageContainer to the New-AzureRmHDInsightCluster cmdlet as well. This will ensures that the cmdlet will be able to resolve the FQDN of your storage account Uri.
E.g. asv://YourDefaultContainer#YourDefaultStorageAccountName.blob.core.windows.net/
Hope this helps!
Use below command for Cluster with Hive Metastore.
Here is a working PowerShell script, to be used with Azure ARM PowerShell, 1.0.1 or later – you can install Azure RM PS via web platform installer or follow this blog https://azure.microsoft.com/en-us/blog/azps-1-0/
Add-AzureRmAccount
$MyClusterName = "clustername";
$MyClusterLocation = "East US 2";
$NumClusterNodes = 2;
$MyClusterVersion = "3.2";
$MyHDInsightUserName = ""
$MyHDInsightPwd = ""
$MySqlAzureUserName = ""
$MySqlAzurePwd = ""
$MySqlAzureServerName = "*.database.windows.net"
$MySqlAzureDbName = "Dbtest"
$MyDefaultContainerName = "tastoreps"
$clusterResourceGroupName = "dirg"
# Use the correct Azure Subscription!
$subid = ""
Select-AzureRmSubscription -SubscriptionId $subid
# Storage key
$primaryStorageAcctName = "toragesouth"
$primaryStorageResourceGroupName = "storagerg"
# you need to use an ARM based storage as the primary account , classic storage won’t work as a primary account, known issue
$storageAccountKey = Get-AzureRmStorageAccountKey -ResourceGroupName $primaryStorageResourceGroupName -Name $primaryStorageAcctName | %{ $_.Key1 }
# credentials
$HdInsightPwd = ConvertTo-SecureString $MyHDInsightPwd -AsPlainText -Force
$HdInsightCreds = New-Object System.Management.Automation.PSCredential ($MyHDInsightUserName, $HdInsightPwd)
$SqlAzurePwd = ConvertTo-SecureString $MySqlAzurePwd -AsPlainText -Force
$SqlAzureCreds = New-Object System.Management.Automation.PSCredential ($MySqlAzureUserName, $SqlAzurePwd)
$config = New-AzureRmHDInsightClusterConfig -ClusterType Hadoop |
Add-AzureRmHDInsightMetastore -SqlAzureServerName $MySqlAzureServerName -DatabaseName $MySqlAzureDbName -Credential $SqlAzureCreds -MetastoreType HiveMetastore |
Add-AzureRmHDInsightMetastore -SqlAzureServerName $MySqlAzureServerName -DatabaseName $MySqlAzureDbName -Credential $SqlAzureCreds -MetastoreType OozieMetastore
$config.DefaultStorageAccountName="$StorageAcctName.blob.core.windows.net"
$config.DefaultStorageAccountKey=$storageAccountKey
#create cluster
New-AzureRmHDInsightCluster -config $config -OSType Windows -clustername $MyClusterName -HttpCredential $HdInsightCreds -DefaultStorageContainer $MyDefaultContainerName -Location $MyClusterLocation -ResourceGroupName $clusterResourceGroupName -ClusterSizeInNodes $NumClusterNodes -Version $MyClusterVersion

Resources