Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 6bf4acb

Browse files
Merge pull request microsoft#432 from srdan-bozovic-msft/master
Add: attach vpn gateway sample
2 parents e5aa23a + 67950e1 commit 6bf4acb

File tree

4 files changed

+389
-0
lines changed

4 files changed

+389
-0
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
#placeholder
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
# Attaches VPN gateway to Managed Instance virtual network
2+
3+
### Contents
4+
5+
[About this sample](#about-this-sample)<br/>
6+
[Before you begin](#before-you-begin)<br/>
7+
[Run this sample](#run-this-sample)<br/>
8+
[Sample details](#sample-details)<br/>
9+
[Disclaimers](#disclaimers)<br/>
10+
[Related links](#related-links)<br/>
11+
12+
13+
<a name=about-this-sample></a>
14+
15+
## About this sample
16+
17+
- **Applies to:** Azure SQL Database
18+
- **Key features:** Managed Instance
19+
- **Workload:** n/a
20+
- **Programming Language:** PowerShell
21+
- **Authors:** Srdan Bozovic
22+
- **Update history:** n/a
23+
24+
<a name=before-you-begin></a>
25+
26+
## Before you begin
27+
28+
To run this sample, you need the following prerequisites.
29+
30+
**Software prerequisites:**
31+
32+
1. PowerShell 5.1
33+
2. Azure PowerShell 5.4.2 or higher
34+
35+
**Azure prerequisites:**
36+
37+
1. Permission to manage Azure virtual network
38+
39+
<a name=run-this-sample></a>
40+
41+
## Run this sample
42+
43+
Run the script below from Windows PowerShell
44+
45+
```powershell
46+
47+
$scriptUrlBase = 'https://raw.githubusercontent.com/Microsoft/sql-server-samples/master/samples/manage/azure-sql-db-managed-instance/attach-vpn-gateway'
48+
49+
$parameters = @{
50+
subscriptionId = '<subscriptionId>'
51+
resourceGroupName = '<resourceGroupName>'
52+
virtualNetworkName = '<virtualNetworkName>'
53+
certificateNamePrefix = '<certificateNamePrefix>'
54+
}
55+
56+
Invoke-Command -ScriptBlock ([Scriptblock]::Create((iwr ($scriptUrlBase+'/attachVPNGateway.ps1?t='+ [DateTime]::Now.Ticks)).Content)) -ArgumentList $parameters, $scriptUrlBase
57+
58+
```
59+
60+
<a name=sample-details></a>
61+
62+
## Sample details
63+
64+
This sample shows how to attach VPN Gateway to Managed Instance virtual network using PowerShell
65+
66+
This is done in three steps:
67+
- Create and install certificates on client machine
68+
- Calculate future VPN Gateway subnet IP range
69+
- Deploy ARM template that will attach VPN Gateway to subnet
70+
71+
<a name=disclaimers></a>
72+
73+
## Disclaimers
74+
The scripts and this guide are copyright Microsoft Corporations and are provided as samples. They are not part of any Azure service and are not covered by any SLA or other Azure-related agreements. They are provided as-is with no warranties express or implied. Microsoft takes no responsibility for the use of the scripts or the accuracy of this document. Familiarize yourself with the scripts before using them.
75+
76+
<a name=related-links></a>
77+
78+
## Related Links
79+
<!-- Links to more articles. Remember to delete "en-us" from the link path. -->
80+
81+
For more information, see these articles:
82+
83+
- [What is a Managed Instance (preview)?](https://docs.microsoft.com/azure/sql-database/sql-database-managed-instance)
84+
- [Configure a VNet for Azure SQL Database Managed Instance](https://docs.microsoft.com/azure/sql-database/sql-database-managed-instance-vnet-configuration)
Lines changed: 202 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,202 @@
1+
$parameters = $args[0]
2+
3+
$subscriptionId = $parameters['subscriptionId']
4+
$resourceGroupName = $parameters['resourceGroupName']
5+
$virtualNetworkName = $parameters['virtualNetworkName']
6+
$certificateNamePrefix = $parameters['certificateNamePrefix']
7+
$force = $parameters['force']
8+
9+
$scriptUrlBase = $args[1]
10+
11+
function Ensure-Login ()
12+
{
13+
$context = Get-AzureRmContext
14+
If($context.Subscription -eq $null)
15+
{
16+
Write-Host "Loging in ..."
17+
If((Login-AzureRmAccount -ErrorAction SilentlyContinue -ErrorVariable Errors) -eq $null)
18+
{
19+
Write-Host ("Login failed: {0}" -f $Errors[0].Exception.Message) -ForegroundColor Red
20+
Break
21+
}
22+
}
23+
Write-Host "User logedin." -ForegroundColor Green
24+
}
25+
26+
function Select-SubscriptionId {
27+
param (
28+
$subscriptionId
29+
)
30+
Write-Host "Selecting subscription '$subscriptionId'."
31+
$context = Get-AzureRmContext
32+
If($context.Subscription.Id -ne $subscriptionId)
33+
{
34+
Try
35+
{
36+
Select-AzureRmSubscription -SubscriptionId $subscriptionId -ErrorAction Stop | Out-null
37+
}
38+
Catch
39+
{
40+
Write-Host "Subscription selection failed: $_" -ForegroundColor Red
41+
Break
42+
}
43+
}
44+
Write-Host "Subscription selected." -ForegroundColor Green
45+
}
46+
47+
function Load-VirtualNetwork {
48+
param (
49+
$resourceGroupName,
50+
$virtualNetworkName
51+
)
52+
Write-Host("Loading virtual network '{0}' in resource group '{1}'." -f $virtualNetworkName, $resourceGroupName)
53+
$virtualNetwork = Get-AzureRmVirtualNetwork -ResourceGroupName $resourceGroupName -Name $virtualNetworkName -ErrorAction SilentlyContinue
54+
If($virtualNetwork.Id -ne $null)
55+
{
56+
Write-Host "Virtual network loaded." -ForegroundColor Green
57+
return $virtualNetwork
58+
}
59+
else
60+
{
61+
Write-Host "Virtual network not found." -ForegroundColor Red
62+
Break
63+
}
64+
}
65+
66+
function Load-ResourceGroup {
67+
param (
68+
$resourceGroupName
69+
)
70+
Write-Host("Loading resource group '{0}'." -f $resourceGroupName)
71+
$resourceGroup = Get-AzureRmResourceGroup -Name $resourceGroupName
72+
If($resourceGroup.ResourceId -ne $null)
73+
{
74+
Write-Host "Resource group loaded." -ForegroundColor Green
75+
return $resourceGroup
76+
}
77+
else
78+
{
79+
Write-Host "Resource group not found." -ForegroundColor Red
80+
Break
81+
}
82+
}
83+
84+
function Set-VirtualNetwork
85+
{
86+
param($virtualNetwork)
87+
88+
Write-Host "Applying changes to the virtual network."
89+
Try
90+
{
91+
Set-AzureRmVirtualNetwork -VirtualNetwork $virtualNetwork -ErrorAction Stop | Out-Null
92+
}
93+
Catch
94+
{
95+
Write-Host "Failed: $_" -ForegroundColor Red
96+
}
97+
98+
}
99+
100+
function ConvertCidrToUint32Array
101+
{
102+
param($cidrRange)
103+
$cidrRangeParts = $cidrRange.Split(@(".","/"))
104+
$ipnum = ([Convert]::ToUInt32($cidrRangeParts[0]) -shl 24) -bor `
105+
([Convert]::ToUInt32($cidrRangeParts[1]) -shl 16) -bor `
106+
([Convert]::ToUInt32($cidrRangeParts[2]) -shl 8) -bor `
107+
[Convert]::ToUInt32($cidrRangeParts[3])
108+
109+
$maskbits = [System.Convert]::ToInt32($cidrRangeParts[4])
110+
$mask = 0xffffffff
111+
$mask = $mask -shl (32 -$maskbits)
112+
$ipstart = $ipnum -band $mask
113+
$ipend = $ipnum -bor ($mask -bxor 0xffffffff)
114+
return @($ipstart, $ipend)
115+
}
116+
117+
function ConvertUInt32ToIPAddress
118+
{
119+
param($uint32IP)
120+
$v1 = $uint32IP -band 0xff
121+
$v2 = ($uint32IP -shr 8) -band 0xff
122+
$v3 = ($uint32IP -shr 16) -band 0xff
123+
$v4 = ($uint32IP -shr 24)
124+
return "$v4.$v3.$v2.$v1"
125+
}
126+
127+
function CalculateNextAddressPrefix
128+
{
129+
param($virtualNetwork, $prefixLength)
130+
Write-Host "Calculating address prefix."
131+
$startIPAddress = 0
132+
ForEach($addressPrefix in $virtualNetwork.AddressSpace.AddressPrefixes)
133+
{
134+
$endIPAddress = (ConvertCidrToUint32Array $addressPrefix)[1]
135+
If($endIPAddress -gt $startIPAddress)
136+
{
137+
$startIPAddress = $endIPAddress
138+
}
139+
}
140+
$startIPAddress += 1
141+
return (ConvertUInt32ToIPAddress $startIPAddress) + "/" + $prefixLength
142+
}
143+
144+
function CalculateVpnClientAddressPoolPrefix
145+
{
146+
param($gatewaySubnetPrefix)
147+
Write-Host "Calculating VPN client address pool prefix."
148+
If($gatewaySubnetPrefix.StartsWith("10."))
149+
{
150+
return "192.168.0.0/24"
151+
}
152+
else
153+
{
154+
return "172.16.0.0/24"
155+
}
156+
157+
}
158+
159+
Ensure-Login
160+
Select-SubscriptionId -subscriptionId $subscriptionId
161+
162+
$virtualNetwork = Load-VirtualNetwork -resourceGroupName $resourceGroupName -virtualNetworkName $virtualNetworkName
163+
164+
$resourceGroup = Get-AzureRmResourceGroup -Name $resourceGroupName
165+
166+
$certificate = New-SelfSignedCertificate -Type Custom -KeySpec Signature `
167+
-Subject ("CN=$certificateNamePrefix"+"P2SRoot") -KeyExportPolicy Exportable `
168+
-HashAlgorithm sha256 -KeyLength 2048 `
169+
-CertStoreLocation "Cert:\CurrentUser\My" -KeyUsageProperty Sign -KeyUsage CertSign
170+
171+
$certificateThumbprint = $certificate.Thumbprint
172+
173+
New-SelfSignedCertificate -Type Custom -DnsName ($certificateNamePrefix+"P2SChild") -KeySpec Signature `
174+
-Subject ("CN=$certificateNamePrefix"+"P2SChild") -KeyExportPolicy Exportable `
175+
-HashAlgorithm sha256 -KeyLength 2048 `
176+
-CertStoreLocation "Cert:\CurrentUser\My" `
177+
-Signer $certificate -TextExtension @("2.5.29.37={text}1.3.6.1.5.5.7.3.2") | Out-null
178+
179+
$publicRootCertData = [Convert]::ToBase64String((Get-Item cert:\currentuser\my\$certificateThumbprint).RawData)
180+
181+
$gatewaySubnetPrefix = CalculateNextAddressPrefix $virtualNetwork 28
182+
183+
$vpnClientAddressPoolPrefix = CalculateVpnClientAddressPoolPrefix $gatewaySubnetPrefix
184+
185+
$virtualNetwork.AddressSpace.AddressPrefixes.Add($gatewaySubnetPrefix)
186+
Add-AzureRmVirtualNetworkSubnetConfig -Name GatewaySubnet -VirtualNetwork $virtualNetwork -AddressPrefix $gatewaySubnetPrefix | Out-Null
187+
188+
Set-VirtualNetwork $virtualNetwork
189+
190+
Write-Host
191+
192+
# Start the deployment
193+
Write-Host "Starting deployment..."
194+
195+
$templateParameters = @{
196+
virtualNetworkName = $virtualNetworkName
197+
gatewaySubnetPrefix = $gatewaySubnetPrefix
198+
vpnClientAddressPoolPrefix = $vpnClientAddressPoolPrefix
199+
publicRootCertData = $publicRootCertData
200+
}
201+
202+
New-AzureRmResourceGroupDeployment -ResourceGroupName $resourceGroupName -TemplateUri ($scriptUrlBase+'/azuredeploy.json?t='+ [DateTime]::Now.Ticks) -TemplateParameterObject $templateParameters
Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
{
2+
"$schema": "http://schema.management.azure.com/schemas/2014-04-01-preview/deploymentTemplate.json#",
3+
"contentVersion": "1.0.0.1",
4+
"parameters": {
5+
"location": {
6+
"type": "string",
7+
"defaultValue": "[resourceGroup().location]",
8+
"metadata": {
9+
"description": "Enter location. If you leave this field blank resource group location would be used."
10+
}
11+
},
12+
"virtualNetworkName": {
13+
"type": "string",
14+
"metadata": {
15+
"description": "Enter virtual network name. If you leave this field blank name will be created by the template."
16+
}
17+
},
18+
"gatewaySubnetPrefix": {
19+
"type": "string",
20+
"metadata": {
21+
"description": "The prefix for the GatewaySubnet where the VirtualNetworkGateway will be deployed. This must be at least /29."
22+
}
23+
},
24+
"vpnClientAddressPoolPrefix": {
25+
"type": "string",
26+
"metadata": {
27+
"description": "The IP address range from which VPN clients will receive an IP address when connected. Range specified must not overlap with on-premise network."
28+
}
29+
},
30+
"publicRootCertData": {
31+
"type": "string",
32+
"metadata": {
33+
"description": "Client root certificate data used to authenticate VPN clients."
34+
}
35+
}
36+
},
37+
"variables": {
38+
"gatewayPublicIpAddressName": "[concat('GatewayIP-', uniqueString(resourceGroup().id))]",
39+
"gatewayName": "[concat('Gateway-', uniqueString(resourceGroup().id))]",
40+
"gatewaySku": "Basic",
41+
"gatewaySubnetName": "GatewaySubnet",
42+
"clientRootCertName": "RootCert"
43+
},
44+
"resources": [
45+
{
46+
"apiVersion": "2017年10月01日",
47+
"type": "Microsoft.Network/publicIPAddresses",
48+
"name": "[variables('gatewayPublicIpAddressName')]",
49+
"location": "[resourceGroup().location]",
50+
"properties": {
51+
"publicIPAllocationMethod": "Dynamic"
52+
}
53+
},
54+
{
55+
"apiVersion": "2017年10月01日",
56+
"type": "Microsoft.Network/virtualNetworkGateways",
57+
"name": "[variables('gatewayName')]",
58+
"location": "[resourceGroup().location]",
59+
"dependsOn": [
60+
"[concat('Microsoft.Network/publicIPAddresses/', variables('gatewayPublicIpAddressName'))]"
61+
],
62+
"properties": {
63+
"ipConfigurations": [
64+
{
65+
"properties": {
66+
"privateIPAllocationMethod": "Dynamic",
67+
"subnet": {
68+
"id": "[resourceId('Microsoft.Network/virtualNetworks/subnets', parameters('virtualNetworkName'), variables('gatewaySubnetName'))]"
69+
},
70+
"publicIPAddress": {
71+
"id": "[resourceId('Microsoft.Network/publicIPAddresses',variables('gatewayPublicIpAddressName'))]"
72+
}
73+
},
74+
"name": "vnetGatewayConfig"
75+
}
76+
],
77+
"sku": {
78+
"name": "[variables('gatewaySku')]",
79+
"tier": "[variables('gatewaySku')]"
80+
},
81+
"gatewayType": "Vpn",
82+
"vpnType": "RouteBased",
83+
"enableBgp": "false",
84+
"vpnClientConfiguration": {
85+
"vpnClientAddressPool": {
86+
"addressPrefixes": [
87+
"[parameters('vpnClientAddressPoolPrefix')]"
88+
]
89+
},
90+
"vpnClientRootCertificates": [
91+
{
92+
"name": "[variables('clientRootCertName')]",
93+
"properties": {
94+
"PublicCertData": "[parameters('publicRootCertData')]"
95+
}
96+
}
97+
]
98+
}
99+
}
100+
}
101+
]
102+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /