How to setup azure application gateway with App services - azure

I am trying to setup azure application gateway with self signed cert. for the first step without https, I am trying to establish the http with port 80. when I try to browse the application with the appgateway public IP it is redirecting it to https://myappname.azurewebsites.net:80, I am not sure whats going wrong here. I specifically write a rewrite rule to override to the the site but in that case the site loads without redirection(as expected) and working fine. I want to understand why its navigating to myappname.azurewebsites.net:80 instead of just myappname.azurewebsites.net. I am following this
Here is the simplified version of the PowerShell script for the same with no existing port 80 rule
$webAppFQDN = "myapp.azurewebsites.net"
$rgName = "acsrg001"
$appGwName = "acsag002"
$appGwBackendPoolNameForAppSvc = "acspebpool001"
$httpSettingsName = "acspehttpsettings001"
$httpListenerName = "acspelistener001"
$reqRoutingRuleName = "acspelatestrule001"
$gw = Get-AzApplicationGateway -Name $appGwName -ResourceGroupName $rgName
Add-AzApplicationGatewayBackendAddressPool -Name $appGwBackendPoolNameForAppSvc -ApplicationGateway $gw -BackendFqdns $webAppFQDN
Set-AzApplicationGateway -ApplicationGateway $gw
$gw = Get-AzApplicationGateway -Name $appGwName -ResourceGroupName $rgName
Add-AzApplicationGatewayBackendHttpSettings -Name $httpSettingsName -ApplicationGateway $gw -Protocol Https -Port 443 -PickHostNameFromBackendAddress -CookieBasedAffinity Disabled -RequestTimeout 30
Set-AzApplicationGateway -ApplicationGateway $gw
$gw = Get-AzApplicationGateway -Name $appGwName -ResourceGroupName $rgName
$port = $gw.FrontendPorts | Where-Object {$_.Port -eq 80}
$listener = $gw.HttpListeners | Where-Object {$_.Protocol.ToString().ToLower() -eq "http" -and $_.FrontendPort.Id -eq $port.Id}
if ($listener -eq $null){
$frontendIpConfig = $gw.FrontendIpConfigurations | Where-Object {$_.PublicIpAddress -ne $null}
Add-AzApplicationGatewayHttpListener -Name $httpListenerName -ApplicationGateway $gw -Protocol Http -FrontendIPConfiguration $frontendIpConfig -FrontendPort $port
Set-AzApplicationGateway -ApplicationGateway $gw
}
$gw = Get-AzApplicationGateway -Name $appGwName -ResourceGroupName $rgName
$httpListener = Get-AzApplicationGatewayHttpListener -Name $httpListenerName -ApplicationGateway $gw
$httpSettings = Get-AzApplicationGatewayBackendHttpSettings -Name $httpSettingsName -ApplicationGateway $gw
$backendPool = Get-AzApplicationGatewayBackendAddressPool -Name $appGwBackendPoolNameForAppSvc -ApplicationGateway $gw
Add-AzApplicationGatewayRequestRoutingRule -Name $reqRoutingRuleName -ApplicationGateway $gw -RuleType Basic -BackendHttpSettings $httpSettings -HttpListener $httpListener -BackendAddressPool $backendPool -Priority 1
Set-AzApplicationGateway -ApplicationGateway $gw
$gw = Get-AzApplicationGateway -Name $appGwName -ResourceGroupName $rgName
Get-AzApplicationGatewayBackendHealth -ResourceGroupName $rgName -Name $appGwName

