Determine provider/resource type at runtime

Is it possible to determine the provider and/or resource type from a resource at runtime?

I want to build a module that can handle Azure role assignment for different object types passed in to it. In AzureRM the role assignment resource takes a principal ID input but this is represented by different attributes in different resources.

For an AD App this would be the resource.object_id attribute but for an AD Group it’s the resource.id. For other resources, the resource.principal_id is used.

Is there any way for me to read the type dynamically and choose the correct attribute? I could pass the type in as another input variable but this is less elegant and leaves room for error.

Hi @evershade,

Terraform has a structural type system, which means it only cares about which attributes an object type has and doesn’t assign any name to an object type. For that reason, there isn’t any way to directly ask if an object is of some named type.

I’m not very familiar with Azure but from looking at azurerm_role_assignment I see that it has an argument principal_id which can accept a user, group, or service principal ID, and so I’m afraid I don’t really understand the problem you are describing: it seems like you’d be assigning a value to principal_id in all cases, and it’s only the format of that id that would be different.

If you could show an example of what a directly-written configuration (without any module abstractions) would look like for each of the cases you want to support then I might be able to suggest an approach to generalize it to support all of the cases.