在 YAML 管道 (Terraform) 中获取服务主体的秘密

Getting the Secret of a Service Prinicpal in YAML Pipeline (Terraform)

我需要在 Terraform 中执行 Invoke-SQLCmd - 一切正常,但我需要获取在整个构建过程中使用的服务主体 (Azure) 的 Secret。所以我可以使用这个:

Import-Module SQLServer

# Note: the sample assumes that you or your DBA configured the server to accept connections using
#       that Service Principal and has granted it access to the database (in this example at least
#       the SELECT permission).

$clientid = "enter application id that corresponds to the Service Principal" # Do not confuse with its display name
$tenantid = "enter the tenant ID of the Service Principal"
$secret = "enter the secret associated with the Service Principal"

$request = Invoke-RestMethod -Method POST `
           -Uri "https://login.microsoftonline.com/$tenantid/oauth2/token"`
           -Body @{ resource="https://database.windows.net/"; grant_type="client_credentials"; client_id=$clientid; client_secret=$secret }`
           -ContentType "application/x-www-form-urlencoded"
$access_token = $request.access_token

# Now that we have the token, we use it to connect to the database 'mydb' on server 'myserver'
Invoke-Sqlcmd -ServerInstance myserver.database.windows.net -Database mydb -AccessToken $access_token`
              -query 'select * from Table1'

我可以在 PowerShell 中很容易地获得 cliendId 和 TenantID,但我无法获得秘密。那我怎么得到它呢?虽然我在构建期间使用相同的服务 Prinical。

正如我已经提到的你只能在创建时检索一个秘密值之后它变成隐藏的。因此,建议将创建的内容存储在一些安全的地方或密钥库中。

如您所见,我使用了 AzureAD Module 和以下脚本进行测试:

## Get APP Details
$APP=Get-AzureADApplication -Filter "DisplayName eq 'ansumanterraformtest'"
## ClientID
Write-Host("clientID : ")$APP.AppId 
##TenantID
$tenantID=(Get-AzureADTenantDetail).objectId
Write-Host ("TenantID :")$tenantID
## Get Secret
$getsecret=Get-AzureADApplicationPasswordCredential -ObjectId $APP.ObjectId 
if($getsecret.value -ne $null){
Write-Host ("Exisitng $get Secret Value: ")$getsecret.Value
}
else{
Write-Host ("Cannot Retrieve Secret!!!!")
}

输出:

所以,作为解决方案 我们可以创建一个新的秘密,如果您没有将它存储在任何地方,我们可以检索它,如下所示:

$end_date = (get-date).Date.AddDays(365)
## Create new Secret
$createsecret = New-AzureADApplicationPasswordCredential -CustomKeyIdentifier "PowershellKey" -ObjectId $APP.ObjectId -EndDate $end_date
## Secret Value
Write-Host ("Secret Value For new Secret :")$createsecret.value

输出: