Delen via


Sql Database-controle beheren met de REST API

Van toepassing op:SQL-database in Microsoft Fabric

U kunt de REST API van Fabric gebruiken om controle-instellingen voor SQL-databases programmatisch weer te geven en te configureren. De API voor SQL-controle-instellingen is een API op databaseniveau die op afzonderlijke SQL-databases werkt. Door de API te combineren met PowerShell-scripts, kunt u de controle consistent beheren voor alle databases in een werkruimte.

In dit artikel wordt gedemonstreert hoe u PowerShell en de REST API voor SQL-controle-instellingen op databaseniveau gebruikt om controle-instellingen voor SQL-databases in een Infrastructuurwerkruimte op te halen en bij te werken.

Vereiste voorwaarden

REST API-eindpunten controleren

De API voor SQL-controle-instellingen biedt twee bewerkingen voor het beheren van controle op afzonderlijke SQL-databases:

Operatie Methode URI
SQL-controle-instellingen ophalen GET https://api.fabric.microsoft.com/v1/workspaces/{workspaceId}/sqlDatabases/{sqlDatabaseId}/settings/sqlAudit
SQL-controle-instellingen bijwerken PATCH https://api.fabric.microsoft.com/v1/workspaces/{workspaceId}/sqlDatabases/{sqlDatabaseId}/settings/sqlAudit

Voor de Get-bewerking is een SQLDatabase.Read.All, SQLDatabase.ReadWrite.All, Item.Read.All of Item.ReadWrite.All gedelegeerd bereik vereist. Voor de updatebewerking is SQLDatabase.ReadWrite.All of Item.ReadWrite.All een gedelegeerd bereik vereist. Beide bewerkingen ondersteunen gebruikersidentiteiten, service-principals en beheerde identiteiten.

Eigenschappen van controle-instellingen

Het object auditinstellingen bevat de volgende eigenschappen:

Vastgoed Typ Beschrijving
auditActionsAndGroups string[] Controleer acties en groepen die moeten worden vastgelegd. Standaard: BATCH_COMPLETED_GROUP, FAILED_DATABASE_AUTHENTICATION_GROUP, SUCCESSFUL_DATABASE_AUTHENTICATION_GROUP.
predicateExpression string Een T-SQL-predicaatexpressie die wordt gebruikt om controlegebeurtenissen te filteren. Sluit bijvoorbeeld statement not like '[select ]%' SELECT-instructies uit.
retentionDays geheel getal Aantal dagen dat auditlogboeken moeten worden bewaard. 0 geeft onbepaalde retentie aan.
state string Status van de audit: Enabled of Disabled. Wanneer u controle voor het eerst inschakelt zonder andere eigenschappen op te geven, gebruikt het systeem standaardwaarden.
storageEndpoint string (Alleen-lezen) Het OneLake-opslageindpunt waarin auditlogboeken worden opgeslagen.

Controle-instellingen voor alle databases in een werkruimte weergeven

Het volgende PowerShell-script bevat alle SQL-databases in een werkruimte en haalt de controleconfiguratie voor elke database op.

Vervang in het volgende script <your workspace id> door uw Fabric-werkruimte-ID. U vindt de id van een werkruimte in de URL. Dit is de unieke tekenreeks binnen twee / tekens na /groups/ in het browservenster. Bijvoorbeeld 00001111-aaaa-2222-bbbb-3333cccc4444 in https://fabric.microsoft.com/groups/00001111-aaaa-2222-bbbb-3333cccc4444/.

Import-Module Az.Accounts

Connect-AzAccount

$workspaceId = '<your workspace id>'
$baseUri = "https://api.fabric.microsoft.com"

# Obtain an access token
$token = (Get-AzAccessToken -ResourceUrl "https://api.fabric.microsoft.com")
$secureToken = $token.Token | ConvertFrom-SecureString -AsPlainText

$headers = @{
    "Authorization" = "Bearer $secureToken"
    "Content-Type"  = "application/json"
}

# List all SQL databases in the workspace
$databasesUri = "$baseUri/v1/workspaces/$workspaceId/sqlDatabases"
$databases = @()
$continuationToken = $null

