How to add AD Administrator to Azure SQL Managed Instance with Powershell - sql

I need to add AD administrator to Azure SQL Managed Instances through PowerShell in order to automate deployments.
But it seems there's no way to do it with Azure PowerShell or the REST APIs.
So far I've been trying to set it up like a normal SQL Server.
$sql = Get-AzureRmResource -ResourceGroupName "RSGName" -Name "InstanceName"
-ResourceType "Microsoft.Sql/managedInstances" -ExpandProperties
$dbaId = Get-AzureRmADGroup -DisplayName "ADGroupName" | Select-Object Id
Set-AzureRmSqlServerActiveDirectoryAdministrator -DisplayName "ADGroupName"
-ResourceGroupName "RSGName" -ServerName "InstanceName" -ObjectId $dbaId.Id
But it is giving me errors saying the Server cannot be found on the resource group.

Related

create a script for azure pim roles assigned to users

$filters = "(roleDefinitionId eq '69091246-20e8-4a56-aa4d-066075b2a7a8')" -or "(roleDefinitionId eq '3d762c5a-1b6c-493f-843e-55a3b42923d4')"
Write-Host -Message "Start ......... Script"
$getallPIMadmins = Get-AzureADMSPrivilegedRoleAssignment -ProviderId "aadRoles" -ResourceId "fd799da1-bfc1-4234-a91c-72b3a1cb9e26" -filter $filters
can i use or condition in filter option
if yes how
i am expecting to get output from above condition if use or
I tried to reproduce the same in my environment to get the Azure AD PIM Roles using PowerShell Script
Check this Script to get the azure PIM roles assigned to users.
Note: Uninstall Azure AD module before installing Azure ADPreview
Module and Login with Azure AD Global Admin Credentials. *
Uninstall-Module AzureAD
Install-module AzureADPreview
Connect-AzureAD
Get-AzureADMSPrivilegedRoleAssignment -ProviderId "aadRoles" -ResourceId 15e217e9-19a5-4006-a9f1-f7e74d8b2a5a
Get-AzureADMSPrivilegedRoleAssignment -ProviderId "aadRoles" -ResourceId "15e217e9-19a5-4006-a9f1-f7e74d8b2a5a" -Filter "roleDefinitionId eq 'fdd7a751-b60b-444a-984c-02652fe8fa1c'
Result:

Printing Name and value of configuration webapps of azure in powershell script

I written some code in PowerShell script to print the configuration of one web app using azure portal. But I struck in between that exactly I want to print names and values in config of particular web app like development environment...
Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass Connect-AzAccount $subscriptions = Get-AzSubscription Write-Host "Subscription:" MDD-NU-01 -Separator "" Set-AzContext -Subscription MDD-NU-01 $srcResourceGroup = "d1-sap-rg52" $srcAppName = "d1-sap-web-l521" $srcAppServer = Get-AzWebApp -ResourceGroupName $srcResourceGroup -Name $srcAppName $srcAppSettings = $srcAppServer.SiteConfig.AppSettings
1.uptohere its connecting in config appsettings
2.In appsetting there are names and value will there
3.After this i struck here the logic should give the output like print all the name and value in configuration of web app("d1-sap-web-l521")
Please anybody help me out.
Thank you
You can directly get the required information of WebApps using Get-AzureRmWebApp. Below is the script that worked for me.
$WebAppInfo = Get-AzureRmWebApp -ResourceGroupName <YourResourceGroupName> -Name <YourWebAppName>
$Configurations = $WebAppInfo.SiteConfig.AppSettings
$Configurations
In portal:

List / discover all Azure SQL Database backup retention policies

I have a large number of Azure SQL Databases and I would like to create a list or report of some kind that shows what backup retention policies are in place for each one.
All I can find is how to check on per-database or per-server basis. This would take me a long time and is error-prone and not something I can check on a regular basis or easily provide to an auditor/manager who wants confirmation that everything is being backed up and retained properly.
Is there a way to obtain all this information in one place? A PowerShell solution would be acceptable.
You can use Powershell commands to get the Long-term retention policies for your SQL Server or even for each database using below commands:
# get all LTR policies within a server
$ltrPolicies = Get-AzSqlDatabase -ResourceGroupName $resourceGroup -ServerName $serverName | `
Get-AzSqlDatabaseLongTermRetentionPolicy
# get the LTR policy of a specific database
$ltrPolicies = Get-AzSqlDatabaseBackupLongTermRetentionPolicy -ServerName $serverName -DatabaseName $dbName `
-ResourceGroupName $resourceGroup
You can also use CLI command to get LTR policies for each database.
az sql db ltr-policy show \
--resource-group mygroup \
--server myserver \
--name mydb
In the above code only you can write the code for each database to get the LTR policies.
Refer: Manage Azure SQL Database long-term backup retention

Backup Azure SQL DB during VSTS Release

I am exploring VSTS Release Management and I wanted to backup my production database hosted on Azure SQL DB before I apply any migration scripts to it. I fail to find any particular task or preferred way of waiting till the Azure SQL DB is fully backed up so that I can proceed with deployment only after the database is correctly backed up. 
I have looked at either using a PowerShell task or Azure SQL CMD task, but I am not sure how to make rest of the tasks wait for the backup to complete. 
Would appreciate if anyone could point me in the right direction. Thanks. 
You can backup Azure SQL database and check the status in a loop.
$exportRequest = New-AzureRmSqlDatabaseExport -ResourceGroupName $ResourceGroupName -ServerName $ServerName `
-DatabaseName $DatabaseName -StorageKeytype $StorageKeytype -StorageKey $StorageKey -StorageUri $BacpacUri `
-AdministratorLogin $creds.UserName -AdministratorLoginPassword $creds.Password
$importStatus = Get-AzureRmSqlDatabaseImportExportStatus -OperationStatusLink $importRequest.OperationStatusLink
[Console]::Write("Exporting")
while ($importStatus.Status -eq "InProgress")
{
$importStatus = Get-AzureRmSqlDatabaseImportExportStatus -OperationStatusLink $importRequest.OperationStatusLink
[Console]::Write(".")
Start-Sleep -s 10
}
[Console]::WriteLine("")
$importStatus
More information, you can refer to Export an Azure SQL database to a BACPAC file.
Another way is that you can backup Azure SQL database by call Microsoft.SqlServer.Dac.DacServices.ExportBacpac method with PowerShell.
param([string]$ConnectionString, [string]$DatabaseName,[string]$OutputFile,[string]$s)
Add-Type -Path "$s\AzureDatabaseSolution\SQLDatabase\lib\Microsoft.SqlServer.Dac.dll"
$now = $(Get-Date).ToString("HH:mm:ss")
$Services = new-object Microsoft.SqlServer.Dac.DacServices $ConnectionString
Write-Host "Starting at $now"
$Watch = New-Object System.Diagnostics.StopWatch
$Watch.Start()
$Services.ExportBacpac($OutputFile, $DatabaseName)
$Watch.Stop()
Write-Host "Backup completed in" $Watch.Elapsed.ToString()
Note: Using the assembly in this package: Microsoft.SqlServer.Dac 1.0.3 (I add it to the source control and map to build agent)
On the other hand, to add firewall rule, you can refer to this thread: Deploy Dacpac packages via power shell script to Azure SQL Server.
BTW, you can build the custom build/release step/task with these PowerShell scripts. Add a build task
Azure SQL Databases are continually backed up automatically. If you are trying to create a copy of the database or archive the database to a BACPAC file, you can do either.
https://learn.microsoft.com/en-us/azure/sql-database/sql-database-automated-backups
https://learn.microsoft.com/en-us/azure/sql-database/sql-database-copy
https://learn.microsoft.com/en-us/azure/sql-database/sql-database-export

Create AD application with VSTS task

I am trying to create a VSTS task, which should create an AD application.
Taken the DeployAzureResouceGroup as a sample, I have created to following script:
[CmdletBinding()]
param()
Trace-VstsEnteringInvocation $MyInvocation
Import-VstsLocStrings "$PSScriptRoot\Task.json"
$connectedServiceNameSelector = Get-VstsInput -Name "connectedServiceNameSelector" -Require
$connectedServiceName = Get-VstsInput -Name "connectedServiceName"
$connectedServiceNameClassic = Get-VstsInput -Name "connectedServiceNameClassic"
$domains = (Get-VstsInput -Name "domains").Split(";")
$appName = Get-VstsInput -Name "appName"
if($connectedServiceNameSelector -eq "ConnectedServiceNameClassic")
{
$connectedServiceName = $connectedServiceNameClassic
$action = $actionClassic
$resourceGroupName = $cloudService
}
Import-Module $PSScriptRoot\ps_modules\VstsAzureHelpers_
Initialize-Azure
# Import the loc strings.
Import-VstsLocStrings -LiteralPath $PSScriptRoot/Task.json
# Import all the dlls and modules which have cmdlets we need
Import-Module "$PSScriptRoot\DeploymentUtilities\Microsoft.TeamFoundation.DistributedTask.Task.Deployment.Internal.psm1"
Import-Module "$PSScriptRoot\DeploymentUtilities\Microsoft.TeamFoundation.DistributedTask.Task.Deployment.dll"
# Load all dependent files for execution
. "$PSScriptRoot\Utility.ps1"
try
{
Validate-AzurePowerShellVersion
$azureUtility = Get-AzureUtility "$connectedServiceName"
Write-Verbose "Loading $azureUtility"
. "$PSScriptRoot\$azureUtility"
Write-Output "test"
Write-Output "Creating a new Application in AAD (App URI -)" -Verbose
$azureAdApplication = New-AzureRmADApplication -DisplayName "test" -IdentifierUris "https://app.com" -HomePage "https://app.com"
$appId = $azureAdApplication.ApplicationId
Write-Output "Azure AAD Application creation completed successfully (Application Id: $appId)" -Verbose
Write-Verbose "Completing Azure Resource Group Deployment Task" -Verbose
}
catch
{
Write-TaskSpecificTelemetry "UNKNOWNDEP_Error"
throw
}
When I use a Service principal as Service Endpoint user, I got the error Resource me not found.
When I use my custom AD account, I got the error:Run Login-AzureRmAccount to login.
What am I doing wrong? How can I get this script working?
If you don't need Powershell scripting, go install Azure AD Application Management extension from https://marketplace.visualstudio.com/items?itemName=RalphJansen.Azure-AD-Application-Management
You can add new tasks from pipeline GUI for managing AD applications.
If you do need Powershell scripting, then things get tricky.
Get Powershell code from https://stackoverflow.com/a/51848069/1548275 as a base. The difference is, that if you're not running your code from an extension, you don't have Get-VstsInput nor Get-VstsEndpoint available to execute.
Also, you don't have AzureAD module cmdlets to run. You need to get the Nuget-package, unzip it to your own repo and have it as part of your scripts to be later Import-Module in a pipeline task.
Finally, you need an auth token for Graph API. As the extension code shows, you will need 3 variables:
$tenantId = (Get-AzureRmSubscription).TenantId
$clientId = (Get-AzureRmADServicePrincipal -DisplayName "Your Project Service Connection name from Azure AD App Registrations").ApplicationId.Guid
$clientSecret = 'hard-coded, reset SPN password'
As you can see, an extension would have access to all three, but regular script (to my knowledge) doesn't.
SPN password reset is covered in The Net. Briefly, it is something like this:
$clientId = (Get-AzureRmADServicePrincipal -DisplayName "Your Project Service Connection name from Azure AD App Registrations").Id.Guid
$password = ConvertTo-SecureString –asplaintext –force "oh, this is very secret!"
New-AzureRmADSpCredential -ObjectId $clientId -Password $password
Also: Update the plaintext password into Azure DevOps project settings, Service Connections for Pipeline to know about the update.