Question
I'm trying to add multiple certificates to a new VMSS when creating it but i'm receiving error List secrets contains repeated instances of
/subscriptions/xxxxx/resourceGroups/xxxxx/providers/Microsoft.KeyVault/vaults/xxxxx,
which is disallowed.
My powershell to create the VMSS is:
$vmssConfig = New-AzureRmVmssConfig -Location $location -SkuCapacity $trgVMSSCapacity -SkuName $trgVMSSSize -UpgradePolicyMode 'Manual'
$vmssConfig = Set-AzureRmVmssStorageProfile -VirtualMachineScaleSet $vmssConfig -OsDiskCaching ReadWrite -OsDiskCreateOption FromImage -OsDiskOsType Windows -ImageReferenceId $Image.Id -ManagedDisk $trgVMSSDisk
$vmssConfig = Set-AzureRmVmssOsProfile -VirtualMachineScaleSet $vmssConfig -AdminUsername $trgOSAdminUser -AdminPassword $trgOSAdminPass -ComputerNamePrefix $trgComputerName -WindowsConfigurationEnableAutomaticUpdate $false -WindowsConfigurationProvisionVMAgent $true
$vmssConfig = Add-AzureRmVmssNetworkInterfaceConfiguration -VirtualMachineScaleSet $vmssConfig -Name 'network-config' -Primary $true -IPConfiguration $ipConfig
$cgCertConfig = New-AzureRmVmssVaultCertificateConfig -CertificateUrl $cgCertURL -CertificateStore 'My'
$ktuCertConfig = New-AzureRmVmssVaultCertificateConfig -CertificateUrl $ktuCertURL -CertificateStore 'My'
$vmssConfig = Add-AzureRmVmssSecret -VirtualMachineScaleSet $vmssConfig -SourceVaultId $vaultId -VaultCertificate $cgCertConfig
$vmssConfig = Add-AzureRmVmssSecret -VirtualMachineScaleSet $vmssConfig -SourceVaultId $vaultId -VaultCertificate $ktuCertConfig
$vmssConfig = Set-AzureRmVmssBootDiagnostic -VirtualMachineScaleSet $vmssConfig -Enabled $true -StorageUri $trgStorage.Context.BlobEndPoint
Expected
On the faq here: https://learn.microsoft.com/en-us/azure/virtual-machine-scale-sets/virtual-machine-scale-sets-faq
it has a section 'When I run Update-AzureRmVmss after adding more than one certificate from the same key vault, I see the following message:' but I cannot work out how to fix my script to work, can anyone help?
I'm not able to test, but based on my reading of the documentation, you can't use the Add-AzureRmVmssSecret more than once. You either have to add all of the certs from the same store in the initial command or edit the list here: $vmss.properties.osProfile.secrets[0].vaultCertificates
For your code, I would try:
$cgCertConfig = New-AzureRmVmssVaultCertificateConfig -CertificateUrl $cgCertURL -CertificateStore 'My'
$ktuCertConfig = New-AzureRmVmssVaultCertificateConfig -CertificateUrl $ktuCertURL -CertificateStore 'My'
$vmssConfig = Add-AzureRmVmssSecret -VirtualMachineScaleSet $vmssConfig -SourceVaultId $vaultId -VaultCertificate $cgCertConfig,$ktuCertConfig
The VaultCertificate property accepts an array so try passing all of the certificates at one time.
This is possible using the .Add function on the VaultCertificates property, for example:
$vmss = Get-AzVmss -ResourceGroupName $vmssResourceGroupName -VMScaleSetName $vmssName
# Add the certificate to the same collection
$vmss.VirtualMachineProfile.OsProfile.Secrets[0].VaultCertificates.Add($certConfig)
# Update VMSS
Update-AzVmss -ResourceGroupName $vmssResourceGroupName -Verbose -Name $vmssName -VirtualMachineScaleSet $vmss
Related
I am trying to use PowerShell to set up an Event Hub with Capture set. However, I am experiencing problems when trying specify the capture settings with Set-AzEventHub. I have the following script commands:
$ehResourceGroup = 'kv-audit-resource'
$location = 'eastus'
$ehNameSpace = 'kv-audit-eh'
$ehName = 'security-logs'
$partitions = 1
$week = 7
# Creat resource group for hub
New-AzResourceGroup -Name $ehResourceGroup -Location $location
# Create namespace for hub
New-AzEventHubNamespace -ResourceGroupName $ehResourceGroup -NamespaceName $ehNameSpace -Location $location
# Make the hub
New-AzEventHub -ResourceGroupName $ehResourceGroup -NamespaceName $ehNameSpace -Name $ehName -PartitionCount $partitions -MessageRetentionInDays $week
# Get hub info
$loggingEventHub = Get-AzEventHub -ResourceGroupName $ehResourceGroup -NamespaceName $ehNameSpace -Name $ehName
# Add capture info
$loggingEventHub.CaptureDescription = New-Object -TypeName Microsoft.Azure.Commands.EventHub.Models.PSCaptureDescriptionAttributes
$loggingEventHub.CaptureDescription.Enabled = $true
$loggingEventHub.CaptureDescription.IntervalInSeconds = 60
$loggingEventHub.CaptureDescription.Encoding = "Avro"
$loggingEventHub.CaptureDescription.SizeLimitInBytes = 10485763
$loggingEventHub.CaptureDescription.Destination.Name = "EventHubArchive.AzureBlockBlob"
$loggingEventHub.CaptureDescription.Destination.BlobContainer = "cyberstorageaccount2"
$loggingEventHub.CaptureDescription.Destination.ArchiveNameFormat = "{Namespace}/{EventHub}/{PartitionId}/{Year}/{Month}/{Day}/{Hour}/{Minute}/{Second}"
$loggingEventHub.CaptureDescription.Destination.StorageAccountResourceId = "/subscriptions/{SubscriptionId}/resourceGroups/$ehResourceGroup/providers/Microsoft.ClassicStorage/cyberstorageaccount2"
# Now update the hub with capture info
Set-AzEventHub -ResourceGroupName $ehResourceGroup -Namespace $ehNameSpace -Name $ehName -InputObject $loggingEventHub
I execute the first three commands to create the Event Hub without problems. The storage account, cyberstorageaccount2, already exists. I wait until the Azure dashboard shows that the Event Hub is successfully made and active, which takes several minutes. When I execute the last two commands to modify the capture settings, I get:
PS C:\> $loggingEventHub = Get-AzEventHub -ResourceGroupName $ehResourceGroup -NamespaceName $ehNameSpace -Name $ehName
>> $loggingEventHub.CaptureDescription = New-Object -TypeName Microsoft.Azure.Commands.EventHub.Models.PSCaptureDescriptionAttributes
>> $loggingEventHub.CaptureDescription.Enabled = $true
>> $loggingEventHub.CaptureDescription.IntervalInSeconds = 60
>> $loggingEventHub.CaptureDescription.Encoding = "Avro"
>> $loggingEventHub.CaptureDescription.SizeLimitInBytes = 10485763
>> $loggingEventHub.CaptureDescription.Destination.Name = "EventHubArchive.AzureBlockBlob"
>> $loggingEventHub.CaptureDescription.Destination.BlobContainer = "cyberstorageaccount2"
>> $loggingEventHub.CaptureDescription.Destination.ArchiveNameFormat = "{Namespace}/{EventHub}/{PartitionId}/{Year}/{Month}/{Day}/{Hour}/{Minute}/{Second}"
>> $loggingEventHub.CaptureDescription.Destination.StorageAccountResourceId = "/subscriptions/{SubscriptionId}/resourceGroups/$ehResourceGroup/providers/Microsoft.ClassicStorage/cyberstorageaccount2"
>> Set-AzEventHub -ResourceGroupName $ehResourceGroup -Namespace $ehNameSpace -Name $ehName -InputObject $loggingEventHub
Set-AzEventHub : Operation returned an invalid status code 'BadRequest'
At line:11 char:1
+ Set-AzEventHub -ResourceGroupName $ehResourceGroup -Namespace $ehName ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OpenError: (Microsoft.Azure...ExecuteCmdlet():ErrorResponseException) [Set-AzEventHub],
ErrorResponseException
+ FullyQualifiedErrorId : SubCode=40000. StorageAccountResourceId. TrackingId:ea7e4590-486a-4597-9351-b5e8508857b8
_M6CH3_M6CH3_G28, SystemTracker:kv-audit-eh.servicebus.windows.net:security-logs, Timestamp:2020-12-08T12:37:56 Co
rrelationId: 4b1edeed-6585-47f0-b14e-476614404a23,Microsoft.Azure.Commands.EventHub.Commands.EventHub.SetAzureEven
tHub
What am I doing wrong? It looks like it's griping about the storage account, but when I display the contents of $loggingEventHub.CaptureDescription.Destination.StorageAccountResourceId, the path appears correct.
Thanks in advance for any info.
Storage resource-id seems malformed. It is missing 'storageaccounts' segment.
"/subscriptions/{SubscriptionId}/resourceGroups/$ehResourceGroup/providers/Microsoft.ClassicStorage/storageAccounts/cyberstorageaccount2"
I got this to work. My code was based on an example provided by Microsoft, but their example assumed you had set up a lot of things previously. What follows is my PowerShell code that fills in some of the gaps in their example. The code is commented (slightly) and has debug output that you can delete. It assumes that you have already made an Event Hub with the prerequisite resource group and namespace.
$ehResourceGroup = 'kv-audit-resource'
$location = 'eastus'
$ehNameSpace = 'kv-audit-eh'
$ehName = 'security-logs'
$partitions = 1
$week = 7
$kvStorageAccount = 'cybersecurityaccount2'
$kvContainer = 'security-container'
# Create the storage account for the Event Hub
Write-Output("Create storage account $kvStorageAccount")
$storageAcct = New-AzStorageAccount -ResourceGroupName $ehResourceGroup -AccountName $kvStorageAccount -Location $location -SkuName Standard_GRS -Kind BlobStorage -AccessTier Cool
# Get the "context" required for the container
$accountContext = $storageAcct.Context
# Create a container for the storage account
Write-Output("Create storage account container $kvContainer")
New-AzStorageContainer -Name $kvContainer -Context $accountContext -Permission 'Container'
# Get the storage account ID for the Event Hub
Write-Output("Get ID of storage account $kvStorageAccount")
$kvStorageAccountId = (Get-AzStorageAccount -ResourceGroupName $ehResourceGroup -Name $kvStorageAccount).Id
# Get Event Hub object
Write-Output("Get Event Hub object")
$loggingEventHub = Get-AzEventHub -ResourceGroupName $ehResourceGroup -Namespace $ehNameSpace -Name $ehName
# Update Event Hub capture description
Write-Output("Update Event Hub object")
$loggingEventHub.CaptureDescription = New-Object -TypeName Microsoft.Azure.Commands.EventHub.Models.PSCaptureDescriptionAttributes
$loggingEventHub.CaptureDescription.Enabled = $true
$loggingEventHub.CaptureDescription.IntervalInSeconds = 60
$loggingEventHub.CaptureDescription.Encoding = "Avro"
$loggingEventHub.CaptureDescription.SizeLimitInBytes = 10485763
$loggingEventHub.CaptureDescription.Destination.Name = "EventHubArchive.AzureBlockBlob"
$loggingEventHub.CaptureDescription.Destination.BlobContainer = $kvContainer
$loggingEventHub.CaptureDescription.Destination.ArchiveNameFormat = "{Namespace}/{EventHub}/{PartitionId}/{Year}/{Month}/{Day}/{Hour}/{Minute}/{Second}"
$loggingEventHub.CaptureDescription.Destination.StorageAccountResourceId = $kvStorageAccountId
Set-AzEventHub -ResourceGroupName $ehResourceGroup -Namespace $ehNameSpace -Name $ehName -InputObject $loggingEventHub
Write-Output($loggingEventHub)
I am trying to create HDInsight cluster in Azure with Metastore using the Powershell script. But it is throwing BadRequest: RegionCapabilityNotAvailable,Region capability not available for region 'East US' error. But East US is a supported region for the HDInsight cluster. Please find my code below.
$storageAccountResourceGroupName = "hdi-rg"
$storageAccountName = "qwertyhdi"
#$storageAccountKey = (Get-AzStorageAccountKey -ResourceGroupName $storageAccountResourceGroupName -Name $storageAccountName)[0].value
$storageContainer = "qwertyiopasdf-2020-05-03t08-30-23-118z"
# Cluster configuration info
$location = "East US"
$clusterResourceGroupName = "hdi-rg"
$clusterName = "qwertyiopasdf"
$username = "admin"
$password = ConvertTo-SecureString "password" -AsPlainText -Force
$clusterCreds = New-Object System.Management.Automation.PSCredential -ArgumentList ($username, $password)
# Hive metastore info
$hiveSqlServer = "server"
$hiveDb = "db123"
$sqlusername = "qwerty"
$sqlpassword = ConvertTo-SecureString "password" -AsPlainText -Force
$hiveCreds = New-Object System.Management.Automation.PSCredential -ArgumentList ($sqlusername, $sqlpassword)
New-AzStorageAccount `
-ResourceGroupName $storageAccountResourceGroupName `
-Name $storageAccountName `
-Location $location `
-SkuName Standard_LRS `
-Kind StorageV2 `
-EnableHttpsTrafficOnly 1
# Note: Storage account kind BlobStorage cannot be used as primary storage.
$storageAccountKey = (Get-AzStorageAccountKey `
-ResourceGroupName $storageAccountResourceGroupName `
-Name $storageAccountName)[0].Value
$defaultStorageContext = New-AzStorageContext `
-StorageAccountName $storageAccountName `
-StorageAccountKey $storageAccountKey
New-AzStorageContainer `
-Name $storageContainer `
-Context $defaultStorageContext #use the cluster name as the container name
$metastore = New-AzHDInsightClusterConfig | Add-AzHDInsightMetastore -SqlAzureServerName "$hiveSqlServer.database.windows.net" -DatabaseName $hiveDb -Credential $hiveCreds -MetastoreType HiveMetastore
New-AzHDInsightCluster -Location $location -ResourceGroupName $clusterResourceGroupName -ClusterName $clusterName -ClusterType Hadoop -OSType Windows -ClusterSizeInNodes 1 -HttpCredential $clusterCreds -DefaultStorageAccountName "$storageAccountName.blob.core.windows.net" -DefaultStorageAccountKey $storageAccountKey -DefaultStorageContainer $storageContainer -Config $metastore
Is -OSType Windows still valid. I realize "Windows" is listed as an option from the PowerShell specs, but I think "linux" is the only value that will actually work.
You will receive this error message BadRequest: RegionCapabilityNotAvailable,Region capability not available for region 'East US', when underlying compute sku is not available for the selected region in that subscription.
I would request you to check if the resource are available from Azure Portal.
Azure Portal => Select your subscription => Usage + Quotas
Filter with => Microsoft.Compute and Region => East US
If you're unable to find a suitable SKU in that region/zone or an alternative region/zone that meets your business needs, submit a SKU request or Quota increase to Azure Support.
What username and password should we use to access SF nodes ?
Is it the same Azure portal username and password?
You have provided the password as part of the creation of the cluster. For example, it's passed as an ARM template parameter. Fortunately, you can reset the password of your VM scaleset.
Login-AzureRmAccount
Get-AzureRmSubscription -SubscriptionId 'SUBSCRIPTIONID' | Select-AzureRmSubscription
$vmssName = 'SCALESETNAME'
$vmssResourceGroup = 'SCALESETRESOURCEGROUP'
$publicConfig = #{'UserName' = 'USERNAME'}
$privateConfig = #{'Password' = 'NEWPASSWORD'}
$extName = 'VMAccessAgent'
$publisher = 'Microsoft.Compute'
$vmss = Get-AzureRmVmss -ResourceGroupName $vmssResourceGroup -VMScaleSetName $vmssName
$vmss = Add-AzureRmVmssExtension -VirtualMachineScaleSet $vmss -Name $extName -Publisher $publisher -Setting $publicConfig -ProtectedSetting $privateConfig -Type $extName -TypeHandlerVersion '2.0' -AutoUpgradeMinorVersion $true
Update-AzureRmVmss -ResourceGroupName $vmssResourceGroup -Name $vmssName -VirtualMachineScaleSet $vmss
I would like to set the connection strings and app settings of my Azure web app using powershell. And I would like those settings to stick with the slot, and not with the app when it is swapped.
The code for app settings looks like this and it works:
$PropertiesObject = #{"SMTPUser"="myuser"; "SMTPPassword"="secretpwd";}
$webAppName = "mywebapp"
$slotName = "demo"
$resourceGroupName = "myResourceGroup"
New-AzureRmResource -PropertyObject $PropertiesObject -ResourceGroupName $resourceGroupName -ResourceType Microsoft.Web/sites/slots/config -ResourceName $webAppName/$slotName/appsettings -ApiVersion 2015-08-01 -Force
$stickSlotConfigObject = #{"connectionStringNames"=#(); "appSettingNames" = #("SMTPUserName","SMTPPassword");}
$result = Set-AzureRmResource -PropertyObject $stickSlotConfigObject -ResourceGroupName $resourceGroupName -ResourceType Microsoft.Web/sites/config -ResourceName $webAppName/slotConfigNames -ApiVersion 2015-08-01 -Force
This works. When I go to the slot blade of the web app in the Azure portal, the "Slot Setting" check box is checked as I want it to be.
I'm struggling with how to set the connection strings to also have the "slot setting" box checked. I tried the following,
$PropertiesObject = #{
AzureWebJobsStorage = #{
Type = "Custom";
Value = "somestring"
};
Common = #{
Type = "SQLAzure";
Value = "somedatabasestring"
};
};
$webAppName = "mywebapp"
$slotName = "demo"
$resourceGroupName = "myResourceGroup"
New-AzureRmResource -PropertyObject $PropertiesObject -ResourceGroupName $resourceGroupName -ResourceType Microsoft.Web/sites/slots/config -ResourceName $webAppName/$slotName/appsettings -ApiVersion 2015-08-01 -Force
$stickSlotConfigObject = #{"appSettingNames"=#();"connectionStringNames"=#("AzureWebJobsStorage","Common"); }
$result = Set-AzureRmResource -PropertyObject $stickSlotConfigObject -ResourceGroupName $resourceGroupName -ResourceType Microsoft.Web/sites/config -ResourceName $webAppName/appsettings -ApiVersion 2015-08-01 -Force
This did not work. I got the following error:
New-AzureRmResource : {"Code":"BadRequest","Message":"The parameter properties has an invalid value.","Target":null,"Details":[{"Message":"The parameter properties has an invalid value."},{"Code":"BadRequest"},{"ErrorEntity":{"Code":"BadRequest","Message":"The parameter properties has an invalid value.","ExtendedCode":"51008","MessageTemplate":"The parameter {0} has an invalid value.","Parameters":["properties"],"InnerErrors":null}}],"Innererror":null}
I tried another tweak (which I forgot) and it said that the $PropertiesObject object was not in the right format.
How do I code it in Powershell so that I can check the slot setting check box of a web app connection string (or configure it as "sticky"?
Please have a try with the following code to set connection string as sticky setting for slot. It works correctly for me. More info about automating Azure WebApps with PowerShell ARM way please refer to the document.
$connectionString = #{}
$webAppName = "Web AppName"
$resourceGroup ="Resource Group Name"
$slotName ="slot Name"
$connectionString.Add("AzureWebJobsStorage", #{ value = "The Actual connecting string here" ; Type = 3 }) #Custom
$connectionString.Add("Common", #{ value = "The Actual connecting string here" ; Type = 2 }) #Azure SQL
Login-AzureRmAccount
# creat slot connection string
New-AzureRmResource -PropertyObject $connectionString `
-ResourceGroupName $resourceGroup `
-ResourceType "Microsoft.Web/sites/slots/config" `
-ResourceName "$webAppName/$slotName/connectionstrings" `
-ApiVersion 2015-08-01 -Force
# set connection string as sticky setting
$stickSlotConfigObject = #{"connectionStringNames" = #("AzureWebJobsStorage","Common")} #connection string Name
Set-AzureRmResource -PropertyObject $stickSlotConfigObject `
-ResourceGroupName $resourceGroup `
-ResourceType Microsoft.Web/sites/config `
-ResourceName $webAppName/slotConfigNames `
-ApiVersion 2015-08-01 -Force
There are now two new cmdlets to control the slot settings: Get-AzureRmWebAppSlotConfigName and Set-AzureRmWebAppSlotConfigName
For instance, I wanted to make sure that my connection strings weren't a slot config so I executed:
Set-AzureRmWebAppSlotConfigName -ResourceGroupName MyRg -Name MyWebApp -RemoveAllConnectionStringNames
$resourceName = $webappname + “/slotconfigname”
$stickySlot = Get-AzureRmResource -ResourceName $resourceName -ResourceGroupName -ResourceType “Microsoft.Web/Sites/config” -ApiVersion “2015-08-01”
You can then check the existing ones by:
$stickySlot.Properties.AppSettingNames
Here you need to different approaches. If these are empty from the get go, you need to create a new array with settings:
$settings = #(“AppSetting1, “AppSetting2”)
$stickySlot.Properties.AppSettingNames = $settings
If there already are other values, and you want to keep them:
$stickySlot.Properties.AppSettingNames += “AppSetting1”
$stickySlot.Properties.AppSettingNames += “AppSetting2”
Then after that is done:
Set-AzureRmResource -ResourceName $resourceName -ResourceGroupName -ResourceType “Microsoft.Web/Sites/config” -Properties $stickySlot.Properties -ApiVersion “2015-08-01"
Taken from: https://msftplayground.com/2016/02/adding-azure-app-service-application-settings-powershell/
I have hunted around for an answer to this, but I am not having much luck. All the articles I can find are either setting up a Point-to-Site or are instructions for classic Azure, not Azure 2.0 (Resource Group)
Currently, we are dialing up a whole new resource group everytime we do a new built. This consists of Web apps and SQL DBs. When we have a new build we start up the new and del the old resource group. Simple. To minimize the start-up time we have a static resource group that isn't deleted that houses the VPN connection to our on Prem resources.
The problem I'm having is when I add the new websites using AzureRM Powershell cmd's to the Point-to-site it says it's successful. The Azure Portal says its good but it does let me communicate. If I remove and add it from one of the 8 WebApps they all start working.
I am out of ideas. Any help would be greatly appreciated.
Azure VPN
Below is the function I have put togeather from what I can find out there.
function AddExistingVnet{
param(
[string] $subscriptionId,
[string] $resourceGroupName,
[string] $webAppName
)
$Vnet = Get-AzureRmVirtualNetwork | Where-Object {$_.ResourceGroupName -like "*Static*"}
IF($Vnet.Name.count -gt 1) {write-host 'Two or networks have been returned. Unable to continue ' return}
$gatewaySubnet = $vnet.Subnets | Where-Object { $_.Name -eq "GatewaySubnet" }
$vnetName = $vnet.Name
$uriParts = $gatewaySubnet.IpConfigurations[0].Id.Split('/')
$gatewayResourceGroup = $uriParts[4]
$gatewayName = $uriParts[8]
$gateway = Get-AzureRmVirtualNetworkGateway -ResourceGroupName $vnet.ResourceGroupName -Name $gatewayName
Write-Host "Creating App association to VNET"
$propertiesObject = #{
"vnetResourceId" = "/subscriptions/$($subscriptionId)/resourceGroups/$($vnet.ResourceGroupName)/providers/Microsoft.Network/virtualNetworks/$($vnetName)"
}
$virtualNetwork = New-AzureRmResource -Location $location -Properties $PropertiesObject -ResourceName "$($webAppName)/$($vnet.Name)" -ResourceType "Microsoft.Web/sites/virtualNetworkConnections" -ApiVersion 2015-08-01 -ResourceGroupName $resourceGroupName -Force
# Now finish joining by getting the VPN package and giving it to the App
Write-Host "Retrieving VPN Package and supplying to App"
$packageUri = Get-AzureRmVpnClientPackage -ResourceGroupName $vnet.ResourceGroupName -VirtualNetworkGatewayName $gateway.Name -ProcessorArchitecture Amd64
# Put the VPN client configuration package onto the App
$PropertiesObject = #{
"vnetName" = $vnet.Name; "vpnPackageUri" = $packageUri
}
New-AzureRmResource -Location $location -Properties $PropertiesObject -ResourceName "$($webAppName)/$($vnet.Name)/primary" -ResourceType "Microsoft.Web/sites/virtualNetworkConnections/gateways" -ApiVersion 2015-08-01 -ResourceGroupName $resourceGroupName -WarningAction silentlyContinue -Force
}
So after 2 weeks of going back and forth with Microsoft (had a really good guy Charles) we managed to find the problem.
When requesting
$packageUri = Get-AzureRmVpnClientPackage -ResourceGroupName $vnet.ResourceGroupName -VirtualNetworkGatewayName $gateway.Name -ProcessorArchitecture Amd64
It was giving me an output of:
"https://mdsbrketwprodsn1prod.blob.core.windows.net/cmakexe/xxx~xxx/amd64/xxxx~xxxx&sp=r&fileExtension=.exe"
For some reason (that Microsoft could explain) why it kept adding in " to the beginning and end of the variable.
I find it odd that it lets the script work with " and allows the WebApps to join to the VPN.
Any why here is the fix which basicly removes the " from the begining and end of $packageUri :
$packageUri = $packageUri.ToString();
$packageUri = $packageUri.Substring(1, $packageUri.Length-2);
So hope that helps someone else out there who is banging there head agaist the same problem.
Here is the complete function if any one is intrested:
function AddExistingVnet{
param(
[string] $subscriptionId,
[string] $resourceGroupName,
[string] $webAppName
)
$Vnet = Get-AzureRmVirtualNetwork | Where-Object {$_.ResourceGroupName -like "*Static*"}
IF($Vnet.Name.count -gt 1) {write-host 'Two or networks have been returned. Unable to continue ' return}
$gatewaySubnet = $vnet.Subnets | Where-Object { $_.Name -eq "GatewaySubnet" }
$vnetName = $vnet.Name
$uriParts = $gatewaySubnet.IpConfigurations[0].Id.Split('/')
$gatewayResourceGroup = $uriParts[4]
$gatewayName = $uriParts[8]
$gateway = Get-AzureRmVirtualNetworkGateway -ResourceGroupName $vnet.ResourceGroupName -Name $gatewayName
$webApp = Get-AzureRmResource -ResourceName $webAppName -ResourceType "Microsoft.Web/sites" -ApiVersion 2015-08-01 -ResourceGroupName $resourceGroupName
$location = $webApp.Location
Write-Host "Creating App association to VNET"
$propertiesObject = #{
"vnetResourceId" = "/subscriptions/$($subscriptionId)/resourceGroups/$($vnet.ResourceGroupName)/providers/Microsoft.Network/virtualNetworks/$($vnetName)"
}
$virtualNetwork = New-AzureRmResource -Location $location -Properties $PropertiesObject -ResourceName "$($webAppName)/$($vnet.Name)" -ResourceType "Microsoft.Web/sites/virtualNetworkConnections" -ApiVersion 2015-08-01 -ResourceGroupName $resourceGroupName -Force
# Now finish joining by getting the VPN package and giving it to the App
Write-Host "Retrieving VPN Package and supplying to App"
$packageUri = Get-AzureRmVpnClientPackage -ResourceGroupName $vnet.ResourceGroupName -VirtualNetworkGatewayName $gateway.Name -ProcessorArchitecture Amd64
$packageUri = $packageUri.ToString();
$packageUri = $packageUri.Substring(1, $packageUri.Length-2);
# Put the VPN client configuration package onto the App
$PropertiesObject = #{
"vnetName" = $vnet.Name; "vpnPackageUri" = $packageUri.ToString()
}
$date = Get-Date -format "HH:mm tt"
New-AzureRmResource -Location $location -Properties $PropertiesObject -ResourceName "$($webAppName)/$($vnet.Name)/primary" -ResourceType "Microsoft.Web/sites/virtualNetworkConnections/gateways" -ApiVersion 2015-08-01 -ResourceGroupName $resourceGroupName -WarningAction silentlyContinue -Force
}
Enjoy