Service Principal in block

The Azure provider block defines syntax that allows you to specify your Azure subscription's authentication information.

To authenticate Terraform to Azure in a secure, automated, and cloud-agnostic way, use a Service Principal and reference its credentials in your provider block. This is the recommended approach for CI/CD pipelines and IaC workflows.


Step-by-Step Example

  1. Store your Service Principal credentials securely (e.g., as environment variables or in your CI/CD secret manager):

    • ARM_SUBSCRIPTION_ID

    • ARM_TENANT_ID

    • ARM_CLIENT_ID

    • ARM_CLIENT_SECRET

  2. Reference these variables in your Terraform provider block:

terraform {
  required_providers {
    azurerm = {
      source  = "hashicorp/azurerm"
      version = "~>3.0"
    }
  }
}

provider "azurerm" {
  features {}

  subscription_id = var.subscription_id
  tenant_id       = var.tenant_id
  client_id       = var.client_id
  client_secret   = var.client_secret
}

variable "subscription_id" {}
variable "tenant_id" {}
variable "client_id" {}
variable "client_secret" {}
  1. Set the variables using environment variables or a terraform.tfvars file:

Or in terraform.tfvars (not recommended for production):


Real-Life DevOps Example: GitHub Actions


Best Practices

  • Never hardcode credentials in your Terraform code or repository

  • Use environment variables or secret managers for sensitive values

  • Rotate Service Principal credentials regularly

  • Grant only the minimum RBAC permissions needed


References


Tip: For passwordless authentication in CI/CD, consider using OIDC with GitHub Actions or Azure Pipelines.


Add to SUMMARY.md

Last updated