Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit b0edb39

Browse files
authored
Merge pull request microsoft#1310 from anosov1960/master
Merge activate-pcore-license
2 parents 12211db + ee6acbf commit b0edb39

3 files changed

Lines changed: 286 additions & 0 deletions

File tree

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
---
2+
services: Azure SQL
3+
platforms: Azure
4+
author: anosov1960
5+
ms.author: sashan
6+
ms.date: 06/24/2024
7+
---
8+
9+
# Overview
10+
11+
This script performes a scheduled activation of a SQL Server p-core license.
12+
13+
# Required permissions
14+
15+
Your RBAC role must include the following permissions:
16+
17+
- Microsoft.AzureArcData/SqlLicenses/read
18+
- Microsoft.AzureArcData/SqlLicenses/write
19+
- Microsoft.Management/managementGroups/read
20+
- Microsoft.Resources/subscriptions/read
21+
- Microsoft.Resources/subscriptions/resourceGroups/read
22+
- Microsoft.Support/supporttickets/write
23+
24+
# Creating a Azure runbook
25+
26+
You can scahedule to run the the command as a runbook. To set it up using Azure Portal, follow these steps.
27+
28+
1. Open a command shell on your device and run this command. It will copy the script to your local folder.
29+
```console
30+
curl https://raw.githubusercontent.com/microsoft/sql-server-samples/master/samples/manage/azure-arc-enabled-sql-server/activate-pcore-license/activate-pcore-license.md -o activate-pcore-license.ps1
31+
```
32+
2. [Create a new automation account](https://ms.portal.azure.com/#create/Microsoft.AutomationAccount) or open an existing one.
33+
1. Select *Run as accounts* in the **Account Settings** group, open the automatically created *Azure Run As Account* and note or copy the Display Name property.
34+
1. Select *Runbooks* in the **Process automation** group and click on *Import a runbook*, select the file you downloaded in Step 1 and click **Create**.
35+
1. When import is completed, click the *Publish* button.
36+
1. From the runbook blade, click on the *Link to schedule* button and select an existing schedule or create a new one withand spesify the designed launch time.
37+
1. Click on *Parameters and run settings* and specify the following parameters:
38+
- LICENSEID. Put in teh resourec URI
39+
1. Click **OK** to link to the schedule and **OK** again to create the job.
40+
41+
For more information about the runbooks, see the [Runbook tutorial](https://docs.microsoft.com/en-us/azure/automation/learn/automation-tutorial-runbook-textual-powershell)
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
<#
2+
.DESCRIPTION
3+
This runbook activates a SQL Server license using the Managed Identity
4+
The runbook accepts the following parameters:
5+
6+
-LicenseID (The license resource URI)
7+
8+
.NOTES
9+
AUTHOR: Alexander (Sasha) Nosov
10+
LASTEDIT: June 24, 2024
11+
#>
12+
13+
param (
14+
[Parameter (Mandatory= $true)]
15+
[string] $LicenseId,
16+
)
17+
18+
#
19+
# Suppress warnings
20+
#
21+
Update-AzConfig -DisplayBreakingChangeWarning $false
22+
23+
# Logging in to Azure..."
24+
try
25+
{
26+
Connect-AzAccount -Identity
27+
}
28+
catch {
29+
Write-Error -Message $_.Exception
30+
throw $_.Exception
31+
}
32+
33+
$currentLicense = Get-AzResource -ResourceId $LicenseId
34+
$currentLicense.properties.activationState = "Activated"
35+
$currentLicense | Set-AzResource -Force
36+
Lines changed: 209 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,209 @@
1+
param (
2+
[Parameter (Mandatory=$true)]
3+
[string]$AzureSubscriptionId,
4+
[Parameter (Mandatory=$true)]
5+
[string]$AzureResourceGroupUri,
6+
[Parameter (Mandatory=$true)]
7+
[string]$AzureRegion,
8+
[Parameter (Mandatory=$false)]
9+
[string]$SqlServerInstanceName,
10+
[Parameter (Mandatory=$true)]
11+
[string]$SqlServerAdminAccounts,
12+
[Parameter (Mandatory=$true)]
13+
[string]$SqlServerSvcAccount,
14+
[Parameter (Mandatory=$true)]
15+
[string]$SqlServerSvcPassword,
16+
[Parameter (Mandatory=$true)]
17+
[string]$SqlServerVersion,
18+
[Parameter (Mandatory=$true)]
19+
[string]$SqlServerEdition,
20+
[Parameter (Mandatory=$true)]
21+
[string]$SqlServerProductKey,
22+
[Parameter (Mandatory=$true)]
23+
[string]$isoURL
24+
)
25+
26+
# This function checks if the specified module is imported into the session and if not installes and/or imports it
27+
function LoadModule
28+
{
29+
param (
30+
[parameter(Mandatory = $true)][string] $name
31+
)
32+
33+
$retVal = $true
34+
35+
if (!(Get-Module -Name $name))
36+
{
37+
$retVal = Get-Module -ListAvailable | Where-Object {$_.Name -eq $name}
38+
39+
if ($retVal)
40+
{
41+
try
42+
{
43+
Import-Module $name -ErrorAction SilentlyContinue
44+
}
45+
catch
46+
{
47+
write-host "The request to lload module $($name) failed with the following error:"
48+
write-host $_.Exception.Message
49+
$retVal = $false
50+
}
51+
}
52+
else {
53+
54+
# If module is not imported, not available on disk, but is in online gallery then install and import
55+
if (Find-Module -Name $name) {
56+
Install-Module -Name $name -Force -Verbose -Scope CurrentUser
57+
try
58+
{
59+
Import-Module $name -ErrorAction SilentlyContinue
60+
}
61+
catch
62+
{
63+
write-host "The request to lload module $($name) failed with the following error:"
64+
write-host $_.Exception.Message
65+
$retVal = $false
66+
}
67+
}
68+
else {
69+
70+
# If module is not imported, not available and not in online gallery then abort
71+
write-host "Module $($name) not imported, not available and not in online gallery, exiting."
72+
EXIT 1
73+
}
74+
}
75+
}
76+
77+
return $retVal
78+
}
79+
80+
try {
81+
82+
#Step 0: Ensure PS version and load missing Azure modules
83+
#
84+
# Suppress warnings
85+
#
86+
Update-AzConfig -DisplayBreakingChangeWarning $false
87+
88+
# Load required modules
89+
$requiredModules = @(
90+
"AzureAD",
91+
"Az.Accounts",
92+
"Az.ConnectedMachine",
93+
"Az.ResourceGraph"
94+
)
95+
$requiredModules | Foreach-Object {LoadModule $_}
96+
97+
# Step 1: Check if setup.exe is already running and kill it if so
98+
if (Get-Process setup -ErrorAction SilentlyContinue) {
99+
Stop-Process -Name setup -Force
100+
Write-Host "Existing setup.exe process terminated."
101+
}
102+
103+
# Step 2: Log in to Azure
104+
Connect-AzAccount
105+
$subscription = Get-AzSubscription -SubscriptionId $AzureSubscriptionId -ErrorAction SilentlyContinue
106+
if (-not $subscription) {
107+
Write-Error "Azure subscription with ID '$AzureSubscriptionId' does not exist."
108+
exit
109+
}
110+
111+
# Step 2: Block auto-onboarding to Arc by tagging the resource group
112+
$existingResourceGroup = Get-AzResourceGroup -Name $AzureResourceGroupUri -ErrorAction SilentlyContinue
113+
114+
if ($existingResourceGroup) {
115+
Write-Host "Resource group '$AzureResourceGroupUri' exists."
116+
} else {
117+
Write-Error "Resource group '$AzureResourceGroupUri' does not exist."
118+
exit
119+
}
120+
$tags = @{"ArcOnboarding" = "Blocked"}
121+
Set-AzResourceGroup -Name $AzureResourceGroupUri -Tag $tags
122+
123+
# Step 3: Onboard the VM to Azure Arc
124+
$hostName = (Get-WmiObject Win32_ComputerSystem).Name
125+
126+
New-AzConnectedMachine -ResourceGroupName $AzureResourceGroupUri -Name $hostName -Location $AzureRegion
127+
128+
# Step 4: Automatically download installable media
129+
130+
$isoLocation = "C:\download\SQLServer.iso"
131+
if (!(Test-Path -Path $isoLocation)) {
132+
$freeSpace = (Get-PSDrive -Name C).Free
133+
$isoSize = (Invoke-WebRequest -Uri $isoURL -Method Head).Headers.'Content-Length'
134+
if ($freeSpace -gt $isoSize) {
135+
Start-BitsTransfer -Source $isoURL -Destination $isoLocation
136+
} else {
137+
throw "Not enough free space to download the ISO."
138+
}
139+
}
140+
141+
# Step 5: Mount the ISO file as a volume
142+
$volumeInfo = Mount-DiskImage -ImagePath $isoLocation -PassThru | Get-Volume
143+
144+
# Step 6: Run unattended SQL Server setup from the mounted volume
145+
$setupPath = ($volumeInfo.DriveLetter + ":\setup.exe")
146+
$argumentList = "
147+
/q
148+
/ACTION=Install
149+
/FEATURES=SQL
150+
/INSTANCEDIR=C:\SQL
151+
/SQLSYSADMINACCOUNTS='$($SqlServerAdminAccounts)'
152+
/SQLSVCACCOUNT='$($SqlServerSvcAccount)'
153+
/SQLSVCPASSWORD='$($SqlServerSvcPassword)'
154+
/AGTSVCACCOUNT='$($SqlServerSvcAccount)'
155+
/AGTSVCPASSWORD='$($SqlServerSvcPassword)'
156+
/IACCEPTSQLSERVERLICENSETERMS
157+
/PID='$($SqlServerProductKey)'
158+
/Edition='$($SqlServerEdition)'
159+
"
160+
if ($SqlServerInstanceName) {
161+
$argumentList += "/INSTANCENAME='$($SqlServerInstanceName)'"
162+
}
163+
164+
Start-Process -FilePath $setupPath -ArgumentList $argumentList
165+
166+
# Step 7: Install SQL Arc extension with LT=PAYG
167+
$Settings = @{
168+
SqlManagement = @{ IsEnabled = $true };
169+
LicenseType = "PAYG";
170+
enableExtendedSecurityUpdates = $True;
171+
esuLastUpdatedTimestamp = [DateTime]::UtcNow.ToString('yyyy-MM-ddTHH:mm:ss.fffZ')
172+
}
173+
New-AzConnectedMachineExtension -ResourceGroupName $AzureResourceGroupUri -MachineName $hostName -Name "WindowsAgent.SqlServer" -Publisher "Microsoft.AzureData" -Type "WindowsAgent.SqlServer" -TypeHandlerVersion "1.0" -Settings $settings
174+
175+
# Step 9: Dismount the ISO file after installation
176+
Dismount-DiskImage -ImagePath $isoLocation
177+
178+
# Step 10: Remove the media from the local file system
179+
Remove-Item -Path $isoLocation
180+
181+
# Step 8: Display the status of the Azure resource for Arc-enabled SQL Server
182+
$query = "
183+
resources
184+
| where type =~ 'microsoft.hybridcompute/machines'
185+
| where resourceGroup =~ '$($AzureResourceGroupUri)'
186+
| where properties.detectedProperties.mssqldiscovered == 'true'
187+
| extend machineIdHasSQLServerDiscovered = id
188+
| project name, machineIdHasSQLServerDiscovered, resourceGroup, subscriptionId
189+
| join kind= leftouter (
190+
resources
191+
| where type == 'microsoft.hybridcompute/machines/extensions' | where properties.type in ('WindowsAgent.SqlServer','LinuxAgent.SqlServer')
192+
| extend machineIdHasSQLServerExtensionInstalled = iff(id contains '/extensions/WindowsAgent.SqlServer' or id contains '/extensions/LinuxAgent.SqlServer', substring(id, 0, indexof(id, '/extensions/')), '')
193+
| project Extension_State = properties.provisioningState,
194+
License_Type = properties.settings.LicenseType,
195+
ESU = iff(notnull(properties.settings.enableExtendedSecurityUpdates), iff(properties.settings.enableExtendedSecurityUpdates == true,'enabled','disabled'), ''),
196+
Extension_Version = properties.instanceView.typeHandlerVersion,
197+
machineIdHasSQLServerExtensionInstalled)on $left.machineIdHasSQLServerDiscovered == $right.machineIdHasSQLServerExtensionInstalled
198+
| where isnotempty(machineIdHasSQLServerExtensionInstalled)
199+
| project-away machineIdHasSQLServerDiscovered, machineIdHasSQLServerExtensionInstalled
200+
"
201+
Search-AzGraph -Query "$($query)"
202+
203+
} catch {
204+
Write-Error "An error occurred: $_"
205+
# You can add additional error handling logic here
206+
} finally {
207+
# Cleanup or other actions that should always run
208+
Write-Host "Script execution completed."
209+
}

0 commit comments

Comments
 (0)