How can I use the Azure Go SDK to work with role assignments? For example, how can I use it to list the role assignments that a particular principal has?
After consulting its documentation, I was able to figure out how to create clients for various Azure services, but I wasn't able to figure this out for working with role definitions in particular. After checking Stack Overflow for whether this problem has been addressed, I found some questions with answers, but they were for other programming languages such as .NET Core.
The SDK is divided into multiple Go modules. The documentation for the SDK itself starts at a reference page that lists the modules but does not explain how to get started.
On another Azure docs page, there are instructions for authenticating the Go SDK using environment variables for the credentials associated with the service principal you want to use with the SDK -
AZURE_TENANT_ID
,AZURE_CLIENT_ID
, andAZURE_CLIENT_SECRET
. If you do not already have a service principal to use with the SDK, you will need to create one using Microsoft Entra ID (formerly known as Azure AD).With these environment variables set, you can use
NewDefaultAzureCredential
from packageazidentity
to create a credential variable that can be used with any client from the SDK.You cannot use this credential directly to create a client for working with role definitions. Instead, you must first create a client factory. The client factory must be created using the correct Go package, where there is a Go package for each Azure API. For working with role assignments, the package is
armauthorization
.Then, you can use the client factory to create a
*RoleAssignmentsClient
and use the client. You also need to use the subscription ID of the subscription for the scope you're working with.Complete code example (assumes env vars described above are set):
Example output:
Note that they are pointers when they come back from the API, and that I have two principals in my example. They are:
Note: I created this answer because I wasn't able to find docs that were useful to me right away. Eventually, I found docs in the GitHub repo. These can be used for further reference.