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 23ce7be

Browse files
add: attach p2s
1 parent 85cb49a commit 23ce7be

File tree

3 files changed

+386
-0
lines changed

3 files changed

+386
-0
lines changed
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: 181 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,181 @@
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 ConvertCidrToUint32Array
85+
{
86+
param($cidrRange)
87+
$cidrRangeParts = $cidrRange.Split(@(".","/"))
88+
$ipnum = ([Convert]::ToUInt32($cidrRangeParts[0]) -shl 24) -bor `
89+
([Convert]::ToUInt32($cidrRangeParts[1]) -shl 16) -bor `
90+
([Convert]::ToUInt32($cidrRangeParts[2]) -shl 8) -bor `
91+
[Convert]::ToUInt32($cidrRangeParts[3])
92+
93+
$maskbits = [System.Convert]::ToInt32($cidrRangeParts[4])
94+
$mask = 0xffffffff
95+
$mask = $mask -shl (32 -$maskbits)
96+
$ipstart = $ipnum -band $mask
97+
$ipend = $ipnum -bor ($mask -bxor 0xffffffff)
98+
return @($ipstart, $ipend)
99+
}
100+
101+
function ConvertUInt32ToIPAddress
102+
{
103+
param($uint32IP)
104+
$v1 = $uint32IP -band 0xff
105+
$v2 = ($uint32IP -shr 8) -band 0xff
106+
$v3 = ($uint32IP -shr 16) -band 0xff
107+
$v4 = ($uint32IP -shr 24)
108+
return "$v4.$v3.$v2.$v1"
109+
}
110+
111+
function CalculateNextAddressPrefix
112+
{
113+
param($virtualNetwork, $prefixLength)
114+
Write-Host "Calculating address prefix."
115+
$startIPAddress = 0
116+
ForEach($addressPrefix in $virtualNetwork.AddressSpace.AddressPrefixes)
117+
{
118+
$endIPAddress = (ConvertCidrToUint32Array $addressPrefix)[1]
119+
If($endIPAddress -gt $startIPAddress)
120+
{
121+
$startIPAddress = $endIPAddress
122+
}
123+
}
124+
$startIPAddress += 1
125+
return (ConvertUInt32ToIPAddress $startIPAddress) + "/" + $prefixLength
126+
}
127+
128+
function CalculateVpnClientAddressPoolPrefix
129+
{
130+
param($gatewaySubnetPrefix)
131+
Write-Host "Calculating VPN client address pool prefix."
132+
If($gatewaySubnetPrefix.StartsWith("10."))
133+
{
134+
return "192.168.0.0/24"
135+
}
136+
else
137+
{
138+
return "172.16.0.0/24"
139+
}
140+
141+
}
142+
143+
Ensure-Login
144+
Select-SubscriptionId -subscriptionId $subscriptionId
145+
146+
$virtualNetwork = Load-VirtualNetwork -resourceGroupName $resourceGroupName -virtualNetworkName $virtualNetworkName
147+
148+
$resourceGroup = Get-AzureRmResourceGroup -Name $resourceGroupName
149+
150+
$certificate = New-SelfSignedCertificate -Type Custom -KeySpec Signature `
151+
-Subject ("CN=$certificateNamePrefix"+"P2SRoot") -KeyExportPolicy Exportable `
152+
-HashAlgorithm sha256 -KeyLength 2048 `
153+
-CertStoreLocation "Cert:\CurrentUser\My" -KeyUsageProperty Sign -KeyUsage CertSign
154+
155+
$certificateThumbprint = $certificate.Thumbprint
156+
157+
New-SelfSignedCertificate -Type Custom -DnsName ($certificateNamePrefix+"P2SChild") -KeySpec Signature `
158+
-Subject ("CN=$certificateNamePrefix"+"P2SChild") -KeyExportPolicy Exportable `
159+
-HashAlgorithm sha256 -KeyLength 2048 `
160+
-CertStoreLocation "Cert:\CurrentUser\My" `
161+
-Signer $certificate -TextExtension @("2.5.29.37={text}1.3.6.1.5.5.7.3.2") | Out-null
162+
163+
$publicRootCertData = [Convert]::ToBase64String((Get-Item cert:\currentuser\my\$certificateThumbprint).RawData)
164+
165+
$gatewaySubnetPrefix = CalculateNextAddressPrefix $virtualNetwork 28
166+
167+
$vpnClientAddressPoolPrefix = CalculateVpnClientAddressPoolPrefix $gatewaySubnetPrefix
168+
169+
Write-Host
170+
171+
# Start the deployment
172+
Write-Host "Starting deployment..."
173+
174+
$templateParameters = @{
175+
virtualNetworkName = $virtualNetworkName
176+
gatewaySubnetPrefix = $gatewaySubnetPrefix
177+
vpnClientAddressPoolPrefix = $vpnClientAddressPoolPrefix
178+
publicRootCertData = $publicRootCertData
179+
}
180+
181+
New-AzureRmResourceGroupDeployment -ResourceGroupName $resourceGroupName -TemplateUri ($scriptUrlBase+'/azuredeploy.json') -TemplateParameterObject $templateParameters
Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
1+
{
2+
"$schema": "http://schema.management.azure.com/schemas/2014-04-01-preview/deploymentTemplate.json#",
3+
"contentVersion": "1.0.0.1",
4+
"parameters": {
5+
"virtualNetworkName": {
6+
"type": "string",
7+
"metadata": {
8+
"description": "Enter virtual network name. If you leave this field blank name will be created by the template."
9+
}
10+
},
11+
"gatewaySubnetPrefix": {
12+
"type": "string",
13+
"metadata": {
14+
"description": "The prefix for the GatewaySubnet where the VirtualNetworkGateway will be deployed. This must be at least /29."
15+
}
16+
},
17+
"vpnClientAddressPoolPrefix": {
18+
"type": "string",
19+
"metadata": {
20+
"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."
21+
}
22+
},
23+
"publicRootCertData": {
24+
"type": "string",
25+
"metadata": {
26+
"description": "Client root certificate data used to authenticate VPN clients."
27+
}
28+
}
29+
},
30+
"variables": {
31+
"gatewayPublicIpAddressName": "[concat('GatewayIP', substring(uniqueString(resourceGroup().id),0,3))]",
32+
"gatewayName": "[concat('Gateway', substring(uniqueString(resourceGroup().id),0,3))]",
33+
"gatewaySku": "Basic",
34+
"gatewaySubnetName": "GatewaySubnet",
35+
"clientRootCertName": "RootCert"
36+
},
37+
"resources": [
38+
{
39+
"name": "[parameters('virtualNetworkName')]",
40+
"type": "Microsoft.Network/virtualNetworks",
41+
"apiVersion": "2018年02月01日",
42+
"dependsOn": [
43+
"[variables('routeTableName')]"
44+
],
45+
"location": "[parameters('location')]",
46+
"properties": {
47+
"mode": "Incremental",
48+
"addressSpace": {
49+
"addressPrefixes": [
50+
"[parameters('gatewaySubnetPrefix')]"
51+
]
52+
},
53+
"subnets": [
54+
{
55+
"name": "[variables('gatewaySubnetName')]",
56+
"properties": {
57+
"addressPrefix": "[parameters('gatewaySubnetPrefix')]"
58+
}
59+
}
60+
]
61+
}
62+
},
63+
{
64+
"apiVersion": "2017年10月01日",
65+
"type": "Microsoft.Network/publicIPAddresses",
66+
"name": "[variables('gatewayPublicIpAddressName')]",
67+
"location": "[resourceGroup().location]",
68+
"properties": {
69+
"publicIPAllocationMethod": "Dynamic"
70+
}
71+
},
72+
{
73+
"apiVersion": "2017年10月01日",
74+
"type": "Microsoft.Network/virtualNetworkGateways",
75+
"name": "[variables('gatewayName')]",
76+
"location": "[resourceGroup().location]",
77+
"dependsOn": [
78+
"[concat('Microsoft.Network/publicIPAddresses/', variables('gatewayPublicIpAddressName'))]",
79+
"[concat('Microsoft.Network/virtualNetworks/', parameters('virtualNetworkName'))]"
80+
],
81+
"properties": {
82+
"ipConfigurations": [
83+
{
84+
"properties": {
85+
"privateIPAllocationMethod": "Dynamic",
86+
"subnet": {
87+
"id": "[resourceId('Microsoft.Network/virtualNetworks/subnets', parameters('virtualNetworkName'), variables('gatewaySubnetName'))]"
88+
},
89+
"publicIPAddress": {
90+
"id": "[resourceId('Microsoft.Network/publicIPAddresses',variables('gatewayPublicIpAddressName'))]"
91+
}
92+
},
93+
"name": "vnetGatewayConfig"
94+
}
95+
],
96+
"sku": {
97+
"name": "[variables('gatewaySku')]",
98+
"tier": "[variables('gatewaySku')]"
99+
},
100+
"gatewayType": "Vpn",
101+
"vpnType": "RouteBased",
102+
"enableBgp": "false",
103+
"vpnClientConfiguration": {
104+
"vpnClientAddressPool": {
105+
"addressPrefixes": [
106+
"[parameters('vpnClientAddressPoolPrefix')]"
107+
]
108+
},
109+
"vpnClientRootCertificates": [
110+
{
111+
"name": "[variables('clientRootCertName')]",
112+
"properties": {
113+
"PublicCertData": "[parameters('publicRootCertData')]"
114+
}
115+
}
116+
]
117+
}
118+
}
119+
}
120+
]
121+
}

0 commit comments

Comments
(0)

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