WireGuard on Azure · Appendix to part 2

Wiring Terraform to Azure

Creating a dedicated identity for Terraform on Azure: key pair and certificate, Service Principal, and RBAC permissions narrowed by a condition to contain the blast radius.

  • Azure
  • Terraform
  • Service Principal
  • RBAC
  • ABAC

As you can imagine, when we talk about cloud deployment, we also talk about identities, and how their authentication and authorizations are handled. The wonderful world where Terraform would connect to our cloud instance with zero configuration is not here yet :)

Following the documentation of Terraform’s azurerm provider, several options are available:

  • “Authenticating to Azure using Managed Service Identity”
  • “Authenticating to Azure using the Azure CLI”
  • “Authenticating to Azure using a Service Principal and a Client Certificate”
  • “Authenticating to Azure using a Service Principal and a Client Secret”
  • “Authenticating to Azure using OpenID Connect”

The most obvious one for the case documented here (a personal deployment from a personal machine) is “Authenticating to Azure using the Azure CLI”. So naturally, I went with “Authenticating to Azure using a Service Principal and a Client Certificate” 🤡

Why? Because in spirit, although the technical implementation differs, it is close to what you find with Kubernetes. Since I work with Azure and K8s, I might as well keep similar practices. Our “sp-terraform” identity will therefore have its certificate, and that is what it will use to authenticate with Azure. It will then need the right permissions: the RBAC roles.

Speaking of which, let’s talk about these RBAC roles. A design choice lies ahead:

  • Full permissions on the subscription, so at least no headaches? (At the risk of some nasty surprises if the cert leaks)
  • Rights on a dedicated resource group? But very little room to maneuver for Terraform and for what the project can do

Or else… there is the dark and painful path… the path of RBAC CONDITIONS 😧 (My AZ-104 trauma; if you are curious, have fun (or maybe I just never understood it because I am plain dumb, which is a highly plausible theory))

Once everything is in place, it will look like this:

Diagram 'From the key pair to the Azure token'. On the local machine, in PowerShell, openssl generates a private key sp-terraform.key and a public certificate sp-terraform.crt, then a sp-terraform.pfx file that bundles both, protected by a passphrase. The public certificate is registered in Microsoft Entra ID on the sp-terraform App Registration, whose Enterprise Application is the service principal that receives the roles. These setup steps are done once, with an admin account. On every terraform plan or apply, the azurerm provider reads the ARM_* environment variables, sends Entra ID an assertion signed with the private key, receives an access token valid for about one hour, then calls Azure Resource Manager with that token. On the subscription, the service principal holds two roles: Contributor, which creates, changes and deletes resources with no rights on RBAC, and RBAC Administrator with an ABAC condition, which can only assign or remove Key Vault Secrets User, and only to service principals. The private key never leaves the machine: only the public certificate goes to Entra ID.
From the key pair to the Azure token: the one-time setup, and what happens on every terraform plan / apply. · enlarge diagram


Authn

Create a self-signed certificate:

powershell
openssl req -x509 -newkey rsa:4096 -sha256 -days 365 -noenc `
  -keyout sp-terraform.key `
  -out    sp-terraform.crt `
  -subj "/CN=sp-terraform"

The certificate is needed base64-encoded, on a single line, without BEGIN/END… So you have to play a little with the .NET classes to extract it cleanly:

powershell
$cert = [System.Security.Cryptography.X509Certificates.X509Certificate2]::new($(Resolve-Path ~\Desktop\sp-terraform.crt).Path)
$certValue = [System.Convert]::ToBase64String($cert.GetRawCertData())

Then we create the Service Principal on Azure, passing the certificate extracted above:

powershell
$sp = New-AzADServicePrincipal -DisplayName "sp-terraform" `
  -CertValue $certValue `
  -StartDate $cert.NotBefore `
  -EndDate   $cert.NotAfter

Terraform needs a certificate in PFX format to authenticate; generate it with a passphrase:

