简体   繁体   English

Microsoft Azure 在任何服务主体过期时发出邮件警报

[英]Microsoft Azure alert to mail when any service principal getting expired

I need to know if there any simple script which I can run from Azure cli or Azure automation.我需要知道是否有任何可以从 Azure cli 或 Azure 自动化运行的简单脚本。 I am amazed in 2022 there is no by default ready-maid solution when service principal getting expired should get a mail alert.我很惊讶在 2022 年,当服务主体过期时,默认情况下没有现成的解决方案应该收到邮件警报。

I am new to Azure admin stuff could help us to run the azure CLI or Azure automation (what modules I need to install & which script to get the alert.) I have found a script but some how it is not running in azure cli and azure automation.我是 Azure 管理员的新手,可以帮助我们运行 azure CLI 或 Azure 自动化(我需要安装哪些模块以及获取警报的脚本。)我找到了一个脚本,但有些脚本没有在 azure cli 中运行,并且天蓝色自动化。

https://dev.azure.com/leo1984sandeep/Sandeep%20Project/_git/Sandeep%20Project?path=/Useful%20Powershell%20Scripts/get%20SPN%20details%20with%20secret%20expiry.ps1
    

Thanks Anuj Gupta谢谢阿努杰古普塔

Please check if my findings are helpful,请检查我的发现是否有帮助,

We can use the below script to automate for getting alert when our serviceprincipal is about to expired using sendgrid:当我们的 serviceprincipal 使用 sendgrid 即将过期时,我们可以使用以下脚本自动获取警报:

PowerShell Script:- PowerShell 脚本:-

Param
(
    [Parameter (Mandatory = $true,
        HelpMessage = "Enter the originating email address.")]
    [string] $FromEmailAddress,
    [Parameter (Mandatory = $true,
        HelpMessage = "Enter the destination email address.")]
    [string] $ToEmailAddress,
    [Parameter (Mandatory = $true,
        HelpMessage = "Enter the email subject.")]
    [string] $EmailSubject,
    [Parameter (Mandatory = $true,
        HelpMessage = "Enter the number of days to warn of credential expiry")]
    [string] $ExpiresInDays
)

function Send-EmailWithSendGrid {
    Param
    (
        [Parameter(Mandatory = $true)]
        [string] $From,

        [Parameter(Mandatory = $true)]
        [String] $To,

        [Parameter(Mandatory = $true)]
        [string] $ApiKey,

        [Parameter(Mandatory = $true)]
        [string] $Subject,

        [Parameter(Mandatory = $true)]
        [string] $Body

    )

    $headers = @{}
    $headers.Add("Authorization", "Bearer $apiKey")
    $headers.Add("Content-Type", "application/json")

    $jsonRequest = [ordered]@{
        personalizations = @(@{to = @(@{email = "$To" })
                subject           = "$SubJect" 
            })
        from             = @{email = "$From" }
        content          = @( @{ type = "text/plain"
                value        = "$Body" 
            }
        )
    } | ConvertTo-Json -Depth 10
    Invoke-RestMethod   -Uri "https://api.sendgrid.com/v3/mail/send" -Method Post -Headers $headers -Body $jsonRequest 

}

