DEV Community

Smallsun2025
Smallsun2025

Posted on

Create and Assign a Custom Role in Azure Using Terraform

🧭 Introduction
In today's post, we’ll explore how to create a custom role in Azure using Terraform and assign it to a specific resource group. This is a critical step toward managing fine-grained permissions in enterprise-grade Azure deployments.

Whether you're building production systems or just learning Infrastructure as Code (IaC), this project gives you a practical look at customizing access control with Terraform.
πŸ—‚ Project Structure
Here’s a quick look at the project files:
azure-custom-role-assignment/
β”œβ”€β”€ main.tf # Define custom role + assignment
β”œβ”€β”€ variables.tf # Input variables
β”œβ”€β”€ terraform.tfvars # Variable values
β”œβ”€β”€ outputs.tf # Outputs (like Role Definition ID)
πŸ”§ What the Terraform Code Does
Creates a Custom Role using azurerm_role_definition
The role is defined in JSON format and includes permissions like Microsoft.Resources/subscriptions/resourceGroups/*.

Assigns the Role to a user, group, or service principal using azurerm_role_assignment.

Scopes the Role Assignment to a specific resource group for tight access control.
πŸš€ How to Deploy
Make sure you have:

βœ… Azure CLI (az login)

βœ… Terraform installed

Then follow these steps:

terraform init
terraform plan
terraform apply

When prompted, type yes.

After deployment, your custom role will be created and assigned β€” scoped to the resource group you specified.

πŸ” Example Use Case
Let’s say you want to grant read-only access to a service principal but only within a specific resource group, not across the whole subscription. This setup enables that β€” all in one Terraform script!

βœ… Conclusion
Custom roles are a powerful way to enforce principle of least privilege in Azure. With just a few lines of Terraform, you can define exactly what actions are permitted, where, and by whom.

This example helps solidify your understanding of:

Role Definition JSON structure

Role Assignment best practices

Scoped access control via Terraform

πŸ”œ Coming Next...
Managing Key Vault secrets via Terraform

Building reusable modules for RBAC policies

Advanced Role Assignments using Azure AD groups

If you found this useful, feel free to ⭐ the repo and share your thoughts in the comments!

πŸ“ Ready to post on Dev.to
πŸ“¦ Repo name suggestion: azure-custom-role-assignment

Top comments (0)