Skip to content

Instantly share code, notes, and snippets.

@kewalaka
Last active January 2, 2025 02:01
Show Gist options
  • Save kewalaka/6280ae89d0c7412551b0d869b7956f55 to your computer and use it in GitHub Desktop.
Save kewalaka/6280ae89d0c7412551b0d869b7956f55 to your computer and use it in GitHub Desktop.
This terraform illustrates how to fetch the role definition ID via its common name (e.g. "Reader"), when using AzAPI.
terraform {
required_providers {
azapi = {
source = "Azure/azapi"
version = "2.1.0"
}
}
}
variable "subscription_id" {
description = "The subscription ID to query for role definitions."
type = string
}
variable "role_names" {
description = "Role Definition names to query."
type = set(string)
default = ["Reader", "Key Vault Secrets Officer"]
}
data "azapi_resource_list" "role_definition" {
for_each = var.role_names
type = "Microsoft.Authorization/roleDefinitions@2022-05-01-preview"
parent_id = "/subscriptions/${var.subscription_id}"
query_parameters = {
"$filter" = ["roleName eq '${each.key}'"]
}
response_export_values = {
"values" = "value[].{id: id}"
}
}
locals {
role_definition_map = {
for role_name, role_definition in data.azapi_resource_list.role_definition : role_name => one(role_definition.output.values).id
}
}
output "role_definitions" {
value = local.role_definition_map
}
@kewalaka
Copy link
Author

Suggestion;-

output "role_definition" { value = { for k, v in data.azapi_resource_list.role_definition : k => v.output.value[0].name } }

That's fair. I'd probably wrap it in a one() function to check only one was returned.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment