You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用PowerShell/Azure CLI自动化配置带PIM的Azure安全组

自动化Azure安全组PIM配置与资格成员添加

以下提供PowerShell和Azure CLI两种脚本方案,实现验证安全组PIM配置、自动启用(若未配置)并添加符合条件的资格成员。


PowerShell 方案

前置要求

  1. 安装AzureADPreview模块:
    Install-Module AzureADPreview -Force -AllowClobber
    
  2. 登录Azure AD:
    Connect-AzureAD
    

自动化脚本

# 配置变量
$groupName = "SG_AZR-0111-0014-002_O"
# 替换为实际需要添加的成员UPN(支持用户或服务主体)
$eligibleMemberUPNs = @("user1@contoso.com", "sp-thirdparty@contoso.com")

# 1. 获取目标安全组
$group = Get-AzureADGroup -Filter "DisplayName eq '$groupName'"
if (-not $group) {
    Write-Error "安全组 $groupName 不存在,请检查组名正确性。"
    exit 1
}

# 2. 验证组是否为可分配角色类型(PIM管理的必要条件)
if (-not $group.IsAssignableToRole) {
    Write-Error "安全组 $groupName 不是可分配角色的安全组,无法通过PIM管理成员资格。请先在门户转换组类型。"
    exit 1
}

# 3. 检查组是否已配置PIM资格分配
$roleDefinitionId = $group.ObjectId
$existingEligibleAssignments = Get-AzureADMSPrivilegedRoleAssignment -ProviderId "aadGroups" -Filter "RoleDefinitionId eq '$roleDefinitionId' and AssignmentState eq 'Eligible'"

if (-not $existingEligibleAssignments) {
    Write-Host "安全组 $groupName 未配置PIM资格分配,将直接添加成员..."
} else {
    Write-Host "安全组 $groupName 已配置PIM资格分配,跳过启用步骤。"
}

# 4. 批量添加资格成员
foreach ($upn in $eligibleMemberUPNs) {
    # 查找成员对象(兼容用户与服务主体)
    $member = Get-AzureADUser -Filter "UserPrincipalName eq '$upn'" -ErrorAction SilentlyContinue
    if (-not $member) {
        $member = Get-AzureADServicePrincipal -Filter "AppId eq '$upn'" -ErrorAction SilentlyContinue
        if (-not $member) {
            Write-Warning "无法找到身份 $upn,跳过该成员。"
            continue
        }
    }

    # 检查成员是否已存在于资格列表
    $existingAssignment = $existingEligibleAssignments | Where-Object { $_.SubjectId -eq $member.ObjectId }
    if ($existingAssignment) {
        Write-Host "成员 $upn 已在 $groupName 的PIM资格列表中,跳过添加。"
        continue
    }

    # 添加资格分配(永久有效,如需设置过期时间可修改Schedule参数)
    try {
        New-AzureADMSPrivilegedRoleAssignment `
            -ProviderId "aadGroups" `
            -RoleDefinitionId $roleDefinitionId `
            -SubjectId $member.ObjectId `
            -AssignmentState "Eligible" `
            -AssignmentType "User" `
            -Schedule (New-Object Microsoft.Open.MSGraph.Model.AzureADMSPrivilegedSchedule -Property @{
                Type = "Once"
                StartDateTime = (Get-Date).ToUniversalTime().ToString("o")
                EndDateTime = $null
            })
        Write-Host "成功添加 $upn 到 $groupName 的PIM资格列表。"
    } catch {
        Write-Error "添加 $upn 失败:$_"
    }
}

Azure CLI 方案

前置要求

  1. 安装并更新Azure CLI:
    az upgrade
    
  2. 登录Azure账号:
    az login
    

自动化脚本

# 配置变量
GROUP_NAME="SG_AZR-0111-0014-002_O"
# 替换为实际需要添加的成员UPN/服务主体ID
ELIGIBLE_MEMBERS=("user1@contoso.com" "sp-thirdparty@contoso.com")

# 1. 获取目标安全组ID
GROUP_ID=$(az ad group show --group "$GROUP_NAME" --query id -o tsv)
if [ -z "$GROUP_ID" ]; then
    echo "错误:安全组 $GROUP_NAME 不存在,请检查组名。"
    exit 1
fi

# 2. 验证组是否为可分配角色类型
IS_ASSIGNABLE=$(az ad group show --group "$GROUP_NAME" --query isAssignableToRole -o tsv)
if [ "$IS_ASSIGNABLE" != "true" ]; then
    echo "错误:安全组 $GROUP_NAME 不是可分配角色的安全组,无法通过PIM管理。请先转换组类型。"
    exit 1
fi

# 3. 检查组是否已配置PIM资格分配
EXISTING_ASSIGNMENTS=$(az ad group pim eligible-member list --group "$GROUP_ID" --query "[].id" -o tsv)
if [ -z "$EXISTING_ASSIGNMENTS" ]; then
    echo "安全组 $GROUP_NAME 未配置PIM资格分配,开始添加成员..."
else
    echo "安全组 $GROUP_NAME 已配置PIM资格分配,跳过启用步骤。"
fi

# 4. 批量添加资格成员
for MEMBER in "${ELIGIBLE_MEMBERS[@]}"; do
    # 查找成员ID(兼容用户与服务主体)
    MEMBER_ID=$(az ad user show --id "$MEMBER" --query id -o tsv 2>/dev/null)
    if [ -z "$MEMBER_ID" ]; then
        MEMBER_ID=$(az ad sp show --id "$MEMBER" --query id -o tsv 2>/dev/null)
        if [ -z "$MEMBER_ID" ]; then
            echo "警告:无法找到身份 $MEMBER,跳过该成员。"
            continue
        fi
    fi

    # 检查成员是否已在资格列表
    EXISTS=$(az ad group pim eligible-member list --group "$GROUP_ID" --query "[?subjectId=='$MEMBER_ID'].id" -o tsv)
    if [ -n "$EXISTS" ]; then
        echo "成员 $MEMBER 已在 $GROUP_NAME 的PIM资格列表中,跳过添加。"
        continue
    fi

    # 添加资格分配(默认永久有效,如需设置过期时间可添加--end-date参数)
    az ad group pim eligible-member add --group "$GROUP_ID" --member-id "$MEMBER_ID" --schedule-type once
    if [ $? -eq 0 ]; then
        echo "成功添加 $MEMBER 到 $GROUP_NAME 的PIM资格列表。"
    else
        echo "错误:添加 $MEMBER 失败。"
    fi
done

内容的提问来源于stack exchange,提问作者tony

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 19:09:57