I tried to reproduce the same script in my environment I got the same result like below:
Sku : Microsoft.Azure.Commands.Network.Models.PSApplicationGatewaySku
SslPolicy :
GatewayIPConfigurations : {appGatewayIpConfig}
AuthenticationCertificates : {}
SslCertificates : {}
TrustedRootCertificates : {}
TrustedClientCertificates : {}
FrontendIPConfigurations : {appGwPublicFrontendIp}
FrontendPorts : {port_80}
Probes : {}
BackendAddressPools : {back, pool1, backendpool007}
BackendHttpSettingsCollection : {http}
SslProfiles : {}
HttpListeners : {listhttp}
UrlPathMaps : {}
RequestRoutingRules : {rule1}
RewriteRuleSets : {}
RedirectConfigurations : {rule1}
WebApplicationFirewallConfiguration :
FirewallPolicy :
AutoscaleConfiguration : Microsoft.Azure.Commands.Network.Models.PSApplicationGatewayAutoscaleConfiguration
CustomErrorConfigurations : {}
PrivateLinkConfigurations : {}
PrivateEndpointConnections : {}
EnableHttp2 : False
EnableFips :
ForceFirewallPolicyAssociation :
Zones : {}
OperationalState : Running
ProvisioningState : Succeeded
Identity :
GatewayIpConfigurationsText : [
{
"Subnet": {
"Id": "/subscriptions/6ca9eff3-3c2d-420e-875e-ea526b412ca0/resourceGroups/imran/providers/Microsoft.Network/virtualNetworks/imran-vnet/su
bnets/appsubnet"
},
"ProvisioningState": "Succeeded",
"Type": "Microsoft.Network/applicationGateways/gatewayIPConfigurations",
"Name": "appGatewayIpConfig",
"Etag": "W/\"2494e0c1-b1fc-4840-896e-a39e9ebf0846\"",
"Id": "/subscriptions/6ca9eff3-3c2d-420e-875e-ea526b412ca0/resourceGroups/imran/providers/Microsoft.Network/applicationGateways/imran/gatew
ayIPConfigurations/appGatewayIpConfig"
}
This issue may cause having a different hostname at the reverse proxy in app gateway one of the back-end application servers can cause cookies or redirect URLs to malfunction. For instance, the session state may be lost, authentication may fail, or back-end URLs may unintentionally discover back-end URLs.
To resolve this issue, Try to add a custom domain Configure App Service with Application Gateway along with a certificate in your backend pool with use of custom domain and add authentication trusted root certificates of back-end servers like below:
In application gateway under setting click rules in backend target -> add backend pool of app service and Add appropriate App Gateway in the HTTP configuration.
You can check the similar thread for reference:
when I hit application gateway's public ip, I get redirected to app service dns. by GitaraniSharma
Azure application gateway with Web App - Gateway IP wont work

Related

PS: Remove Azure NIC from LB Pool

I'm trying to remove Azure Load Balancer Backend Pool setting out of NIC Ipconfig in PowerShell but not succeeding without destroying whole Ipconfig. Either it removes entire config like
Remove-AzNetworkInterfaceIpConfig -NetworkInterface $NIC
Or when I was trying to set Ipconfig while naming other properties, LB pool config persists
Set-AzNetworkInterfaceIpConfig -NetworkInterface $NIC -Name "ipconfig1" -PrivateIpAddress $DIP -Subnet $backendSubnet -PublicIpAddress $PIP -ApplicationSecurityGroup $NSG
How can I only remove LB Backend Pool and keep the other properties? Thanks
If you want just remove or add specific NIC you can use this one. Just pass required variables and Action name "remove" or "add". It removes only NIC from Backend Load Balancer Pool, but didn't destroys whole Backend Pool configuration.
$ResourceGroup = "YourResourceGroupName"
$Loadbalancer = "YourLoadBalancerName"
$NICName = "YourVirtualMachineNetworkInterfaceName"
$Action = "remove" #add
if ($Action -eq 'add')
{
Write-Host ("Adding to LB")
$nic = Get-AzNetworkInterface | Where-Object { ($_.ResourceGroupName -eq "$ResourceGroup") -and ($_.Name -eq "$NICName") }
$lb = Get-AzLoadBalancer | Where-Object { ($_.ResourceGroupName -eq "$ResourceGroup") -and ($_.Name -eq "$Loadbalancer") }
$nic.IpConfigurations[0].LoadBalancerBackendAddressPools = $lb.BackendAddressPools[0]
Set-AzNetworkInterface -NetworkInterface $nic
}
if ($Action -eq 'remove')
{
Write-Host ("Removing from LB")
$nic = Get-AzNetworkInterface | Where-Object { ($_.ResourceGroupName -eq "$ResourceGroup") -and ($_.Name -eq "$NICName") }
$nic.Ipconfigurations[0].LoadBalancerBackendAddressPools = $null
Set-AzNetworkInterface -NetworkInterface $nic
}
What you need to do is not remove the Ipconfig of the NIC, but remove the nat rule config and backend pool config from the Load Balancer that associated with the Ipconfig of the NIC. And the example code here:
$resourceGrouName = "xxxxx"
$loabBalancerName = "xxxxx"
$inboundRuleConfigName = "xxxxx"
$backendpoolconfigName = "xxxxx"
$lb = Get-AzLoadBalancer -ResourceGroupName $resourceGrouName -Name $loabBalancerName
Remove-AzLoadBalancerInboundNatRuleConfig -LoadBalancer $lb -Name $inboundRuleConfigName
Remove-AzLoadBalancerBackendAddressPoolConfig -LoadBalancer $lb -Name $backendpoolconfigName
Set-AzLoadBalancer -LoadBalancer $lb
And you need to change the variables into yours. Then you can find the info about the Load Balancer that was removed from the Ipconfig of the NIC.
turns that you don't have to remove entire backend pool config but just modify NIC Ipconfig. I've tried
$DeactivateNIC = Get-AzNetworkInterface -ResourceGroupName $RG -Name $DeactivateNICName
$DeactivateNIC.IpConfigurations[0].LoadBalancerBackendAddressPools = $null
Set-AzNetworkInterface -NetworkInterface $DeactivateNIC
that works and LB pool stays. For adding I just add the Ipconfig property like:
$ActivateNIC = Get-AzNetworkInterface -ResourceGroupName $RG -Name $ActivateNICName
$lb = Get-AzLoadBalancer -ResourceGroupName $RG -Name "LB"
$lbPoolConfig = Get-AzLoadBalancerBackendAddressPoolConfig -LoadBalancer $lb
$ActivateNIC.IpConfigurations[0].LoadBalancerBackendAddressPools=$lbPoolConfig
Set-AzNetworkInterface -NetworkInterface $ActivateNIC

Integrate API Management in an internal VNET with Application Gateway

I developed PowerShell script based on the following manual Integrate API Management in an internal VNET with Application Gateway https://learn.microsoft.com/en-us/azure/api-management/api-management-howto-integrate-internal-vnet-appgateway
##log in to the Azure account
Connect-AzAccount
##Create Resource group
New-AzResourceGroup -Name Network -Location westeurope
New-AzResourceGroup -Name Security -Location westeurope
New-AzResourceGroup -Name Application -Location westeurope
##Create DDOS protection plan
$ddosProtectionPlan = New-AzDdosProtectionPlan -ResourceGroupName Security -Name DdosProtectionPlanName -Location "westeurope"
##create the subnet
$appgatewaysubnet = New-AzVirtualNetworkSubnetConfig -Name "apim01" -AddressPrefix "10.0.0.0/24"
$apimsubnet = New-AzVirtualNetworkSubnetConfig -Name "apim02" -AddressPrefix "10.0.1.0/24"
##create the VNet
$vnet = New-AzVirtualNetwork -Name "appgwvnet" -ResourceGroupName Network -Location westeurope -AddressPrefix "10.0.0.0/16" -Subnet $appgatewaysubnet,$apimsubnet -DdosProtectionPlanId $ddosProtectionPlan.Id
##Assign a subnet variable
$appgatewaysubnetdata = $vnet.Subnets[0]
$apimsubnetdata = $vnet.Subnets[1]
##Create an API Management Virtual Network object using the subnet $apimsubnetdata
$apimVirtualNetwork = New-AzApiManagementVirtualNetwork -SubnetResourceId $apimsubnetdata.Id
##Create an API Management service inside the Virtual Network
$apimServiceName = "starAPImanagment123" # API Management service instance name
$apimOrganization = "star" # organization name
$apimAdminEmail = "aanwar#ejada.com" # administrator's email address
$apimService = New-AzApiManagement -ResourceGroupName Application -Location westeurope -Name $apimServiceName -Organization $apimOrganization -AdminEmail $apimAdminEmail -VirtualNetwork $apimVirtualNetwork -VpnType "Internal" -Sku "Developer"
##Test
$gatewayHostname = "api.star.net" # API gateway host
$portalHostname = "portal.star.net" # API developer portal host
$proxyHostnameConfig = New-AzApiManagementCustomHostnameConfiguration -Hostname $gatewayHostname -HostnameType Proxy
$portalHostnameConfig = New-AzApiManagementCustomHostnameConfiguration -Hostname $portalHostname -HostnameType DeveloperPortal
$apimService.ProxyCustomHostnameConfiguration = $proxyHostnameConfig
$apimService.PortalCustomHostnameConfiguration = $portalHostnameConfig
Set-AzApiManagement -InputObject $apimService
##Create a public IP
$publicip = New-AzPublicIpAddress -ResourceGroupName Network -name "publicIP01" -location westeurope -AllocationMethod Dynamic
##Create an application gateway IP configuration in the back-end IP pool
$gipconfig = New-AzApplicationGatewayIPConfiguration -Name "gatewayIP01" -Subnet $appgatewaysubnetdata
##Configure the front-end IP port for the public IP endpoint
$fp01 = New-AzApplicationGatewayFrontendPort -Name "port01" -Port 443
$fipconfig01 = New-AzApplicationGatewayFrontendIPConfig -Name "frontend1" -PublicIPAddress $publicip
##Test2
$listener = New-AzApplicationGatewayHttpListener -Name "listener01" -Protocol "Https" -FrontendIPConfiguration $fipconfig01 -FrontendPort $fp01 -HostName $gatewayHostname -RequireServerNameIndication true
$portalListener = New-AzApplicationGatewayHttpListener -Name "listener02" -Protocol "Https" -FrontendIPConfiguration $fipconfig01 -FrontendPort $fp01 -HostName $portalHostname -RequireServerNameIndication true
$apimprobe = New-AzApplicationGatewayProbeConfig -Name "apimproxyprobe" -Protocol "Https" -HostName $gatewayHostname -Path "/status-0123456789abcdef" -Interval 30 -Timeout 120 -UnhealthyThreshold 8
$apimPortalProbe = New-AzApplicationGatewayProbeConfig -Name "apimportalprobe" -Protocol "Https" -HostName $portalHostname -Path "/signin" -Interval 60 -Timeout 300 -UnhealthyThreshold 8
$apimPoolSetting = New-AzApplicationGatewayBackendHttpSettings -Name "apimPoolSetting" -Port 443 -Protocol "Https" -CookieBasedAffinity "Disabled" -Probe $apimprobe -RequestTimeout 180
$apimPoolPortalSetting = New-AzApplicationGatewayBackendHttpSettings -Name "apimPoolPortalSetting" -Port 443 -Protocol "Https" -CookieBasedAffinity "Disabled" -Probe $apimPortalProbe -RequestTimeout 180
##Configure a back-end IP address pool
$apimProxyBackendPool = New-AzApplicationGatewayBackendAddressPool -Name "apimbackend" -BackendIPAddresses $apimService.PrivateIPAddresses[0]
##Create rules for the Application Gateway
$rule01 = New-AzApplicationGatewayRequestRoutingRule -Name "rule1" -RuleType Basic -HttpListener $listener -BackendAddressPool $apimProxyBackendPool -BackendHttpSettings $apimPoolSetting
$rule02 = New-AzApplicationGatewayRequestRoutingRule -Name "rule2" -RuleType Basic -HttpListener $portalListener -BackendAddressPool $apimProxyBackendPool -BackendHttpSettings $apimPoolPortalSetting
##Configure the number of instances and size for the Application Gateway
$sku = New-AzApplicationGatewaySku -Name "WAF_Medium" -Tier "WAF" -Capacity 2
##Configure WAF to be in "Prevention" mode
$config = New-AzApplicationGatewayWebApplicationFirewallConfiguration -Enabled $true -FirewallMode "Prevention"
##Create an Application Gateway
$appgwName = "apim-app-gw"
$appgw = New-AzApplicationGateway -Name $appgwName -ResourceGroupName Network -Location westeurope -BackendAddressPools $apimProxyBackendPool -BackendHttpSettingsCollection $apimPoolSetting, $apimPoolPortalSetting -FrontendIpConfigurations $fipconfig01 -GatewayIpConfigurations $gipconfig -FrontendPorts $fp01 -Sku $sku -WebApplicationFirewallConfig $config -Probes $apimprobe, $apimPortalProbe
Get-AzPublicIpAddress -ResourceGroupNam`e Network -Name "publicIP01"`
but i got a message which i cannot understand it
cmdlet New-AzApplicationGateway at command pipeline 1
Supply values for the following parameters:
(Type !? for Help.)
HttpListeners[0]:
RwquestRoutingRules[0]:
note : i didn't put any certification in my script .
kindly advise
You need to specify also the listeners in the New-AzApplicationGateway command:
-HttpListeners $listener,$portalListener

Azure Powershell - Applying multiple service endpoints to a subnet

I have coded a powershell script to set an existing subnet to function as a service endpoint for multiple services. However, when I run the command line in the script, it doesn't add a new service endpoint, it just changes the existing one.
I am trying to parameterise this through Jenkins as well, which may be an added complication. I think if I can get the base syntax right then that shouldn't be a problem.
Syntax I am using is:
#Get vnet
$virtualnetwork = Get-AzureRmVirtualNetwork -Name $VN -ResourceGroupName $RG
#Configure service endpoint
Add-AzureRmVirtualNetworkSubnetConfig -Name $SN -AddressPrefix $SAP -
VirtualNetwork $virtualnetwork -ServiceEndpoint $EP
#Set configuration
$virtualnetwork | Set-AzureRmVirtualNetwork
You can use something like this to add as many endpoints as required:
$rgname = "amgar-dtl"
$vnName = "Dtlamgar-dtl"
$sname = "Dtlamgar-dtlSubnet"
$subnetPrefix = "10.0.0.0/20"
#Get vnet
$VirtualNetwork = Get-AzureRmVirtualNetwork -ResourceGroupName $rgname -Name $vnName | Get-AzureRmVirtualNetworkSubnetConfig -Name $sname
#Get existing service endpoints
$ServiceEndPoint = New-Object 'System.Collections.Generic.List[String]'
$VirtualNetwork.ServiceEndpoints | ForEach-Object { $ServiceEndPoint.Add($_.service) }
#Add new service endpoint
Get-AzureRmVirtualNetwork -ResourceGroupName $rgname -Name $vnName | Set-AzureRmVirtualNetworkSubnetConfig -Name $sname -AddressPrefix $subnetPrefix -ServiceEndpoint $ServiceEndPoint.Add("Microsoft.KeyVault") | Set-AzureRmVirtualNetwork
Hope this helps!
Successful syntax is:
#Vnet
$VN = "$ENV:VNET_NAME"
#Resource Group
$RG = "$ENV:RESOURCEGROUP_NAME"
#Subnet
$SN = "$ENV:SUBNET_NAME"
#Subnet Address Prexifx
$SAP = "$ENV:ADDRESS_PREFIX"
#ServiceEndpoint
$EP = "$ENV:SERVICE_ENDPOINT"
Write-Host "Importing the AzureRM module into the PowerShell session"
Import-Module AzureRM
Write-Host "Connect service principle account to Azure RM"
Connect-AzureRmAccount -ServicePrincipal -Credential $CREDS -TenantId $TID -Subscription $SID
#Get vnet
$VirtualNetwork = Get-AzureRmVirtualNetwork -ResourceGroupName $RG -Name $VN | Get-AzureRmVirtualNetworkSubnetConfig -Name $SN
#Get existing service endpoints
$ServiceEndPoint = New-Object 'System.Collections.Generic.List[String]'
$VirtualNetwork.ServiceEndpoints | ForEach-Object { $ServiceEndPoint.Add($_.service) }
$ServiceEndPoint.Add($EP)
#Add new service endpoint
Get-AzureRmVirtualNetwork -ResourceGroupName $RG -Name $VN | Set-AzureRmVirtualNetworkSubnetConfig -Name $SN -AddressPrefix $SAP -ServiceEndpoint $ServiceEndPoint | Set-AzureRmVirtualNetwork
Powershell does not appear to support the command $ServiceEndPoint.Add("Microsoft.KeyVault") with “|”. Once it was executed separately, the script worked.
Here is another version for those looking to process multiple subnets and to validate that the subnet doesn't already have the service endpoint enabled because it will error out if the same service is listed twice when modifying the subnet.
$subscription = "Enter Subscription ID here"
$subnets = #('my-subnet-1','my-subnet-2','my-subnet-3')
$vnetName = "MY-VNET"
$vnetRgName = "MY-VNET-RG"
$newEndpoint = "Microsoft.AzureCosmosDB"
Set-AzContext -Subscription $subscription
foreach($snet in $subnets){
Write-Host "Modifying Service Endpoints for subnet: $snet" -fore red -back white
$virtualNetwork = Get-AzVirtualNetwork -Name $vnetName -ResourceGroupName $vnetRgName | Get-AzVirtualNetworkSubnetConfig -Name $snet
$addrPrefix = $virtualNetwork.AddressPrefix
#Get existing service endpoints
$ServiceEndPoint = New-Object 'System.Collections.Generic.List[String]'
$virtualNetwork.ServiceEndpoints | ForEach-Object { $ServiceEndPoint.Add($_.service) }
if ($ServiceEndPoint -notcontains $newEndPoint){
$ServiceEndPoint.Add($newEndpoint)
}
#Add new service endpoint
Get-AzVirtualNetwork -Name $vnetName -ResourceGroupName $vnetRgName | Set-AzVirtualNetworkSubnetConfig -Name $snet -AddressPrefix $addrPrefix -ServiceEndpoint $ServiceEndPoint | Set-AzVirtualNetwork
}

Create Azure Load Balancer in existing v-net fears to "Not all Backend IP Configurations referenced by the Load Balancer"

I try to create a load balancer on azure via powershell, but in case I use an existing vnet from an different resource group I get an error.
(Not all Backend IP Configurations referenced by the Load Balancer). The load balancer should later be used for a VM Scale Set.
But I did not set the v-net and IPs for the BackendAddressPoolConfig, also I do not see how to do this.
$vnet= Get-AzureRmVirtualNetwork -Name $vnetname -ResourceGroupName $vnetrg -ErrorAction Stop
$subnetMain = $vnet.Subnets[2]
$subNetName = $subnetMain.Name
$frontendIP = New-AzureRmLoadBalancerFrontendIpConfig -Name LB-Frontend `
-SubnetId $subnetMain.Id
$beaddresspool= New-AzureRmLoadBalancerBackendAddressPoolConfig -Name "LB-backend"
$inboundNATRule1= New-AzureRmLoadBalancerInboundNatRuleConfig -Name "RDP" `
-FrontendIpConfiguration $frontendIP `
-Protocol TCP `
-FrontendPort 3389 `
-BackendPort 3389
$healthProbe = New-AzureRmLoadBalancerProbeConfig -Name "HealthProbe" `
-RequestPath "Default.htm" `
-Protocol http -Port 80 `
-IntervalInSeconds 15 `
-ProbeCount 2
$lbrule = New-AzureRmLoadBalancerRuleConfig -Name "HTTP" `
-FrontendIpConfiguration $frontendIP `
-BackendAddressPool $beAddressPool `
-Probe $healthProbe `
-Protocol Tcp `
-FrontendPort 80 `
-BackendPort 80
$nrplb = New-AzureRmLoadBalancer -ResourceGroupName $currentrg `
-Name "NRP-LB" `
-Location $loc `
-FrontendIpConfiguration $frontendIP `
-InboundNatRule $inboundNATRule1 `
-LoadBalancingRule $lbrule `
-BackendAddressPool $beAddressPool `
-Probe $healthProbe
Must I set the IP configuration for the backend? But how? Or is something earls wrong?
Today new Version 6.2.1 of Azure Powershell came out that. This solves the Problem.
See
https://github.com/Azure/azure-powershell/Releases

Not able to connect through Rasdial in azure ARM VPN connection

I am not able connect to VPN using powershell cmdlet. I use 'rasdial' from a build agent to connect to vpn, so that we can trigger automated tests. The whole process is automated.
Earlier same rasdial command - Rasdial "VPNName" was working perfectly fine with classic model (ASM) of vpn. But, after I migrated to ARM, I am facing this issue. However through UI i.e. clicking on buttons to connect to vpn is working fine but our need is to connect through script.
I am getting a message-
This function is not supported on this system.
NB: I am following this post- https://dzone.com/articles/deconstructing-azure-point
The same workaround worked in ASM but not woking in ARM. What can be another workaround or fix for this ?
I am using below script to create and download the VPN package. I am not sure I am missing something in my script which is causing this issue-
$VNetName = "MYVPN"
$SubName = "Subnet-1"
$GWSubName = "GatewaySubnet"
$VNetPrefix1 = "15.3.0.0/16"
$SubPrefix = "15.3.1.0/24"
$GWSubPrefix = "15.3.200.0/26"
$VPNClientAddressPool = "158.17.201.0/24"
$RG = "VMsRG"
$Location = "West Europe"
$DNS = "15.3.0.0"
$GWName = "GateWay"
$GWIPName = "GateWayIP"
$GWIPconfName = "GateWayIPConfig"
$P2SRootCertName = "XXXXX.cer"
$DeployUserName = "atf#hotmail.com"
$DeployUserPassword = "XXXXX"
$Azurepwd = ConvertTo-SecureString $DeployUserPassword -AsPlainText -Force
$AzureCredential = new-object -typename System.Management.Automation.PSCredential -argumentlist $DeployUserName, $Azurepwd
Add-AzureRmAccount -credential $AzureCredential -SubscriptionName Development
New-AzureRmResourceGroup -Name $RG -Location $Location
$fesub = New-AzureRmVirtualNetworkSubnetConfig -Name $SubName -AddressPrefix $SubPrefix
$gwsub = New-AzureRmVirtualNetworkSubnetConfig -Name $GWSubName -AddressPrefix $GWSubPrefix
New-AzureRmVirtualNetwork -Name $VNetName -ResourceGroupName $RG -Location $Location -AddressPrefix $VNetPrefix1 -Subnet $fesub, $gwsub -DnsServer $DNS
$vnet = Get-AzureRmVirtualNetwork -Name $VNetName -ResourceGroupName $RG
$subnet = Get-AzureRmVirtualNetworkSubnetConfig -Name "GatewaySubnet" -VirtualNetwork $vnet
$pip = New-AzureRmPublicIpAddress -Name $GWIPName -ResourceGroupName $RG -Location $Location -AllocationMethod dynamic
$ipconf = New-AzureRmVirtualNetworkGatewayIpConfig -Name $GWIPconfName -Subnet $subnet -PublicIpAddress $pip
$MyP2SRootCertPubKeyBase64 = "XXXXX"
$p2srootcert = New-AzureRmVpnClientRootCertificate -Name "P2SVNETRootCertName" -PublicCertData $MyP2SRootCertPubKeyBase64
New-AzureRmVirtualNetworkGateway -Name $GWName -ResourceGroupName $RG -Location $Location -IpConfigurations $ipconf -GatewayType Vpn -VpnType RouteBased -EnableBgp $false -GatewaySku Standard -VpnClientAddressPool $VPNClientAddressPool -VpnClientRootCertificates $p2srootcert
Get-AzureRmVpnClientPackage -ResourceGroupName $RG -VirtualNetworkGatewayName $GWName -ProcessorArchitecture Amd64
As I am able to connect using GUI. I hope script is doing it's job.
After 4 Months I got a reply from MS (as I raised a ticket for the same).
They told Rasdial is not supported by Azure VPN Client Package till date. Also, Even after deconstructing-the-azure-point-to-site-vpn lacks addition of route which should be taken care by adding the route explicitly.
So as an workaround I did the steps provided in the blog - http://www.diaryofaninja.com/blog/2013/11/27/deconstructing-the-azure-point-to-site-vpn-for-command-line-usage
However the last part of adding the route is a bit complex. So, for adding route I have created my own PS script-
$Subnet = #("10.0.1.0", "10.0.2.0","10.0.3.0")
$VPNClientAddressPool = "x.x.x"
$Mask = "255.255.0.0"
$azureIpAddress = ""
$VPNCmd = "MYVPNName"
Here x.x.x are the 3 octet that can be found in "GateWay - Point-to-site configuration" of the VPN-
$routeExists = route print | findstr $VPNClientAddressPool
if($routeExists)
{
route delete $Subnet
}
rasdial $VPNCmd > $null
$azureIPAddress = ipconfig | findstr $VPNClientAddressPool
if($azureIPAddress -ne $null)
{
$azureIpAddress = $azureIpAddress.Split(": ")
$azureIpAddress = $azureIpAddress[$azureIpAddress.Length-1]
$azureIpAddress = $azureIpAddress.Trim()
route add $Subnet MASK $Mask $azureIPAddress
}
This solved the purpose for me. Basically You just need to take care of the route add part.
Your PowerShell script seems fine (I didn't try the login and resource group pieces, but everything else works from $fesub on.) except for the third line from the bottom. The -Name tag which you currently have as "P2SVNETRootCertName" needs to be the same as your $P2SRootCertName. For more information, refer to Azure documentation: https://azure.microsoft.com/en-us/documentation/articles/vpn-gateway-howto-point-to-site-rm-ps/
As for Rasdial, another StackOverflow post has answered this: Azure Virtual Network Point-to-Site (ex. Azure Connect) autoconnect
-Bridget [MSFT]

Resources