Sunday, March 31, 2024

Bringing Role Assignments into Terraform State Management

Terraform is an infrastructure automation tool that keeps track of the state of your infrastructure managed by Terraform in a state file. It serves as a snapshot of the actual infrastructure. Therefore, Keeping Terraform state file up to date is crucial. If a new resource added or any manual changes are made to the actual resource, it is important to import those changes into the state file. This blog explains how to import manually added role assignment to the terraform state file.

Pre-requisites: Manually add User Access Administrator Role to the Azure resource group.

We use the terraform import command to import manually added role assignment into the terraform state file. The following command can be used to find the ID of the role assignments that have been added to the given scope. For this blog post, we use the scope of the Container-app-rg Resource group.

az role assignment list --scope <<scope>>

ex: az role assignment list --scope /subscriptions/<subscriptionid>/resourceGroups/<resource group name>

The command will give information about role assignments of the given scope similar to following.



Get the 'id' value from the results belonging to the User Access Administrator role and use it to run the Terraform import to import the state. Add the terraform code block similar to the following to your Terraform script.

resource "azurerm_role_assignment" "role" {
  scope                = "/subscriptions/<subscriptionid>/resourceGroups/container-app-rg"
  role_definition_name = "User Access Administrator"
  principal_id         = "<object id of entra user>"
}

Run following terraform import command with correct values to import the role assignment to the state file. Replace your_subscription_id with your Azure subscription ID and role_assignment_id with the ID of the role assignment you want to import.

terraform import azurerm_role_assignment.role /subscriptions/<your_subscription_id>/resourceGroups/<resource group name>/providers/Microsoft.Authorization/roleAssignments/<role_ assignment_id>



No comments:

Post a Comment