Ed Chalstrey
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # [SHM Deployment - Configure DC Script fails](https://github.com/alan-turing-institute/data-safe-haven/issues/948) ## Debug idea ### test script to show whether using @params impacts string quotation ```pwsh function print-params{ param( [Parameter(Mandatory = $true)] [string]$parameters ) Write-Output $parameters } $keyvals = { bob = "`"quoted string"`", mary = "nonquoted string" } print-params -parameters $keyvals $params = @{ parameters = $keyvals } print-params @params ``` Output shows no difference on the method used: ``` bob = "`"quoted string"`", mary = "nonquoted string" bob = "`"quoted string"`", mary = "nonquoted string" ``` ## Diff of Deployments.psm1 to find the differences in function Invoke-RemoteScript ``` git diff e73a404 76fa6427 deployment/common/Deployments.psm1 ``` ```pwsh @@ -1194,19 +1147,23 @@ function Invoke-RemoteScript { $Script | Out-File -FilePath $tmpScriptFile.FullName $ScriptPath = $tmpScriptFile.FullName } - # Setup the remote command - if ($Shell -eq "PowerShell") { - $commandId = "RunPowerShellScript" - } else { - $commandId = "RunShellScript" - } # Run the remote command - if ($Parameter) { - $result = Invoke-AzVMRunCommand -Name $VMName -ResourceGroupName $ResourceGroupName -CommandId $commandId -ScriptPath $ScriptPath -Parameter $Parameter - $success = $? - } else { - $result = Invoke-AzVMRunCommand -Name $VMName -ResourceGroupName $ResourceGroupName -CommandId $commandId -ScriptPath $ScriptPath - $success = $? + $params = @{} + if ($Parameter) { $params["Parameter"] = $Parameter } + $params["CommandId"] = ($Shell -eq "PowerShell") ? "RunPowerShellScript" : "RunShellScript" + try { + # Catch failures from running two commands in close proximity and rerun + while ($true) { + try { + $result = Invoke-AzVMRunCommand -Name $VMName -ResourceGroupName $ResourceGroupName -ScriptPath $ScriptPath @params -ErrorAction Stop + $success = $? + break + } catch [Microsoft.Azure.Commands.Compute.Common.ComputeCloudException] { + if (-not ($_.Exception.Message -match "Run command extension execution is in progress")) { throw } + } + } + } catch { + Add-LogMessage -Level Fatal "Running '$ScriptPath' on remote VM '$VMName' failed." -Exception $_.Exception } $success = $success -and ($result.Status -eq "Succeeded") foreach ($outputStream in $result.Value) { @@ -1222,12 +1179,12 @@ function Invoke-RemoteScript { # Check for success or failure if ($success) { Add-LogMessage -Level Success "Remote script execution succeeded" + if (-not $SuppressOutput) { Write-Host ($result.Value | Out-String) } } else { - Add-LogMessage -Level Info "Script output:`n$($result | Out-String)" + Add-LogMessage -Level Info "Script output:" + Write-Host ($result | Out-String) Add-LogMessage -Level Fatal "Remote script execution has failed. Please check the output above before re-running this script." } - # Wait 10s to allow the run command extension to register as completed - Start-Sleep 10 return $result } Export-ModuleMember -Function Invoke-RemoteScript ``` ## Diff of Setup_SHM_DC.ps1 ```pwsh > git diff e73a404 76fa6427 deployment/safe_haven_management_environment/setup/Setup_SHM_DC.ps1 diff --git a/deployment/safe_haven_management_environment/setup/Setup_SHM_DC.ps1 b/deployment/safe_haven_management_environment/setup/Setup_SHM_DC.ps1 index ea5865fe..17ae2d04 100644 --- a/deployment/safe_haven_management_environment/setup/Setup_SHM_DC.ps1 +++ b/deployment/safe_haven_management_environment/setup/Setup_SHM_DC.ps1 @@ -4,18 +4,18 @@ param( ) Import-Module Az -ErrorAction Stop +Import-Module $PSScriptRoot/../../common/AzureStorage -Force -ErrorAction Stop Import-Module $PSScriptRoot/../../common/Configuration -Force -ErrorAction Stop Import-Module $PSScriptRoot/../../common/Deployments -Force -ErrorAction Stop -Import-Module $PSScriptRoot/../../common/GenerateSasToken -Force -ErrorAction Stop Import-Module $PSScriptRoot/../../common/Logging -Force -ErrorAction Stop Import-Module $PSScriptRoot/../../common/Security -Force -ErrorAction Stop # Get config and original context before changing subscription # ------------------------------------------------------------ -$config = Get-ShmFullConfig $shmId +$config = Get-ShmConfig $shmId $originalContext = Get-AzContext -$null = Set-AzContext -SubscriptionId $config.subscriptionName +$null = Set-AzContext -SubscriptionId $config.subscriptionName -ErrorAction Stop # Setup boot diagnostics resource group and storage account @@ -36,14 +36,6 @@ Add-LogMessage -Level Info "Ensuring that blob storage containers exist..." foreach ($containerName in ("shm-dsc-dc", "shm-configuration-dc", "sre-rds-sh-packages")) { $null = Deploy-StorageContainer -Name $containerName -StorageAccount $storageAccount } -# NB. we would like the NPS VM to log to a database, but this is not yet working -# # Create file storage shares -# foreach ($shareName in ("sqlserver")) { -# if (-not (Get-AzStorageShare -Context $storageAccount.Context | Where-Object { $_.Name -eq "$shareName" })) { -# Add-LogMessage -Level Info "Creating share '$shareName' in storage account '$($config.storage.artifacts.accountName)'" -# New-AzStorageShare -Name $shareName -Context $storageAccount.Context; -# } -# } # Upload artifacts @@ -94,41 +86,30 @@ $filename = $httpContent.Links | Where-Object { $_.href -like "*installer.msi" } $version = ($filename -split "-")[2] Start-AzStorageBlobCopy -AbsoluteUri "$($baseUri.Replace('latest', $version))/$filename" -DestContainer "sre-rds-sh-packages" -DestBlob "PuTTY_x64.msi" -DestContext $storageAccount.Context - Force $success = $success -and $? -# WinSCP -$httpContent = Invoke-WebRequest -Uri "https://winscp.net/eng/download.php" -$filename = $httpContent.Links | Where-Object { $_.href -like "*Setup.exe" } | ForEach-Object { ($_.href -split "/")[-1] } -$absoluteUri = (Invoke-WebRequest -Uri "https://winscp.net/download/$filename").Links | Where-Object { $_.href -like "*winscp.net*$filename*" } | ForEach-Object { $_.href } | Select-Object - First 1 -Start-AzStorageBlobCopy -AbsoluteUri "$absoluteUri" -DestContainer "sre-rds-sh-packages" -DestBlob "WinSCP_x32.exe" -DestContext $storageAccount.Context -Force -$success = $success -and $? if ($success) { Add-LogMessage -Level Success "Uploaded Windows package installers" } else { Add-LogMessage -Level Fatal "Failed to upload Windows package installers!" } -# NB. we would like the NPS VM to log to a database, but this is not yet working -# Add-LogMessage -Level Info "Uploading SQL server installation files to storage account '$($config.storage.artifacts.accountName)'" -# # URI to Azure File copy does not support 302 redirect, so get the latest working endpoint redirected from "https://go.microsoft.com/fwlink/?linkid=853017" -# Start-AzStorageFileCopy -AbsoluteUri "https://download.microsoft.com/download/5/E/9/5E9B18CC-8FD5-467E-B5BF-BADE39C51F73/SQLServer2017-SSEI-Expr.exe" -DestShareName "sqlserver" -DestFilePa th "SQLServer2017-SSEI-Expr.exe" -DestContext $storageAccount.Context -Force -# # URI to Azure File copy does not support 302 redirect, so get the latest working endpoint redirected from "https://go.microsoft.com/fwlink/?linkid=2088649" -# Start-AzStorageFileCopy -AbsoluteUri "https://download.microsoft.com/download/5/4/E/54EC1AD8-042C-4CA3-85AB-BA307CF73710/SSMS-Setup-ENU.exe" -DestShareName "sqlserver" -DestFilePath "SSMS- Setup-ENU.exe" -DestContext $storageAccount.Context -Force + # Create SHM DC resource group if it does not exist # ------------------------------------------------- $null = Deploy-ResourceGroup -Name $config.dc.rg -Location $config.location -# Retrieve usernames/passwords from the keyvault -# ---------------------------------------------- -Add-LogMessage -Level Info "Creating/retrieving secrets from key vault '$($config.keyVault.name)'..." -$domainAdminUsername = Resolve-KeyVaultSecret -VaultName $config.keyVault.name -SecretName $config.keyVault.secretNames.domainAdminUsername -DefaultValue "domain$($config.id)admin".ToLower() -$domainAdminPassword = Resolve-KeyVaultSecret -VaultName $config.keyVault.name -SecretName $config.keyVault.secretNames.domainAdminPassword -DefaultLength 20 -$safemodeAdminPassword = Resolve-KeyVaultSecret -VaultName $config.keyVault.name -SecretName $config.dc.safemodePasswordSecretName -DefaultLength 20 +# Retrieve usernames/passwords from the Key Vault +# ----------------------------------------------- +Add-LogMessage -Level Info "Creating/retrieving secrets from Key Vault '$($config.keyVault.name)'..." +$domainAdminUsername = Resolve-KeyVaultSecret -VaultName $config.keyVault.name -SecretName $config.keyVault.secretNames.domainAdminUsername -DefaultValue "domain$($config.id)admin".ToLower() -AsPlaintext +$domainAdminPassword = Resolve-KeyVaultSecret -VaultName $config.keyVault.name -SecretName $config.keyVault.secretNames.domainAdminPassword -DefaultLength 20 -AsPlaintext +$safemodeAdminPassword = Resolve-KeyVaultSecret -VaultName $config.keyVault.name -SecretName $config.dc.safemodePasswordSecretName -DefaultLength 20 -AsPlaintext # Deploy SHM DC from template # --------------------------- Add-LogMessage -Level Info "Deploying domain controller (DC) from template..." -$artifactSasToken = New-ReadOnlyAccountSasToken -subscriptionName $config.subscriptionName -resourceGroup $config.storage.artifacts.rg -AccountName $config.storage.artifacts.accountName +$artifactSasToken = New-ReadOnlyStorageAccountSasToken -subscriptionName $config.subscriptionName -resourceGroup $config.storage.artifacts.rg -AccountName $config.storage.artifacts.accountNa me $params = @{ Administrator_Password = (ConvertTo-SecureString $domainAdminPassword -AsPlainText -Force) Administrator_User = $domainAdminUsername @@ -169,7 +150,7 @@ Add-LogMessage -Level Info "Importing configuration artifacts for: $($config.dc. # Get list of blobs in the storage account $storageContainerName = "shm-configuration-dc" $blobNames = Get-AzStorageBlob -Container $storageContainerName -Context $storageAccount.Context | ForEach-Object { $_.Name } -$artifactSasToken = New-ReadOnlyAccountSasToken -subscriptionName $config.subscriptionName -resourceGroup $config.storage.artifacts.rg -AccountName $config.storage.artifacts.accountName +$artifactSasToken = New-ReadOnlyStorageAccountSasToken -subscriptionName $config.subscriptionName -resourceGroup $config.storage.artifacts.rg -AccountName $config.storage.artifacts.accountNa me $remoteInstallationDir = "C:\Installation" # Run remote script $scriptPath = Join-Path $PSScriptRoot ".." "remote" "create_dc" "scripts" "Import_Artifacts.ps1" -Resolve @@ -180,8 +161,7 @@ $params = @{ storageContainerName = "`"$storageContainerName`"" sasToken = "`"$artifactSasToken`"" } -$result = Invoke-RemoteScript -Shell "PowerShell" -ScriptPath $scriptPath -VMName $config.dc.vmName -ResourceGroupName $config.dc.rg -Parameter $params -Write-Output $result.Value +$null = Invoke-RemoteScript -Shell "PowerShell" -ScriptPath $scriptPath -VMName $config.dc.vmName -ResourceGroupName $config.dc.rg -Parameter $params # Configure Active Directory remotely @@ -190,11 +170,11 @@ Add-LogMessage -Level Info "Configuring Active Directory for: $($config.dc.vmNam # Fetch user and OU details $userAccounts = $config.users.computerManagers + $config.users.serviceAccounts foreach ($user in $userAccounts.Keys) { - $userAccounts[$user]["password"] = Resolve-KeyVaultSecret -VaultName $config.keyVault.name -SecretName $userAccounts[$user]["passwordSecretName"] -DefaultLength 20 + $userAccounts[$user]["password"] = Resolve-KeyVaultSecret -VaultName $config.keyVault.name -SecretName $userAccounts[$user]["passwordSecretName"] -DefaultLength 20 -AsPlaintext } # Run remote script $scriptTemplate = Join-Path $PSScriptRoot ".." "remote" "create_dc" "scripts" "Active_Directory_Configuration.ps1" | Get-Item | Get-Content -Raw -$script = $scriptTemplate.Replace("<ou-data-servers-name>", $config.domain.ous.dataServers.name). +$script = $scriptTemplate.Replace("<ou-database-servers-name>", $config.domain.ous.databaseServers.name). Replace("<ou-identity-servers-name>", $config.domain.ous.identityServers.name). Replace("<ou-linux-servers-name>", $config.domain.ous.linuxServers.name). Replace("<ou-rds-gateway-servers-name>", $config.domain.ous.rdsGatewayServers.name). @@ -212,8 +192,7 @@ $params = @{ userAccountsB64 = [Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes(($userAccounts | ConvertTo-Json))) securityGroupsB64 = [Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes(($config.domain.securityGroups | ConvertTo-Json))) } -$result = Invoke-RemoteScript -Shell "PowerShell" -Script $script -VMName $config.dc.vmName -ResourceGroupName $config.dc.rg -Parameter $params -$result = Invoke-RemoteScript -Shell "PowerShell" -Script $script -VMName $config.dc.vmName -ResourceGroupName $config.dc.rg -Parameter $params -Write-Output $result.Value +$null = Invoke-RemoteScript -Shell "PowerShell" -Script $script -VMName $config.dc.vmName -ResourceGroupName $config.dc.rg -Parameter $params # Configure group policies @@ -224,8 +203,7 @@ $params = @{ shmFqdn = "`"$($config.domain.fqdn)`"" serverAdminSgName = "`"$($config.domain.securityGroups.serverAdmins.name)`"" } -$result = Invoke-RemoteScript -Shell "PowerShell" -ScriptPath $scriptPath -VMName $config.dc.vmName -ResourceGroupName $config.dc.rg -Parameter $params -Write-Output $result.Value +$null = Invoke-RemoteScript -Shell "PowerShell" -ScriptPath $scriptPath -VMName $config.dc.vmName -ResourceGroupName $config.dc.rg -Parameter $params # Configure the domain controllers and set their DNS resolution @@ -233,16 +211,16 @@ Write-Output $result.Value foreach ($vmName in ($config.dc.vmName, $config.dcb.vmName)) { # Configure DNS to forward requests to the Azure DNS resolver $params = @{ - externalDnsResolver = "`"$($config.dc.external_dns_resolver)`"" + ExternalDnsResolver = "$($config.dc.external_dns_resolver)" + IdentitySubnetCidr = "$($config.network.vnet.subnets.identity.cidr)" } $scriptPath = Join-Path $PSScriptRoot ".." "remote" "create_dc" "scripts" "Configure_DNS.ps1" - $result = Invoke-RemoteScript -Shell "PowerShell" -ScriptPath $scriptPath -VMName $vmName -ResourceGroupName $config.dc.rg -Parameter $params - Write-Output $result.Value + $null = Invoke-RemoteScript -Shell "PowerShell" -ScriptPath $scriptPath -VMName $vmName -ResourceGroupName $config.dc.rg -Parameter $params # Remove custom per-NIC DNS settings - $nic = Get-AzNetworkInterface -ResourceGroupName $config.dc.rg -Name "${vmName}-NIC" - $nic.DnsSettings.DnsServers.Clear() - $null = $nic | Set-AzNetworkInterface + $networkCard = Get-AzNetworkInterface -ResourceGroupName $config.dc.rg -Name "${vmName}-NIC" + $networkCard.DnsSettings.DnsServers.Clear() + $null = $networkCard | Set-AzNetworkInterface # Set locale, install updates and reboot Add-LogMessage -Level Info "Updating DC VM '$vmName'..." @@ -252,4 +230,4 @@ foreach ($vmName in ($config.dc.vmName, $config.dcb.vmName)) { # Switch back to original subscription # ------------------------------------ -$null = Set-AzContext -Context $originalContext +$null = Set-AzContext -Context $originalContext -ErrorAction Stop diff --git a/deployment/safe_haven_management_environment/setup/Setup_SHM_DC.ps1 b/deployment/safe_haven_management_environment/setup/Setup_SHM_DC.ps1 index ea5865fe..17ae2d04 100644 --- a/deployment/safe_haven_management_environment/setup/Setup_SHM_DC.ps1 +++ b/deployment/safe_haven_management_environment/setup/Setup_SHM_DC.ps1 @@ -4,18 +4,18 @@ param( ) Import-Module Az -ErrorAction Stop +Import-Module $PSScriptRoot/../../common/AzureStorage -Force -ErrorAction Stop Import-Module $PSScriptRoot/../../common/Configuration -Force -ErrorAction Stop Import-Module $PSScriptRoot/../../common/Deployments -Force -ErrorAction Stop -Import-Module $PSScriptRoot/../../common/GenerateSasToken -Force -ErrorAction Stop Import-Module $PSScriptRoot/../../common/Logging -Force -ErrorAction Stop Import-Module $PSScriptRoot/../../common/Security -Force -ErrorAction Stop # Get config and original context before changing subscription # ------------------------------------------------------------ -$config = Get-ShmFullConfig $shmId +$config = Get-ShmConfig $shmId $originalContext = Get-AzContext -$null = Set-AzContext -SubscriptionId $config.subscriptionName +$null = Set-AzContext -SubscriptionId $config.subscriptionName -ErrorAction Stop # Setup boot diagnostics resource group and storage account @@ -36,14 +36,6 @@ Add-LogMessage -Level Info "Ensuring that blob storage containers exist..." foreach ($containerName in ("shm-dsc-dc", "shm-configuration-dc", "sre-rds-sh-packages")) { $null = Deploy-StorageContainer -Name $containerName -StorageAccount $storageAccount } -# NB. we would like the NPS VM to log to a database, but this is not yet working -# # Create file storage shares -# foreach ($shareName in ("sqlserver")) { -# if (-not (Get-AzStorageShare -Context $storageAccount.Context | Where-Object { $_.Name -eq "$shareName" })) { -# Add-LogMessage -Level Info "Creating share '$shareName' in storage account '$($config.storage.artifacts.accountName)'" -# New-AzStorageShare -Name $shareName -Context $storageAccount.Context; -# } -# } # Upload artifacts @@ -94,41 +86,30 @@ $filename = $httpContent.Links | Where-Object { $_.href -like "*installer.msi" } $version = ($filename -split "-")[2] Start-AzStorageBlobCopy -AbsoluteUri "$($baseUri.Replace('latest', $version))/$filename" -DestContainer "sre-rds-sh-packages" -DestBlob "PuTTY_x64.msi" -DestContext $storageAccount.Context - ...skipping... diff --git a/deployment/safe_haven_management_environment/setup/Setup_SHM_DC.ps1 b/deployment/safe_haven_management_environment/setup/Setup_SHM_DC.ps1 index ea5865fe..17ae2d04 100644 --- a/deployment/safe_haven_management_environment/setup/Setup_SHM_DC.ps1 +++ b/deployment/safe_haven_management_environment/setup/Setup_SHM_DC.ps1 @@ -4,18 +4,18 @@ param( ) Import-Module Az -ErrorAction Stop +Import-Module $PSScriptRoot/../../common/AzureStorage -Force -ErrorAction Stop Import-Module $PSScriptRoot/../../common/Configuration -Force -ErrorAction Stop Import-Module $PSScriptRoot/../../common/Deployments -Force -ErrorAction Stop -Import-Module $PSScriptRoot/../../common/GenerateSasToken -Force -ErrorAction Stop Import-Module $PSScriptRoot/../../common/Logging -Force -ErrorAction Stop Import-Module $PSScriptRoot/../../common/Security -Force -ErrorAction Stop # Get config and original context before changing subscription # ------------------------------------------------------------ -$config = Get-ShmFullConfig $shmId +$config = Get-ShmConfig $shmId $originalContext = Get-AzContext -$null = Set-AzContext -SubscriptionId $config.subscriptionName +$null = Set-AzContext -SubscriptionId $config.subscriptionName -ErrorAction Stop # Setup boot diagnostics resource group and storage account @@ -36,14 +36,6 @@ Add-LogMessage -Level Info "Ensuring that blob storage containers exist..." foreach ($containerName in ("shm-dsc-dc", "shm-configuration-dc", "sre-rds-sh-packages")) { $null = Deploy-StorageContainer -Name $containerName -StorageAccount $storageAccount } -# NB. we would like the NPS VM to log to a database, but this is not yet working -# # Create file storage shares -# foreach ($shareName in ("sqlserver")) { -# if (-not (Get-AzStorageShare -Context $storageAccount.Context | Where-Object { $_.Name -eq "$shareName" })) { -# Add-LogMessage -Level Info "Creating share '$shareName' in storage account '$($config.storage.artifacts.accountName)'" -# New-AzStorageShare -Name $shareName -Context $storageAccount.Context; -# } -# } # Upload artifacts @@ -94,41 +86,30 @@ $filename = $httpContent.Links | Where-Object { $_.href -like "*installer.msi" } $version = ($filename -split "-")[2] Start-AzStorageBlobCopy -AbsoluteUri "$($baseUri.Replace('latest', $version))/$filename" -DestContainer "sre-rds-sh-packages" -DestBlob "PuTTY_x64.msi" -DestContext $storageAccount.Context - Force $success = $success -and $? -# WinSCP -$httpContent = Invoke-WebRequest -Uri "https://winscp.net/eng/download.php" -$filename = $httpContent.Links | Where-Object { $_.href -like "*Setup.exe" } | ForEach-Object { ($_.href -split "/")[-1] } -$absoluteUri = (Invoke-WebRequest -Uri "https://winscp.net/download/$filename").Links | Where-Object { $_.href -like "*winscp.net*$filename*" } | ForEach-Object { $_.href } | Select-Object - First 1 -Start-AzStorageBlobCopy -AbsoluteUri "$absoluteUri" -DestContainer "sre-rds-sh-packages" -DestBlob "WinSCP_x32.exe" -DestContext $storageAccount.Context -Force -$success = $success -and $? if ($success) { Add-LogMessage -Level Success "Uploaded Windows package installers" } else { Add-LogMessage -Level Fatal "Failed to upload Windows package installers!" } -# NB. we would like the NPS VM to log to a database, but this is not yet working -# Add-LogMessage -Level Info "Uploading SQL server installation files to storage account '$($config.storage.artifacts.accountName)'" -# # URI to Azure File copy does not support 302 redirect, so get the latest working endpoint redirected from "https://go.microsoft.com/fwlink/?linkid=853017" -# Start-AzStorageFileCopy -AbsoluteUri "https://download.microsoft.com/download/5/E/9/5E9B18CC-8FD5-467E-B5BF-BADE39C51F73/SQLServer2017-SSEI-Expr.exe" -DestShareName "sqlserver" -DestFilePa th "SQLServer2017-SSEI-Expr.exe" -DestContext $storageAccount.Context -Force -# # URI to Azure File copy does not support 302 redirect, so get the latest working endpoint redirected from "https://go.microsoft.com/fwlink/?linkid=2088649" -# Start-AzStorageFileCopy -AbsoluteUri "https://download.microsoft.com/download/5/4/E/54EC1AD8-042C-4CA3-85AB-BA307CF73710/SSMS-Setup-ENU.exe" -DestShareName "sqlserver" -DestFilePath "SSMS- Setup-ENU.exe" -DestContext $storageAccount.Context -Force + # Create SHM DC resource group if it does not exist # ------------------------------------------------- $null = Deploy-ResourceGroup -Name $config.dc.rg -Location $config.location -# Retrieve usernames/passwords from the keyvault -# ---------------------------------------------- -Add-LogMessage -Level Info "Creating/retrieving secrets from key vault '$($config.keyVault.name)'..." -$domainAdminUsername = Resolve-KeyVaultSecret -VaultName $config.keyVault.name -SecretName $config.keyVault.secretNames.domainAdminUsername -DefaultValue "domain$($config.id)admin".ToLower() -$domainAdminPassword = Resolve-KeyVaultSecret -VaultName $config.keyVault.name -SecretName $config.keyVault.secretNames.domainAdminPassword -DefaultLength 20 -$safemodeAdminPassword = Resolve-KeyVaultSecret -VaultName $config.keyVault.name -SecretName $config.dc.safemodePasswordSecretName -DefaultLength 20 +# Retrieve usernames/passwords from the Key Vault +# ----------------------------------------------- +Add-LogMessage -Level Info "Creating/retrieving secrets from Key Vault '$($config.keyVault.name)'..." +$domainAdminUsername = Resolve-KeyVaultSecret -VaultName $config.keyVault.name -SecretName $config.keyVault.secretNames.domainAdminUsername -DefaultValue "domain$($config.id)admin".ToLower() -AsPlaintext +$domainAdminPassword = Resolve-KeyVaultSecret -VaultName $config.keyVault.name -SecretName $config.keyVault.secretNames.domainAdminPassword -DefaultLength 20 -AsPlaintext +$safemodeAdminPassword = Resolve-KeyVaultSecret -VaultName $config.keyVault.name -SecretName $config.dc.safemodePasswordSecretName -DefaultLength 20 -AsPlaintext # Deploy SHM DC from template # --------------------------- Add-LogMessage -Level Info "Deploying domain controller (DC) from template..." -$artifactSasToken = New-ReadOnlyAccountSasToken -subscriptionName $config.subscriptionName -resourceGroup $config.storage.artifacts.rg -AccountName $config.storage.artifacts.accountName +$artifactSasToken = New-ReadOnlyStorageAccountSasToken -subscriptionName $config.subscriptionName -resourceGroup $config.storage.artifacts.rg -AccountName $config.storage.artifacts.accountNa me $params = @{ Administrator_Password = (ConvertTo-SecureString $domainAdminPassword -AsPlainText -Force) Administrator_User = $domainAdminUsername @@ -169,7 +150,7 @@ Add-LogMessage -Level Info "Importing configuration artifacts for: $($config.dc. # Get list of blobs in the storage account $storageContainerName = "shm-configuration-dc" $blobNames = Get-AzStorageBlob -Container $storageContainerName -Context $storageAccount.Context | ForEach-Object { $_.Name } -$artifactSasToken = New-ReadOnlyAccountSasToken -subscriptionName $config.subscriptionName -resourceGroup $config.storage.artifacts.rg -AccountName $config.storage.artifacts.accountName +$artifactSasToken = New-ReadOnlyStorageAccountSasToken -subscriptionName $config.subscriptionName -resourceGroup $config.storage.artifacts.rg -AccountName $config.storage.artifacts.accountNa me $remoteInstallationDir = "C:\Installation" # Run remote script $scriptPath = Join-Path $PSScriptRoot ".." "remote" "create_dc" "scripts" "Import_Artifacts.ps1" -Resolve @@ -180,8 +161,7 @@ $params = @{ storageContainerName = "`"$storageContainerName`"" sasToken = "`"$artifactSasToken`"" } -$result = Invoke-RemoteScript -Shell "PowerShell" -ScriptPath $scriptPath -VMName $config.dc.vmName -ResourceGroupName $config.dc.rg -Parameter $params -Write-Output $result.Value +$null = Invoke-RemoteScript -Shell "PowerShell" -ScriptPath $scriptPath -VMName $config.dc.vmName -ResourceGroupName $config.dc.rg -Parameter $params # Configure Active Directory remotely @@ -190,11 +170,11 @@ Add-LogMessage -Level Info "Configuring Active Directory for: $($config.dc.vmNam # Fetch user and OU details $userAccounts = $config.users.computerManagers + $config.users.serviceAccounts foreach ($user in $userAccounts.Keys) { - $userAccounts[$user]["password"] = Resolve-KeyVaultSecret -VaultName $config.keyVault.name -SecretName $userAccounts[$user]["passwordSecretName"] -DefaultLength 20 + $userAccounts[$user]["password"] = Resolve-KeyVaultSecret -VaultName $config.keyVault.name -SecretName $userAccounts[$user]["passwordSecretName"] -DefaultLength 20 -AsPlaintext } # Run remote script $scriptTemplate = Join-Path $PSScriptRoot ".." "remote" "create_dc" "scripts" "Active_Directory_Configuration.ps1" | Get-Item | Get-Content -Raw -$script = $scriptTemplate.Replace("<ou-data-servers-name>", $config.domain.ous.dataServers.name). +$script = $scriptTemplate.Replace("<ou-database-servers-name>", $config.domain.ous.databaseServers.name). Replace("<ou-identity-servers-name>", $config.domain.ous.identityServers.name). Replace("<ou-linux-servers-name>", $config.domain.ous.linuxServers.name). Replace("<ou-rds-gateway-servers-name>", $config.domain.ous.rdsGatewayServers.name). @@ -212,8 +192,7 @@ $params = @{ userAccountsB64 = [Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes(($userAccounts | ConvertTo-Json))) securityGroupsB64 = [Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes(($config.domain.securityGroups | ConvertTo-Json))) } -$result = Invoke-RemoteScript -Shell "PowerShell" -Script $script -VMName $config.dc.vmName -ResourceGroupName $config.dc.rg -Parameter $params -Write-Output $result.Value +$null = Invoke-RemoteScript -Shell "PowerShell" -Script $script -VMName $config.dc.vmName -ResourceGroupName $config.dc.rg -Parameter $params # Configure group policies @@ -224,8 +203,7 @@ $params = @{ shmFqdn = "`"$($config.domain.fqdn)`"" serverAdminSgName = "`"$($config.domain.securityGroups.serverAdmins.name)`"" } -$result = Invoke-RemoteScript -Shell "PowerShell" -ScriptPath $scriptPath -VMName $config.dc.vmName -ResourceGroupName $config.dc.rg -Parameter $params -Write-Output $result.Value +$null = Invoke-RemoteScript -Shell "PowerShell" -ScriptPath $scriptPath -VMName $config.dc.vmName -ResourceGroupName $config.dc.rg -Parameter $params # Configure the domain controllers and set their DNS resolution @@ -233,16 +211,16 @@ Write-Output $result.Value foreach ($vmName in ($config.dc.vmName, $config.dcb.vmName)) { # Configure DNS to forward requests to the Azure DNS resolver $params = @{ - externalDnsResolver = "`"$($config.dc.external_dns_resolver)`"" + ExternalDnsResolver = "$($config.dc.external_dns_resolver)" + IdentitySubnetCidr = "$($config.network.vnet.subnets.identity.cidr)" } $scriptPath = Join-Path $PSScriptRoot ".." "remote" "create_dc" "scripts" "Configure_DNS.ps1" - $result = Invoke-RemoteScript -Shell "PowerShell" -ScriptPath $scriptPath -VMName $vmName -ResourceGroupName $config.dc.rg -Parameter $params - Write-Output $result.Value + $null = Invoke-RemoteScript -Shell "PowerShell" -ScriptPath $scriptPath -VMName $vmName -ResourceGroupName $config.dc.rg -Parameter $params # Remove custom per-NIC DNS settings - $nic = Get-AzNetworkInterface -ResourceGroupName $config.dc.rg -Name "${vmName}-NIC" - $nic.DnsSettings.DnsServers.Clear() - $null = $nic | Set-AzNetworkInterface + $networkCard = Get-AzNetworkInterface -ResourceGroupName $config.dc.rg -Name "${vmName}-NIC" + $networkCard.DnsSettings.DnsServers.Clear() + $null = $networkCard | Set-AzNetworkInterface # Set locale, install updates and reboot Add-LogMessage -Level Info "Updating DC VM '$vmName'..." @@ -252,4 +230,4 @@ foreach ($vmName in ($config.dc.vmName, $config.dcb.vmName)) { # Switch back to original subscription # ------------------------------------ -$null = Set-AzContext -Context $originalContext +$null = Set-AzContext -Context $originalContext -ErrorAction Stop ```

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully