↓ Skip to main content

Spacelift Deploy for Azure (Part 1): Setting Up Authentication

·2182 words·11 mins
Mattias Fjellström
Author
Mattias Fjellström
Author · Microsoft MVP · AWS Community Builder · IBM Champion

Before you use Spacelift Deploy to manage your Microsoft Azure environment, you have to set up an integration between the two platforms. In this blog post I go through different options and how you configure them using OpenTofu.

In the code examples below I will use the following OpenTofu provider configurations:

terraform {
  required_providers {
    azurerm = {
      source  = "hashicorp/azurerm"
      version = "5.15.0"
    }

    azuread = {
      source  = "hashicorp/azuread"
      version = "3.10.0"
    }

    spacelift = {
      source  = "spacelift-io/spacelift"
      version = "1.61.0"
    }
  }
}

provider "azurerm" {
  features {}
}

provider "azuread" {}

provider "spacelift" {}

I run my examples locally and use the Azure CLI to authenticate to Azure. I use environment variables SPACELIFT_API_KEY_ENDPOINT, SPACELIFT_API_KEY_ID and SPACELIFT_API_KEY_SECRET to authenticate to Spacelift Deploy.

Spacelift-managed integration
#

If you are keen on getting started quickly, you can use the managed integration within Spacelift Deploy. In this setup a managed service principal (Enterprise Application) will be created in your Azure tenant. The service principal is managed by Spacelift.

Note

An app registration (think of it as a class) defines configuration for the underlying service principal (think of it as an object of the class). The service principal also appears as an Enterprise Application in your Entra ID tenant. One app registration can have multiple service principals in different tenants, but a service principal only belongs to one app registration.

When you create an app registration in your own Azure tenant you get both the app registration and a service principal. When you install an app from a different tenant in your tenant you only get the service principal. The app registration lives in the tenant where it was created.

Configure a default Azure integration that is automatically attached to any stack having the autoattach:azure label (the distinction default here is my own convention, it is not enforced automatically in any way):

data "azurerm_client_config" "current" {}

resource "spacelift_azure_integration" "default" {
  name                    = "Default Azure Integration"
  tenant_id               = data.azurerm_client_config.current.tenant_id
  default_subscription_id = data.azurerm_client_config.current.subscription_id
  autoattach_enabled      = true
  labels = [
    "autoattach:azure",
  ]
}

Next, create the service principal object from the underlying app registration (referenced by its application ID):

resource "azuread_service_principal" "spacelift" {
  client_id = spacelift_azure_integration.default.application_id
}

The integration requires admin consent in the Entra tenant, and this process requires the app to ask for at least one permission in Entra1. The Entra API is known as the Graph API and we can add and grant a permission for the Spacelift service principal in the Graph API like this:

data "azuread_service_principal" "graph" {
  client_id = "00000003-0000-0000-c000-000000000000"
}

resource "azuread_service_principal_delegated_permission_grant" "user_read" {
  service_principal_object_id          = azuread_service_principal.spacelift.object_id
  resource_service_principal_object_id = data.azuread_service_principal.graph.object_id
  claim_values                         = [
    "User.Read",
  ]
}

Since we handled the consent process in code instead of in the UI we need to tell Spacelift about this, we do that through a dedicated resource:

resource "spacelift_azure_integration_consent" "azure" {
  integration_id = spacelift_azure_integration.default.id
  depends_on = [
    azuread_service_principal_delegated_permission_grant.user_read,
  ]
}

Finally, assign permissions (one or more Azure roles) to the service principal. This example assigns the Contributor role (this is a highly privileged role but is fine for experimentation and POCs):

resource "azurerm_role_assignment" "contributor" {
  principal_id                     = azuread_service_principal.spacelift.object_id
  scope                            = "/subscriptions/${data.azurerm_client_config.current.subscription_id}"
  role_definition_name             = "Contributor"
  skip_service_principal_aad_check = true
}

After this integration is available we can create a stack with the same label as was configured in the integration (i.e. azure) and the Azure integration will automatically be attached to the stack:

resource "spacelift_space" "azure" {
  name            = "azure"
  parent_space_id = "root"
}

resource "spacelift_stack" "azure_stack" {
  name        = "azure-stack"
  description = "Example stack for provisioning Azure infrastructure"
  space_id    = spacelift_space.azure.id

  # ... other arguments omitted for brevity

  labels = [
    "azure",
  ]
}

If you don’t want to use auto-attachment, you can explicitly configure attachments instead:

resource "spacelift_azure_integration_attachment" "default" {
  integration_id = spacelift_azure_integration.default.id
  stack_id       = spacelift_stack.azure_stack.id
}

Create a custom app registration
#

Warning

You can configure an integration that uses static credentials (client secret or certificate). This is not recommended since static credentials represent a risk if they are leaked. I will not consider static credentials in this blog post.

The managed integration uses an app registration that lives in Spacelift’s tenant and a service principal that lives in your tenant. An alternative is to set up your own app registration.

There are some bells and whistles you can configure for your custom app, but the minimum configuration to create the app registration and corresponding service principal is this:

resource "azuread_application" "spacelift" {
  display_name = "spacelift-deploy"
}

resource "azuread_service_principal" "spacelift" {
  client_id = azuread_application.spacelift.client_id
}

Instead of static credentials we will configure a number of federated identity credentials for the application:

variable "spacelift_hostname" {
  type = string
}

variable "stack_id" {
  type = string
}

variable "space_id" {
  type = string
}

locals {
  oidc_issuer   = "https://${var.spacelift_hostname}"
  oidc_audience = [var.spacelift_hostname]

  subject_suffixes = {
    proposed-read = "PROPOSED:scope:read"
    tracked-read  = "TRACKED:scope:read"
    tracked-write = "TRACKED:scope:write"
    destroy-write = "DESTROY:scope:write"
    task-write    = "TASK:scope:write"
  }

  federated_subjects = {
    for name, suffix in local.subject_suffixes :
    name => "space:${var.space_id}:stack:${var.stack_id}:run_type:${suffix}"
  }
}

resource "azuread_application_federated_identity_credential" "all" {
  for_each = local.federated_subjects

  display_name   = each.key
  application_id = azuread_application.spacelift.id
  issuer         = local.oidc_issuer
  audiences      = local.oidc_audience
  subject        = each.value
}

This code configures one credential for each relevant subject value for a given space and stack. Federated identity credentials configure a trust relationship between your Spacelift Deploy organization (specifically for the space and stack) and this app on Azure.

Note

There is a limit of 20 federated identity credentials for an application, this example creates five.

It is also worth noting that flexible federated identity credentials are currently not supported for Spacelift Deploy.

Finally, assign one or more Azure roles to the service principal to allow it to perform actions in your Azure environment:

data "azurerm_client_config" "current" {}

resource "azurerm_role_assignment" "contributor" {
  principal_id         = azuread_service_principal.spacelift.object_id
  scope                = "/subscriptions/${data.azurerm_client_config.current.subscription_id}"
  role_definition_name = "Contributor"
}

See Configure environment variables for federated identity authentication for how to configure a stack to use the service principal.

User-assigned managed identity
#

App registrations are part of Entra ID and you configure them in OpenTofu through the azuread provider. There is an alternative that does not involve Entra ID (although the underlying object is a service principal in Entra): user-assigned managed identities.

A user-assigned managed identity is an Azure resource created through the azurerm provider. In a larger organization it is less common that developers have permissions to work independently in Entra ID, but more common that they have access to their own Azure subscriptions. That is why this approach might be a better fit.

A benefit of these identities is that you can tie them to supported Azure resources (e.g. Azure Functions, Virtual Machines, AKS clusters, etc). You can then authenticate as the identity through the resource to the external platforms you integrate with.

Create a new resource group for this example:

variable "azure_location" {
  type = string
}

resource "azurerm_resource_group" "example" {
  name     = "rg-user-assigned-managed-identity"
  location = var.azure_location
}

Create a user-assigned managed identity:

resource "azurerm_user_assigned_identity" "spacelift" {
  name                = "id-spacelift"
  resource_group_name = azurerm_resource_group.example.name
  location            = azurerm_resource_group.example.location
}

Here we have prefixed the name of the identity by id-, following the recommended abbreviations by Microsoft.

Configure a number of federated identity credentials for the identity similar to what we did for the app registration in the previous section:

variable "spacelift_hostname" {
  type = string
}

variable "stack_id" {
  type = string
}

variable "space_id" {
  type = string
}

locals {
  oidc_issuer   = "https://${var.spacelift_hostname}"
  oidc_audience = [var.spacelift_hostname]

  subject_suffixes = {
    proposed-read = "PROPOSED:scope:read"
    tracked-read  = "TRACKED:scope:read"
    tracked-write = "TRACKED:scope:write"
    destroy-write = "DESTROY:scope:write"
    task-write    = "TASK:scope:write"
  }

  federated_subjects = {
    for name, suffix in local.subject_suffixes :
    name => "space:${var.space_id}:stack:${var.stack_id}:run_type:${suffix}"
  }
}

resource "azurerm_federated_identity_credential" "all" {
  for_each = local.federated_subjects

  name                      = each.key
  audience                  = local.oidc_audience
  issuer                    = local.oidc_issuer
  user_assigned_identity_id = azurerm_user_assigned_identity.spacelift.id
  subject                   = each.value
}

As always we need to give the identity one or more roles to allow it to perform actions in our Azure environment:

data "azurerm_client_config" "current" {}

resource "azurerm_role_assignment" "contributor" {
  principal_id         = azurerm_user_assigned_identity.spacelift.principal_id
  scope                = "/subscriptions/${data.azurerm_client_config.current.subscription_id}"
  role_definition_name = "Contributor"
}

See Configure environment variables for federated identity authentication for how to configure a stack to use the managed identity.

As mentioned previously, a user-assigned managed identity can be associated with one or more Azure resources. If you use a private worker pool with workers running on Azure with an attached user-assigned managed identity, you can utilize the attached identity to authenticate to Azure.

In that case you do not need to configure any federated identity credentials. However, you need to set an environment variable named ARM_USE_MSI to true to tell the Azure provider to use the managed identity, alternatively set it explicitly in the provider block:

provider "azurerm" {
  features {}
  # ... other configuration options omitted ...
  use_msi = true
}

Also see Configure environment variables for federated identity authentication for additional environment variables you need to configure for this integration to work.

The downside with this approach is that every run using this private worker pool can use the same identity.

Read my earlier blog post to learn more about how to run private worker pools on Spacelift Deploy:

Configure environment variables for federated identity authentication
#

If you have set up a custom integration using either an app registration or a user-assigned managed identity, you need to provide a few configuration details to the stacks where the identity should be used.

Specifically, you must provide:

  • Your Azure tenant ID.
  • Your Azure subscription ID.
  • The identity client ID (i.e. reference azuread_service_principal.spacelift.client_id or azurerm_user_assigned_identity.spacelift.client_id depending on which type of identity you use).

You could configure these as variables in your OpenTofu configuration:

variables "arm_tenant_id" {
  type = string
}

variables "arm_subscription_id" {
  type = string
}

variables "arm_client_id" {
  type = string
}

provider "azurerm" {
  features {}

  use_oidc             = true
  oidc_token_file_path = "/mnt/workspace/spacelift.oidc"
  
  tenant_id       = var.arm_tenant_id
  subscription_id = var.arm_subscription_id
  client_id       = var.arm_client_id
}

It’s usually better to supply these as environment variables ARM_TENANT_ID, ARM_SUBSCRIPTION_ID, ARM_CLIENT_ID instead, simplifying the provider configuration to:

provider "azurerm" {
  features {}

  use_oidc             = true
  oidc_token_file_path = "/mnt/workspace/spacelift.oidc"
}

You can attach these environment variables directly to a consuming stack:

resource "spacelift_space" "azure" {
  name            = "azure"
  parent_space_id = "root"
}

resource "spacelift_stack" "azure_stack" {
  name        = "azure-stack"
  description = "Example stack for provisioning Azure infrastructure"
  space_id    = spacelift_space.azure.id

  # ... other arguments omitted for brevity
}

resource "spacelift_environment_variable" "azure" {
  for_each = {
    ARM_TENANT_ID       = var.arm_tenant_id
    ARM_SUBSCRIPTION_ID = var.arm_subscription_id
    ARM_CLIENT_ID       = var.arm_client_id
  }

  stack_id   = spacelift_stack.azure_stack.id
  name       = each.key
  value      = each.value
  write_only = false
}

If the same identity should be used from multiple stacks, you can create a context:

resource "spacelift_context" "azure" {
  name     = "azure"
  space_id = spacelift_space.azure.id
}

resource "spacelift_environment_variable" "azure" {
  for_each = {
    ARM_TENANT_ID       = var.arm_tenant_id
    ARM_SUBSCRIPTION_ID = var.arm_subscription_id
    ARM_CLIENT_ID       = var.arm_client_id
  }

  context_id = spacelift_context.azure.id
  name       = each.key
  value      = each.value
  write_only = false
}

Then attach the context to a stack:

resource "spacelift_context_attachment" "azure_stack" {
  context_id = spacelift_context.azure.id
  stack_id   = spacelift_stack.azure_stack.id
}

Note that if you use a shared context for multiple stacks you need to configure federated identity credentials for each stack. You will quickly reach the limit of 20 federated identity credentials for a given identity in this way.

Comparison and conclusions
#

My recommendation is to use the managed Spacelift Deploy integration with Azure if you are setting up a POC or simply evaluating Spacelift Deploy for your IaC needs. It’s quick to set up and works seamlessly.

For any other integration I recommend using either a custom app registration or a user-assigned managed identity. To choose between the two ask yourself the following questions:

  • Do you have permissions to manage resources on Entra ID? Then you can use either option. If you lack Entra ID permissions, it will be easier to work with user-assigned managed identities which are Azure resources (not Entra resources).
  • Do you want to attach the identity to an Azure resource and authenticate as that resource? Use an user-assigned managed identity.
  • Do you need to work across multiple Entra tenants? If so, you should use an app registration.

The only thing I find slightly inconvenient is that a user-assigned managed identity shows up as an Azure resource and you must place it in a resource group as any other resource. Personally I find it difficult to know how to manage these identities when there are more than one: do I place them in a common resource group? Do I use dedicated resource groups? Do I place them in resource groups along with other resources?


I recommend creating an OpenTofu module for a Spacelift Deploy stack with an associated unique Azure integration. This gives each stack a unique identity that can be scoped to the exact permissions it requires in your Azure environment. Also, the limitation of 20 federated identity credentials will never be a problem if you use unique identities per stack.

Neither integration options has any additional cost associated with it (apart from the required licenses for each platform).


  1. This feels strange, but it’s a feature of Entra not Spacelift Deploy. ↩︎

Related