将 Azure Policy 大规模部署到委托订阅

作为服务提供商,可以将多个客户租户加入 Azure Lighthouse。 借助 Azure Lighthouse,可以跨多个租户大规模执行操作,使管理任务更高效。

本文介绍如何使用 Azure Policy 通过 PowerShell 命令跨多个租户部署策略定义和策略分配。 在此示例中,策略定义确保通过允许仅 HTTPS 流量来保护存储帐户。 对于你想要部署的任何策略,可以使用相同的一般流程。

提示

虽然本文指的是服务提供商和客户, 但管理多个租户的企业 可以使用相同的流程。

使用 Azure Resource Graph 在客户租户之间执行查询

使用 Azure Resource Graph 可以跨你管理的客户租户中的所有订阅进行查询。

此示例标识当前不需要 HTTPS 流量的托管客户订阅中的任何存储帐户。

$MspTenant = "insert your managing tenantId here"

$subs = Get-AzSubscription

$ManagedSubscriptions = Search-AzGraph -Query "ResourceContainers | where type == 'microsoft.resources/subscriptions' | where tenantId != '$($mspTenant)' | project name, subscriptionId, tenantId" -subscription $subs.subscriptionId

Search-AzGraph -Query "Resources | where type =~ 'Microsoft.Storage/storageAccounts' | project name, location, subscriptionId, tenantId, properties.supportsHttpsTrafficOnly" -subscription $ManagedSubscriptions.subscriptionId | convertto-json

跨多个客户租户部署策略

确定不符合要求的存储帐户后,可以部署策略以强制实施该设置。

以下示例演示如何使用 Azure 资源管理器模板 跨多个客户租户中的所有委托订阅部署策略定义和策略分配。 此策略定义要求所有存储帐户都使用 HTTPS 流量,从而阻止创建新的不符合要求的存储帐户。 任何没有该设置的现有存储帐户都标记为不符合。

Write-Output "In total, there are $($ManagedSubscriptions.Count) delegated customer subscriptions to be managed"

foreach ($ManagedSub in $ManagedSubscriptions)
{
    Select-AzSubscription -SubscriptionId $ManagedSub.subscriptionId

    New-AzSubscriptionDeployment -Name mgmt `
                     -Location chinaeast2 `
                     -TemplateUri "https://raw.githubusercontent.com/Azure/Azure-Lighthouse-samples/master/templates/policy-enforce-https-storage/enforceHttpsStorage.json" `
                     -AsJob
}

注意

虽然可以跨多个租户部署策略,但目前无法通过 Azure Lighthouse 查看这些租户中不符合资源的 符合性详细信息

验证策略部署

部署 Azure 资源管理器模板后,尝试在某个委派订阅中创建 EnableHttpsTrafficOnly 设置为 false 的存储帐户,确认已成功应用策略定义。 策略分配应阻止创建此存储帐户。

New-AzStorageAccount -ResourceGroupName (New-AzResourceGroup -name policy-test -Location eastus -Force).ResourceGroupName `
                     -Name (get-random) `
                     -Location chinaeast2 `
                     -EnableHttpsTrafficOnly $false `
                     -SkuName Standard_LRS `
                     -Verbose                  

清理资源

完成后,通过运行以下 PowerShell 脚本删除部署创建的策略定义和分配。

foreach ($ManagedSub in $ManagedSubscriptions)
{
    select-azsubscription -subscriptionId $ManagedSub.subscriptionId

    Remove-AzSubscriptionDeployment -Name mgmt -AsJob

    $Assignment = Get-AzPolicyAssignment | where-object {$_.Name -like "enforce-https-storage-assignment"}

    if ([string]::IsNullOrEmpty($Assignment))
    {
        Write-Output "Nothing to clean up - we're done"
    }
    else
    {

    Remove-AzPolicyAssignment -Name 'enforce-https-storage-assignment' -Scope "/subscriptions/$($ManagedSub.subscriptionId)" -Verbose

    Write-Output "Deployment has been deleted - we're done"
    }
}

后续步骤