【问题标题】:Getting the Secret of a Service Prinicpal in YAML Pipeline (Terraform)在 YAML 管道(Terraform)中获取服务主体的秘密
【发布时间】:2022-01-07 11:43:10
【问题描述】:

我需要在 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,但我无法获得秘密。那我怎么得到它?虽然我在构建过程中使用相同的服务原则。

【问题讨论】:

  • hello @jason_hough ,无法为您的客户端 id 检索已经创建的客户端密码,唯一的方法是生成一个新的并在创建后从 powershell 使用它或使用默认的对其进行硬编码。

标签: azure powershell azure-devops terraform


【解决方案1】:

正如我已经提到的您只能在创建时检索秘密值之后它会被隐藏 。因此,建议将创建的文件存储在某个安全的地方或密钥库中。

如您所见,我使用 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

输出:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-04
    • 2021-10-07
    • 1970-01-01
    • 2020-01-08
    • 2020-10-01
    • 2021-05-05
    • 2020-01-05
    • 1970-01-01
    相关资源
    最近更新 更多