powershell
$pw = Read-Host "Passphrase" -AsSecureString
$env:ARM_CLIENT_CERTIFICATE_PASSWORD = [System.Net.NetworkCredential]::new('', $pw).Password

openssl pkcs12 -export -out sp-terraform.pfx `
  -inkey sp-terraform.key `
  -in sp-terraform.crt `
  -passout env:ARM_CLIENT_CERTIFICATE_PASSWORD

A small adventure in itself, but at least we now have a dedicated identity for Terraform, easy to carry from one environment to another, and traceable.

We can then fill in the variables Terraform needs to authenticate to Azure. Several options: declare them as variables in an HCL file read by Terraform, set them directly in the “provider” block, or declare them as environment variables. I go with the last option:

powershell
$env:ARM_CLIENT_ID = (Get-AzADServicePrincipal -DisplayName "sp-terraform").AppId
$env:ARM_TENANT_ID = (Get-AzContext).Tenant.Id
$env:ARM_SUBSCRIPTION_ID = (Get-AzSubscription -SubscriptionName "Root subscription").Id
$env:ARM_CLIENT_CERTIFICATE_PATH = (Resolve-Path -Path "~\Desktop\sp-terraform.pfx").Path
$env:ARM_CLIENT_CERTIFICATE_PASSWORD = "don't push your luck"

Authz

Assigning the Contributor role: manage resources, without being able to touch RBAC:

powershell
$subId = (Get-AzSubscription -SubscriptionName "Root subscription").Id
$scope = "/subscriptions/$subId"

New-AzRoleAssignment -ObjectId $sp.Id `
  -RoleDefinitionName "Contributor" `
  -Scope $scope

Condition to narrow the RBAC Administrator role:

powershell
# Get the ID of the Key Vault Secrets User role, used by the condition
$kvRoleId = (Get-AzRoleDefinition -Name "Key Vault Secrets User").Id

$condition = @"
(
  (!(ActionMatches{'Microsoft.Authorization/roleAssignments/write'}))
  OR
  (
    @Request[Microsoft.Authorization/roleAssignments:RoleDefinitionId] ForAnyOfAnyValues:GuidEquals {$kvRoleId}
    AND
    @Request[Microsoft.Authorization/roleAssignments:PrincipalType] ForAnyOfAnyValues:StringEqualsIgnoreCase {'ServicePrincipal'}
  )
)
AND
(
  (!(ActionMatches{'Microsoft.Authorization/roleAssignments/delete'}))
  OR
  (
    @Resource[Microsoft.Authorization/roleAssignments:RoleDefinitionId] ForAnyOfAnyValues:GuidEquals {$kvRoleId}
  )
)
"@

Well… this syntax is a bit hard to swallow, but it rests on a single pattern, repeated twice. I might as well make the most of all the fun I had with it (not) and write a short recap. At least after this, the AZ-104 will no longer be scary on this point, because yes, there are questions about it.

The pattern: a disguised “if … then”

The condition language has no “if … then”. To express “if the action is X, then this constraint must hold”, we use a small logic trick: “if X then Y” is written "(NOT X) OR Y"

In other words: either we are not doing X (and all is well), or we are doing X and Y must be true. In the example: either we want to do something other than write (assign) an RBAC role, and that is fine, or, if we want to assign an RBAC role, it must be the “KV Secrets User” role. That’s all.

Here is a recap with a truth table (wow, jargon from distant classes):

X (action of writing a “Role Assignment”)Y (Role = KV Secrets User)Result “(NOT X) OR Y”
truetrue✅ true
truefalse❌ false
falsetrue✅ true
falsefalse✅ true

Our condition is therefore simply:

  • Block 1: if the SP creates a role assignment, then it must be Key Vault Secrets User, and for a service principal.
  • Block 2: if the SP deletes a role assignment, then it must be a Key Vault Secrets User assignment.
  • The two blocks are joined by an AND: both rules must hold at all times.

A golden rule

A condition can only restrict. It filters the actions already granted by the role, it never adds any. The “RBAC Administrator” role grants, among others, “roleAssignments/write” and “roleAssignments/delete”: these are exactly the two actions our condition narrows. Everything else (reading, in particular) goes through untouched.

When the condition is not met, Azure returns a nice “403 AuthorizationFailed” mentioning “ABAC condition that is not fulfilled”. We will trigger it on purpose right after 🙃

The truth table

Action attempted by sp-terraformBlock 1 (write)Block 2 (delete)Result
Read anything✅ not a write✅ not a delete✅ Allowed
Assign Reader❌ wrong role✅❌ Denied
Assign itself RBAC Administrator❌ wrong role✅❌ Denied
Assign Key Vault Secrets User to an SP✅✅✅ Allowed
Assign Key Vault Secrets User to a user❌ wrong type✅❌ Denied
Delete a Key Vault Secrets User assignment✅✅✅ Allowed
Delete your account’s Owner assignment✅❌ wrong role❌ Denied

Result: even if the certificate leaks, the attacker can indeed manage the subscription’s resources (Contributor oblige), but can neither grant themselves more rights nor remove anyone else’s. The blast radius is contained. But now it would be better to actually assign this role with its condition, instead of rambling on.

Assigning the RBAC Administrator role, with the condition defined above:

powershell
$subId = (Get-AzContext).Subscription.Id

New-AzRoleAssignment -ObjectId $sp.Id `
  -RoleDefinitionName "Role Based Access Control Administrator" `
  -Scope $scope `
  -Condition $condition `
  -ConditionVersion "2.0" `
  -Description "sp-terraform: can only assign/remove Key Vault Secrets User, to service principals only"