try {
    #Get the connection "AzureRunAsConnection "

    $servicePrincipalConnection = Get-AutomationConnection -Name "AzureRunAsConnection"

    "Logging in to Azure..."
    $connectionResult = Connect-AzAccount -Tenant $servicePrincipalConnection.TenantID `
        -ApplicationId $servicePrincipalConnection.ApplicationID   `
        -CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint `
        -ServicePrincipal
    "Logged in."

}
catch {
    if (!$servicePrincipalConnection) {
        $ErrorMessage = "Connection $connectionName not found."
        throw $ErrorMessage
    }
    else {
        Write-Error -Message $_.Exception
        throw $_.Exception
    }
}


Write-Host 'Gathering necessary information...'
$applications = Get-AzADApplication
$servicePrincipals = Get-AzADServicePrincipal

$appWithCredentials = @()
$appWithCredentials += $applications | Sort-Object -Property DisplayName | % {
    $application = $_
    $sp = $servicePrincipals | ? ApplicationId -eq $application.ApplicationId
    Write-Verbose ('Fetching information for application {0}' -f $application.DisplayName)
    $application | Get-AzADAppCredential -ErrorAction SilentlyContinue | Select-Object -Property @{Name = 'DisplayName'; Expression = { $application.DisplayName } }, @{Name = 'ObjectId'; Expression = { $application.Id } }, @{Name = 'ApplicationId'; Expression = { $application.ApplicationId } }, @{Name = 'KeyId'; Expression = { $_.KeyId } }, @{Name = 'Type'; Expression = { $_.Type } }, @{Name = 'StartDate'; Expression = { $_.StartDate -as [datetime] } }, @{Name = 'EndDate'; Expression = { $_.EndDate -as [datetime] } }
}

Write-Host 'Validating expiration data...'
$today = (Get-Date).ToUniversalTime()
$limitDate = $today.AddDays($ExpiresInDays)
$appWithCredentials | Sort-Object EndDate | % {
    if ($_.EndDate -lt $today) {
        $_ | Add-Member -MemberType NoteProperty -Name 'Status' -Value 'Expired'
    }
    elseif ($_.EndDate -le $limitDate) {
        $_ | Add-Member -MemberType NoteProperty -Name 'Status' -Value 'ExpiringSoon'
    }
    else {
        $_ | Add-Member -MemberType NoteProperty -Name 'Status' -Value 'Valid'
    }
}

$ExpiringAppCredentials = $appWithCredentials | ? { $_.Status -eq 'Expired' -or $_.Status -eq 'ExpiringSoon' } | Sort-Object -Property DisplayName
$ExpiringAppCredentialsString = $ExpiringAppCredentials | Out-String
#$ExpiringAppCredentialsString = $ExpiringAppCredentials | sort-object -Property enddate | format-table  -Property displayname, startdate, enddate, status, applicationid, keyid, type | Out-String


$ApiKeyString = Get-AutomationVariable -Name "SendGridAutomationCloudServices"

$From = $FromEmailAddress 
$To = $ToEmailAddress  
$APIKEY = $ApiKeyString
$Subject = $EmailSubject 
$Body = "$ExpiringAppCredentialsString"

Send-EmailWithSendGrid -from $from -to $to -ApiKey $APIKEY -Body $Body -Subject $Subject 

For more information please refer this MICROSOFT|TECH COMMUNITY有关更多信息,请参阅此MICROSOFT|TECH 社区

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 azure中的服务主体监控 - Service principal monitoring in azure 使用 PowerShell 获取 Azure 自动化帐户连接的服务主体 - Getting the service principal for an Azure Automation Account connection using PowerShell 使用 PSKeyVaultCertificate 向 Azure 服务主体添加身份验证时出现请求错误 - Request error when using a PSKeyVaultCertificate to add authentication to an Azure Service Principal 无法将凭据添加到Azure AD中的服务主体 - Unable to add Credential to a Service Principal in Azure AD 如何安全/保护 Azure 服务主体机密 - How safe/protect Azure service principal secret 使用 PowerShell 使用 azure 中的服务主体 ID 登录时无法获取订阅详细信息 - unable to get subscription details when logging in with service principal id in azure using PowerShell 使用 Microsoft Graph SDK for Powershell 将角色分配给应用服务主体? - Using Microsoft Graph SDK for Powershell to Assign Role to App Service Principal? 以服务主体身份登录 Microsoft.PowerApps.Administration.PowerShell 空列表 - Login as Service Principal Microsoft.PowerApps.Administration.PowerShell empty list 获取 Azure DevOps 服务连接服务主体 id 与 powershell - Get Azure DevOps service connection service principal id with powershell Azure服务主体权限不足,无法管理其他服务主体 - Azure Service principal insufficient permissions to manage other service principals
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM