DEV Community

Frederick Ollinger
Frederick Ollinger

Posted on

Setting Up Service Principle Deployments for Gitlab CI/CD Terraform Virtual Machine Deployments

In order to use Terraform to deploy to the cloud, you need to either be logged in to Azure all ready or you need to create a Service Principle.

How to login to Azure?

Given that you have an account:

az login
Enter fullscreen mode Exit fullscreen mode

But this won't work in the cloud as it's not headless and will leak credentials. So this is a non-starter. For testing, we need to stay logged out.

az logout
Enter fullscreen mode Exit fullscreen mode

That said, we do need to login to manipulate Service Principles. So log back in for this portion of this tutorial.

What is a Service Principle in Azure?

"An Azure service principal is a security identity used by user-created apps, services, and automation tools to access specific Azure resources." 1

List all your current Service Principles:

az ad sp list -o=table --show-mine
Enter fullscreen mode Exit fullscreen mode

Create a new Service Principle

az ad sp create-for-rbac
Enter fullscreen mode Exit fullscreen mode

2

This will give you the following:

{                                                                                                                                                                                                                  "appId": XXX,
  "displayName": XXX,
  "password": XXX,
  "tenant": XXX
}
Enter fullscreen mode Exit fullscreen mode

Map the Service Principle JSON to Terraform Variables

In the provider block:

  • client_id: This is the appId from the Service Principal JSON object.
  • client_secret: This is the password from the Service Principal JSON object.
  • tenant_id: This is the tenant from the Service Principal JSON object.
  • subscription_id: This is your Azure subscription ID. It's optional if the Service Principal has
provider "azurerm" {
  features {}

  # Use the appId (client ID), password (client secret), and tenant ID (tenant)
  client_id       = var.client_id
  client_secret   = var.client_secret
  tenant_id       = var.tenant_id
  subscription_id = var.subscription_id  # Optional: specify your Azure subscription ID
}
Enter fullscreen mode Exit fullscreen mode

Links

  1. Official Azure Service Principle Docs: https://learn.microsoft.com/en-us/cli/azure/azure-cli-sp-tutorial-1?toc=%2Fazure%2Fazure-resource-manager%2Ftoc.json&view=azure-cli-latest&tabs=bash

  2. Azure Service Principle Creation: https://stackoverflow.com/questions/48096342/what-is-azure-service-principal

Top comments (0)