如何使用 Terraform 创建客户端密钥?

How to create a Client Secret using Terraform?

我正在尝试使用以下代码为我的服务主体创建 Client_secret:

data "azuread_service_principal" "existing_SP" {
  display_name = "TestAppRegistration"
}
resource "azuread_service_principal_password" "Client_Secret" {
  service_principal_id = data.azuread_service_principal.existing_SP.object_id
}

执行 terraform-apply 它已成功创建,但我没有在应用程序注册的“机密和证书”部分看到它:

但是当我检查 tfstate 时,它​​显示了为服务主体创建的值,但对象 ID 与同一应用程序注册的企业应用程序相同:

所以,我的问题:

  1. 如何使用 terraform 创建客户端密钥,我做错了什么吗?
  2. 如果我做的正确,那么生成的秘密可以在门户中的什么地方找到?

How can I create a client secret using terraform, is there something I am doing wrong ?

是的,你做的一切都正确。

但是为了消除这里的混淆,您可能已经知道 azure ad application 有两种类型,即 app registrationsenterprise application。在 terraform 或 powershell 或 cli 中,App Registration 被称为 Azure AD application,而同一应用程序注册的 Enterprise Application 被称为 Service Principal。因此,如果您是通过应用程序注册 blade 从门户创建的,那么默认情况下会为其创建一个服务主体,但如果您是从 Powershell 或 Terraform 创建应用程序注册,则情况就不一样了。

默认情况下 you will be not be able to see the secret or certificate created for service principal from portal 但您肯定可以将其与 client-id 一起用于身份验证目的。

例如:

我使用您的代码在我的环境中对此进行了测试,我获取了 tfstate 文件中存在的密码值并使用它来执行 az 登录:

注意:使用 terraform 创建服务主体密码是安全的,因为它将存储在 tfstate 文件中,因此您在搜索它时不会遇到困难。

If I am doing correct then where is the secret generated can be found in portal?

但是如果你想从 portal 中寻找秘密,那么我建议你使用 azuread_application:

data "azuread_application" "example" {
  display_name = "postman"
}
resource "azuread_application_password" "example" {
  display_name = "terraformgenerated"
  application_object_id = data.azuread_application.example.object_id
}