0
votes

I have been able to successfully create a Service Principal secret with the below terraform. However, I am a bit confused on what is the correct approach for trying to create a Service Principal for several subscriptions. I am bit of a novice and unfortunately running into a wall with this. What is the best/right way to implement service principal for multiple subscriptions?

data "azurerm_subscription" "example-subscription" {
    subscription_id = "959e460c-209e-43d7-a6e9-e30c716e0691"
}

# Azure AD App
resource "azuread_application" "example-subscription" {
  name                       = "example-subscription"
  available_to_other_tenants = false
}

# Service Principal associated with the Azure AD App
resource "azuread_service_principal" "example-subscription" {
  application_id = azuread_application.example-subscription.application_id
}

# Random string to be used for Service Principal password
resource "random_password" "password-subscription" {
  length  = 32
  special = true
}

# Service Principal password
resource "azuread_service_principal_password" "example-subscription" {
  service_principal_id = azuread_service_principal.example-subscription.id
  value                = random_password.password-subscription.result
  end_date_relative    = "17520h"
}

# Role assignment for service principal
resource "azurerm_role_assignment" "example-subscription" {
  scope                = data.azurerm_subscription.example-subscription.id
  role_definition_name = "Contributor"
  principal_id         = azuread_service_principal.example-subscription.id
}

Example Subscriptions

data "azurerm_subscription" "example-subscription" {
    subscription_id = "959e460c-209e-43d7-a6e9-e30c716e0691"
}

data "azurerm_subscription" "example-subscription2” {
    subscription_id = "b344b74c-4600-470d-ad73-e918b0d0ccd3"
}

data "azurerm_subscription" "example-subscription3” {
    subscription_id = "242d05b2-e06e-4713-8094-44955dab1ee8"
}
1

1 Answers

1
votes

A service principal is the local representation, or application instance, of a global application object in a single Azure AD tenant or directory. A service principal is a concrete instance created from the application object and inherits certain properties from that application object.

https://docs.microsoft.com/en-us/azure/active-directory/develop/app-objects-and-service-principals

If you have multiple Azure Subscription in one Azure AD tenant you may use your single Service Principal across all of your Azure Subscriptions.