3

when generating Service Principal in Azure manually, as a result of the operation I'm provided a password.

It's not the case however if I create service principal with Terraform, the password is not among the outputs of this module:

  + azuread_service_principal.k8s_principal
      id:                <computed>
      application_id:    "${azuread_application.app.application_id}"
      display_name:      <computed>

Is there anything I missed? Why does the Terraform behavior differs in the output compared to CLI?

Bernard Halas
  • 972
  • 11
  • 24
  • wire password into other place, or get password as data to be wired into other places, or look at state file - here it is. you cannot export it, it will give – Dzmitry Lahoda Jun 17 '21 at 07:23

3 Answers3

8

password is required INPUT to the azuread_service_principal_password block. As such, you can generate a random password and export it yourself. Complete Terraform code is something like this:

resource "azuread_application" "app" {
  name = "${local.application_name}"
}

# Create Service Principal
resource "azuread_service_principal" "app" {
  application_id = "${azuread_application.app.application_id}"
}

resource "random_string" "password" {
  length  = 32
  special = true
}

# Create Service Principal password
resource "azuread_service_principal_password" "app" {
  end_date             = "2299-12-30T23:00:00Z"                        # Forever
  service_principal_id = "${azuread_service_principal.app.id}"
  value                = "${random_string.password.result}"
}

output "sp_password" {
  value = "${azuread_service_principal_password.app.value}"
  sensitive = true
}
Derek
  • 1,466
  • 15
  • 24
2

In the terraform document, the azuread_service_principal block only defines the Argument application_id and Attributes id, display_name, So you only could see these resources. Also, the azuread_service_principal_password block allows you to export the Key ID for the Service Principal Password. You still could not see the real password.

In the Azure CLI az ad sp create-for-rbac has an optional parameter --Password. So you could see the password output.

Nancy
  • 26,865
  • 3
  • 18
  • 34
2

to who using newer version of Terraform, you don't need to preset the password, following code is working fine:

    resource "azuread_service_principal_password" "auth_pwd" {
      service_principal_id = azuread_service_principal.auth.id
    }
    
    output "auth_client_secret" {
      value = azuread_service_principal_password.auth_pwd.value
      description = "output password"
      sensitive = true
    }

then you can run the following cli to retrieve the password:

terraform output -raw auth_client_secret

tested on terraform 1.0.10, hashicorp/azuread provider 2.11

Ming M Zheng
  • 274
  • 1
  • 8