Tests

Checking the roles assigned to the Service Principal

powershell
Get-AzRoleAssignment -ObjectId $sp.Id `
| Select-Object RoleDefinitionName, Scope, Condition `
| Format-List
Output
shell
RoleDefinitionName : Contributor
Scope              : /subscriptions/xxxx-xxxx-xxxx-xxxx-xxxx
Condition          :

RoleDefinitionName : Role Based Access Control Administrator
Scope              : /subscriptions/xxxx-xxxx-xxxx-xxxx-xxxx
Condition          : (
                       (!(ActionMatches{'Microsoft.Authorization/roleAssignments/write'}))
                       OR
                       (
                         @Request[Microsoft.Authorization/roleAssignments:RoleDefinitionId]
                     ForAnyOfAnyValues:GuidEquals {4633458b-17de-408a-b874-0445c86b69e6}
                         AND
                         @Request[Microsoft.Authorization/roleAssignments:PrincipalType]
                     ForAnyOfAnyValues:StringEqualsIgnoreCase {'ServicePrincipal'}
                       )
                     )
                     AND
                     (
                       (!(ActionMatches{'Microsoft.Authorization/roleAssignments/delete'}))
                       OR
                       (
                         @Resource[Microsoft.Authorization/roleAssignments:RoleDefinitionId]
                     ForAnyOfAnyValues:GuidEquals {4633458b-17de-408a-b874-0445c86b69e6}
                       )
                     )

Signing in with the Service Principal

powershell
Connect-AzAccount -ServicePrincipal `
  -ApplicationId $sp.AppId `
  -Tenant (Get-AzContext).Tenant.Id `
  -CertificatePath (Resolve-Path ~\Desktop\sp-terraform.pfx).Path `
  -CertificatePassword (ConvertTo-SecureString $env:ARM_CLIENT_CERTIFICATE_PASSWORD -AsPlainText -Force)
Output
powershell
Subscription name Tenant
----------------- ------
Root subscription xxxx-xxxx-xxxx-xxxx-xxxx

Testing the assignment of a forbidden role

powershell
# Should fail: Reader is not allowed by the condition
New-AzRoleAssignment -ObjectId $sp.Id -RoleDefinitionName "Reader" -Scope $scope
Output
shell
New-AzRoleAssignment: Operation returned an invalid status code 'Forbidden'. AuthorizationFailed: The client
'xxxx-xxxx-xxxx-xxxx-xxxx' with object id 'xxxx-xxxx-xxxx-xxxx-xxxx' has an authorization with
ABAC condition that is not fulfilled to perform action 'Microsoft.Authorization/roleAssignments/write' over scope '/sub
scriptions/xxxx-xxxx-xxxx-xxxx-xxxx/providers/Microsoft.Authorization/roleAssignments/fc847e5c-a150-42f7-b4ca-9eb7921f501c' or the scope is invalid. If access was recently granted, please refresh your credentials.

Testing the assignment of the “Key Vault Secrets User” role to a ServicePrincipal

powershell
# Should succeed: Key Vault Secrets User is allowed by the condition
New-AzRoleAssignment -ObjectId $sp.Id -RoleDefinitionName "Key Vault Secrets User" -Scope $scope
Output
shell
RoleAssignmentName : xxxx-xxxx-xxxx-xxxx-xxxx
RoleAssignmentId   : /subscriptions/xxxx-xxxx-xxxx-xxxx-xxxx/providers/Microsoft.Authorization/roleAssignments/xxxx-xxxx-xxxx-xxxx-xxxx
Scope              : /subscriptions/xxxx-xxxx-xxxx-xxxx-xxxx
DisplayName        : sp-terraform
SignInName         :
RoleDefinitionName : Key Vault Secrets User
RoleDefinitionId   : 4633458b-17de-408a-b874-0445c86b69e6
ObjectId           : xxxx-xxxx-xxxx-xxxx-xxxx
ObjectType         : ServicePrincipal
CanDelegate        : False
Description        :
ConditionVersion   :
Condition          :

Testing the assignment of the “Key Vault Secrets User” role to a user

powershell
# Should fail: right role, but the assignee is not a service principal
$user = Get-AzADUser -UserPrincipalName "[email protected]"
New-AzRoleAssignment -ObjectId $user.Id -RoleDefinitionName "Key Vault Secrets User" -Scope $scope
Output
shell
New-AzRoleAssignment: Operation returned an invalid status code 'Forbidden'. AuthorizationFailed: The client 'xxxx-xxxx-xxxx-xxxx-xxxx' with object id 'xxxx-xxxx-xxxx-xxxx-xxxx' does not have authorization to perform action 'Microsoft.Authorization/roleAssignments/write' over scope '/subscriptions/xxxx-xxxx-xxxx-xxxx-xxxx/providers/Microsoft.Authorization/roleAssignments/9abc1263-fee2-4581-a06e-c305619cafbf' or the scope is invalid. If access was recently granted, please refresh your credentials

Conclusion

Well, I once again went way down the rabbit hole, spending far too much time on something an az login would have settled in ten seconds. But at least we come away with much more than a working connection:

  • An identity dedicated to Terraform, separate from my personal account (and its Owner rights)
  • Certificate-based authentication, with no shared secret in transit
  • Broad permissions where Terraform needs them (Contributor), and narrowed ones where it gets dangerous (delegating rights)
  • A tested RBAC condition: escalation is denied, the legitimate case goes through
  • My traumatic AZ-104 topic on the road to recovery :)

Let’s also be honest about what can still be improved:

  • The .pfx lives on my machine. It is protected by a passphrase, but if it leaks along with it, sp-terraform can still do quite a bit of damage in the subscription. The blast radius is contained, not zero.
  • The certificate expires in a year. And by then, I will have completely forgotten about it.

In the meantime, Terraform finally has its identity papers. All that is left is to make it do something useful… and that is where another identity comes on stage: the VM’s own, to fetch its WireGuard key from the Key Vault (after all, this is precisely the case I had so much fun with RBAC conditions for). Two identities, two roles, and a confusion trap we will defuse in the next article!

© 2026 Louis Lecat