Terraform: Assign Azure Role
Description
It is very common to have to assign IAM roles at the resource level in Terraform. To do this, it is only a few lines of code:
To Resolve:
-
Ensure the azuread provider is present in any of your
*.tf
files since terraform doesn’t care (usuallybackend.tf
,providers.tf
, orversions.tf
) :1 2 3 4 5
provider "azuread" { tenant_id = var.tenant_id client_id = var.client_id client_secret = var.client_secret }
-
In
main.tf
just do a data lookup for the group and assign itsobject_id
to theprinciple_id
to whateverscope
you want. For example, at the Resource Group level you would do something like:1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
data "azuread_group" "my_group" { display_name = "aa_group_name" } module "azure_learning_rg" { source = "git::https://github.com/gerryw1389/terraform-modules.git//resource-group?ref=v1.0.0" resource_group_name = "aa-${var.env_stage_abbr}-${var.region_abbr}-test-remote" location = var.region tags = local.sbx_tags } resource "azurerm_role_assignment" "owner" { scope = module.azure_learning_rg.id role_definition_name = "Owner" principal_id = data.azuread_group.my_group.object_id }
Comments