do {
    $url = $databasesUri
    if ($continuationToken) {
        $encoded = [System.Web.HttpUtility]::UrlEncode($continuationToken)
        $url = "$url`?continuationToken=$encoded"
    }
    $response = Invoke-RestMethod -Method GET -Uri $url -Headers $headers
    if ($response.value) { $databases += $response.value }
    $continuationToken = $response.continuationToken
} while ($continuationToken)

Write-Host "Found $($databases.Count) SQL databases."

# Retrieve audit settings for each database
$results = @()

foreach ($db in $databases) {
    try {
        $auditUri = "$baseUri/v1/workspaces/$workspaceId/sqlDatabases/$($db.id)/settings/sqlAudit"
        $audit = Invoke-RestMethod -Method GET -Uri $auditUri -Headers $headers

        $results += [PSCustomObject]@{
            DatabaseName        = $db.displayName
            DatabaseId          = $db.id
            State               = $audit.state
            RetentionDays       = $audit.retentionDays
            AuditActionsAndGroups = ($audit.auditActionsAndGroups -join "; ")
            PredicateExpression = $audit.predicateExpression
        }
    }
    catch {
        $results += [PSCustomObject]@{
            DatabaseName        = $db.displayName
            DatabaseId          = $db.id
            State               = "ERROR"
            RetentionDays       = ""
            AuditActionsAndGroups = ""
            PredicateExpression = $_.Exception.Message
        }
    }
}

$results | Format-Table -AutoSize

Controle configureren voor alle databases in een werkruimte

Nadat u de huidige controlestatus hebt gecontroleerd, gebruikt u het volgende script om de controle consistent te configureren voor alle databases in een werkruimte.

Vervang <your workspace id> door de ID van uw Fabric-werkruimte. Wijzig het object zodat het $auditPayload overeenkomt met de gewenste controleconfiguratie.

Import-Module Az.Accounts

Connect-AzAccount

$workspaceId = '<your workspace id>'
$baseUri = "https://api.fabric.microsoft.com"

# Obtain an access token
$token = (Get-AzAccessToken -ResourceUrl "https://api.fabric.microsoft.com")
$secureToken = $token.Token | ConvertFrom-SecureString -AsPlainText

$headers = @{
    "Authorization" = "Bearer $secureToken"
    "Content-Type"  = "application/json"
}

# Define the audit configuration to apply
$auditPayload = @{
    state                = "Enabled"
    auditActionsAndGroups = @(
        "BATCH_COMPLETED_GROUP",
        "FAILED_DATABASE_AUTHENTICATION_GROUP",
        "SUCCESSFUL_DATABASE_AUTHENTICATION_GROUP"
    )
    retentionDays        = 10
    predicateExpression  = "statement not like '[select ]%'"
} | ConvertTo-Json -Depth 5

# List all SQL databases in the workspace
$databasesUri = "$baseUri/v1/workspaces/$workspaceId/sqlDatabases"
$databases = @()
$continuationToken = $null

do {
    $url = $databasesUri
    if ($continuationToken) {
        $encoded = [System.Web.HttpUtility]::UrlEncode($continuationToken)
        $url = "$url`?continuationToken=$encoded"
    }
    $response = Invoke-RestMethod -Method GET -Uri $url -Headers $headers
    if ($response.value) { $databases += $response.value }
    $continuationToken = $response.continuationToken
} while ($continuationToken)

Write-Host "Configuring auditing for $($databases.Count) SQL databases..."

foreach ($db in $databases) {
    try {
        $auditUri = "$baseUri/v1/workspaces/$workspaceId/sqlDatabases/$($db.id)/settings/sqlAudit"
        Invoke-RestMethod -Method PATCH -Uri $auditUri -Headers $headers -Body $auditPayload | Out-Null
        Write-Host "[OK] Updated auditing for: $($db.displayName)"
    }
    catch {
        Write-Host "[FAIL] $($db.displayName): $($_.Exception.Message)"
    }
}

Beste praktijken

  • Haal altijd de huidige controle-instellingen op met een GET verzoek voordat u bijwerkt met PATCH, om inzicht te krijgen in de bestaande configuratie.
  • Afhandelen van fouten per database. Als één database-update mislukt, gaat u verder met het verwerken van de resterende databases.
  • Probeer tijdelijke fouten afzonderlijk opnieuw in plaats van het volledige script voor bulkupdates opnieuw uit te voeren.
  • Gebruik een service-principal of beheerde identiteit voor geautomatiseerde of geplande controleconfiguratie in productieomgevingen.