This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Assign Azure roles using Azure CLI

  • 10 contributors

Azure role-based access control (Azure RBAC) is the authorization system you use to manage access to Azure resources. To grant access, you assign roles to users, groups, service principals, or managed identities at a particular scope. This article describes how to assign roles using Azure CLI.

Prerequisites

To assign roles, you must have:

  • Microsoft.Authorization/roleAssignments/write permissions, such as Role Based Access Control Administrator
  • Bash in Azure Cloud Shell or Azure CLI

Steps to assign an Azure role

To assign a role consists of three elements: security principal, role definition, and scope.

Step 1: Determine who needs access

You can assign a role to a user, group, service principal, or managed identity. To assign a role, you might need to specify the unique ID of the object. The ID has the format: 11111111-1111-1111-1111-111111111111 . You can get the ID using the Azure portal or Azure CLI.

For a Microsoft Entra user, get the user principal name, such as [email protected] or the user object ID. To get the object ID, you can use az ad user show .

For a Microsoft Entra group, you need the group object ID. To get the object ID, you can use az ad group show or az ad group list .

Service principal

For a Microsoft Entra service principal (identity used by an application), you need the service principal object ID. To get the object ID, you can use az ad sp list . For a service principal, use the object ID and not the application ID.

Managed identity

For a system-assigned or a user-assigned managed identity, you need the object ID. To get the object ID, you can use az ad sp list .

To just list user-assigned managed identities, you can use az identity list .

Step 2: Select the appropriate role

Permissions are grouped together into roles. You can select from a list of several Azure built-in roles or you can use your own custom roles. It's a best practice to grant access with the least privilege that is needed, so avoid assigning a broader role.

To list roles and get the unique role ID, you can use az role definition list .

Here's how to list the details of a particular role.

For more information, see List Azure role definitions .

Step 3: Identify the needed scope

Azure provides four levels of scope: resource, resource group , subscription, and management group . It's a best practice to grant access with the least privilege that is needed, so avoid assigning a role at a broader scope. For more information about scope, see Understand scope .

Resource scope

For resource scope, you need the resource ID for the resource. You can find the resource ID by looking at the properties of the resource in the Azure portal. A resource ID has the following format.

Resource group scope

For resource group scope, you need the name of the resource group. You can find the name on the Resource groups page in the Azure portal or you can use az group list .

Subscription scope

For subscription scope, you need the subscription ID. You can find the ID on the Subscriptions page in the Azure portal or you can use az account list .

Management group scope

For management group scope, you need the management group name. You can find the name on the Management groups page in the Azure portal or you can use az account management-group list .

Step 4: Assign role

To assign a role, use the az role assignment create command. Depending on the scope, the command typically has one of the following formats.

The following shows an example of the output when you assign the Virtual Machine Contributor role to a user at a resource group scope.

Assign role examples

Assign a role for all blob containers in a storage account resource scope.

Assigns the Storage Blob Data Contributor role to a service principal with object ID 55555555-5555-5555-5555-555555555555 at a resource scope for a storage account named storage12345 .

Assign a role for a specific blob container resource scope

Assigns the Storage Blob Data Contributor role to a service principal with object ID 55555555-5555-5555-5555-555555555555 at a resource scope for a blob container named blob-container-01 .

Assign a role for a group in a specific virtual network resource scope

Assigns the Virtual Machine Contributor role to the Ann Mack Team group with ID 22222222-2222-2222-2222-222222222222 at a resource scope for a virtual network named pharma-sales-project-network .

Assign a role for a user at a resource group scope

Assigns the Virtual Machine Contributor role to [email protected] user at the pharma-sales resource group scope.

Assign a role for a user using the unique role ID at a resource group scope

There are a couple of times when a role name might change, for example:

  • You are using your own custom role and you decide to change the name.
  • You are using a preview role that has (Preview) in the name. When the role is released, the role is renamed.

Even if a role is renamed, the role ID does not change. If you are using scripts or automation to create your role assignments, it's a best practice to use the unique role ID instead of the role name. Therefore, if a role is renamed, your scripts are more likely to work.

The following example assigns the Virtual Machine Contributor role to the [email protected] user at the pharma-sales resource group scope.

Assign a role for all blob containers at a resource group scope

Assigns the Storage Blob Data Contributor role to a service principal with object ID 55555555-5555-5555-5555-555555555555 at the Example-Storage-rg resource group scope.

Assign a role for an application at a resource group scope

Assigns the Virtual Machine Contributor role to an application with service principal object ID 44444444-4444-4444-4444-444444444444 at the pharma-sales resource group scope.

Assign a role for a new service principal at a resource group scope

If you create a new service principal and immediately try to assign a role to that service principal, that role assignment can fail in some cases. For example, if you use a script to create a new managed identity and then try to assign a role to that service principal, the role assignment might fail. The reason for this failure is likely a replication delay. The service principal is created in one region; however, the role assignment might occur in a different region that hasn't replicated the service principal yet. To address this scenario, you should specify the principal type when creating the role assignment.

To assign a role, use az role assignment create , specify a value for --assignee-object-id , and then set --assignee-principal-type to ServicePrincipal .

The following example assigns the Virtual Machine Contributor role to the msi-test managed identity at the pharma-sales resource group scope:

Assign a role for a user at a subscription scope

Assigns the Reader role to the [email protected] user at a subscription scope.

Assign a role for a group at a subscription scope

Assigns the Reader role to the Ann Mack Team group with ID 22222222-2222-2222-2222-222222222222 at a subscription scope.

Assign a role for all blob containers at a subscription scope

Assigns the Storage Blob Data Reader role to the [email protected] user at a subscription scope.

Assign a role for a user at a management group scope

Assigns the Billing Reader role to the [email protected] user at a management group scope.

  • List Azure role assignments using Azure CLI
  • Use the Azure CLI to manage Azure resources and resource groups

Coming soon: Throughout 2024 we will be phasing out GitHub Issues as the feedback mechanism for content and replacing it with a new feedback system. For more information see: https://aka.ms/ContentUserFeedback .

Submit and view feedback for

Additional resources

How to use Azure Managed Identity

Azure resources, like Azure Automation or Azure Virtual Machines, often need to have access to other resources. For example, when accessing the Azure AD from within a Runbook. To grant access, you usually need accounts, passwords, or certificates. But you don’t want to store this info inside your code. This is where Azure Managed Identity comes in.

Azure Managed Identity gives Azure Resources a managed identity inside your Azure AD. This way you can easily manage permissions and authenticate in Azure without the need for storing credentials.

In this article

In this article, we will look at what Azure Managed Identities are, how to create them and use them of course. I have also created a PowerShell script that allows you to easily set the permissions of your managed identity.

What are Azure Managed Identities

Azure Managed Identities are an essential tool for securely managing access to Azure resources. These identities provide a way for Azure Applications and Services to authenticate and authorize themselves without the need for storing and managing credentials. This reduces the risk of credential theft or misuse, as there are no credentials to steal or manage.

They work by creating an identity (Enterprise Application) within your Azure Active Directory (AAD). The identity is then associated with a specific Azure resource, like an Azure Automation account. You can give the identity specific permission to the different APIs in Azure, like MsGraph or Exchange Online, just like with regular Enterprise Applications in Azure AD. The identity is then used by the resource to authenticate and authorize access, without the need for credentials.

Managed Identities Types

There are two types of Azure Managed Identities, with the main difference in how they are created and managed:

S ystem-Assigned Managed Identity

System-Assigned Managed Identities are tied to one specific resource. You can enable them for most Azure services, like virtual machines or automation accounts. It creates a unique identity in your Azure AD, allowing you to set specific permissions for the resource.

The advantage of system-assigned identities is that they are automatically deleted when you delete the resource.

User-Assigned Managed Identity

User-Assigned Managed identities, on the other hand, are standalone Azure resources. They can be associated with one or more Azure services. This provides greater flexibility and control over the management of identities, allowing you to create and manage your own identities and use them for multiple resources.

This also means that user-assigned identities are not deleted when you remove a resource, allowing you to reuse the identity.

Creating an Azure Managed Identity

The principle of creating a managed identity and assigning permissions is for each Azure service pretty much the same. For the examples below, we are going to create a managed identity for an Azure Automation Account. We can then use the identity inside the runbooks to access the different APIs, like MsGraph or Exchange online.

I assume that you already have created an Automation account, if not then read this article first to get started.

Step 1 – Enabling System-Assigned Managed Identity

The first step is to enable the system assigned managed identity. If you open your Azure service, in this case, the Automation Account, you will find in the left menu the item Identity (might need to scroll a bit down). Select this and enable the system-assigned identity and click on save .

system assigned managed identity

Step 2 – Assigning Roles

After you have clicked Save , you will get a confirmation popup. After you confirmed that you want to create a system-assigned identity you will see the Object ID and the option to assign Azure Roles. Important here is that we add the same roles as our current Run-As account (if you are migrating your runbook).

  • In your Azure Automation account, click on Run as accounts
  • Open the Run as account

Azure Runas Account

  • Note the roles that are currently assigned to the account

Roles

  • Go back to Identity
  • Click on Azure Role Assignments

azure system assigned managed identity

We are going to assign the same role(s) to the system-assigned identity as our RunAs account had.

  • Click on Add role assignment
  • Set the scope
  • Add the required Role

Azure role assignments

You can now already connect to Azure resources from within the Azure Runbook for example. The required modules for this are already loaded in new Automation Accounts. However, for existing Automation Accounts you will need to load at least the following modules:

  • Az.ManagedServiceIdentity
  • Az.Accounts
  • Az.Automation

Step 3 – Adding Permissions

The Azure Roles only handle the permissions to other Azure resources, but won’t give the managed identity access to MsGraph or Exchange Online for example. For this, we will need to grant permissions to each of the services.

You can view the assigned permissions in the Azure Portal, but we can’t assign permissions. For this, we will need to use PowerShell and we will need to Object ID of the managed identity.

Let’s first lookup the object ID:

  • Open the Enterprise Applications in the Azure Portal
  • Select All applications
  • Click on the filter Application Type
  • Choose Managed Identities and click on Apply

Enterprise applications

Only the managed identities are now listed. Open the identity that we created earlier and not the object ID:

az role assignment create managed identity

Open PowerShell on your computer, make sure that you have the Microsoft Graph Module installed, and connect to Graph with the following scopes:

We are first going to store the Managed Identity Object ID into a variable because we are going to use it a couple of times in the scripts below:

MsGraph Permissions

We are first going to get the Service Principal for Graph based on the standard App ID:

For Graph, we need to define the scopes that we need permission to. We can then grant permissions for each of the scopes by looking up the app role:

We can now use MgGraph in our Azure Runbook for example. For the runbooks, make sure that you have added at least the following modules to your Azure Automation account:

  • Microsoft.Graph.Authentication
  • Microsoft.Graph.Users

To connect to Graph we first need to connect to Azure so we can obtain an access token.

Note Make sure that you have the following modules loaded in your Automation Account: – Az.ManagedServiceIdentity – Az.Accounts – Az.Automation Otherwise you won’t be able t use the Connect-AzAccount cmdlet

Connecting to Microsoft Graph will become easier with the new V2 module that is coming out. It’s currently in preview, but once released you can simply connect to Microsoft Graph with a managed identity by using the -identity parameter.

SharePoint Online Permissions

Also for SharePoint, we first need to get the Service Principal and define the scopes to which we want to give permission. Use the PowerShell commands below to add the SharePoint permission to your managed identity:

To connect to SharePoint Online inside your runbook you will need to add PnP-Online modules to your Automation Account. Connecting to PnPOnline is done by adding the -ManagedIdentity parameter:

Exchange Online

For Exchange, we often only need to ManageAsApp role. So we can simply add the permission with the following commands:

Besides the permission, we will also need to give our managed identity the Exchange Adminitrator Role. Otherwise, you will get the following error:

We can add the role using MgGraph or using the Azure Portal. For the latter, go to the Azure Active Directory > R oles and administrator . Search for the Exchange Administrator Role and add your managed identity as a member. But we can also use PowerShell of course:

To use the Exchange Online connection in your Azure Runbook, you will need to make sure that you have the latest Exchange Online ( EXO V3 ) module loaded in your automation account. Because this will make connecting to Exchange Online a lot simpler with managed identities:

Verify Permissions

After you added all the permissions it’s always a good idea to verify if they are all added to your managed identity as you expected. We can view the permissions in the Azure Active Directory:

  • Open portal.azure.com and navigate to Enterprise Applications in Azure AD
  • Click on All Applications
  • Change the filter Application type to Managed identies

Azure Enterprise applications

  • Select the managed identity
  • Click on permissions to review them

Managed Identity Permissions

Managed Identity Permissions Script

I have also created a complete script that will set all the permissions for your managed identity. You only need to set the name of your managed identity or you can use the object id of the identity. The script will set all required permissions. You can find the latest version of the script here in my GitHub Repository

Wrapping Up

Managed Identities are great too securely managing access to Azure resources. It provides a secure and easy way to manage access to resources without the need for credentials or complex security policies, which reduces the risk of credential theft or misuse.

While updating your scripts, make sure that you also switch to the latest version of the Exchange Online module, and replace the Azure AD module with the new Microsoft Graph module.

I hope you liked this article, if you have any questions, just drop a comment below.

You may also like the following articles

high volume email

How to use High Volume Email in Microsoft 365

az role assignment create managed identity

How to use Passkeys in Microsoft Authenticator for Microsoft Entra ID

Follow a meeting in Outlook

New Outlook Feature – Follow a Meeting

13 thoughts on “how to use azure managed identity”.

Nice article. I have been trying to get MIs working for a while but haven’t been able to – until I found this! Thank you.

I have created a manged identity and can verify the Microsoft Graph permissions on the MI but still get errors (Object reference not set) wen trying to perform MgGraph cmdlets.

Great article!

I want to send emails in my runbook, but I’m not sure how to do it with Managed Identities. Do you have an example?

Currently, I’m already sending emails through the Graph API, but I’m using an App ID and secret.

Best regards, Stefan

Try the following: – Import the Microsoft.Graph.Users.Actions module in your PowerShell Runbooks – Add the following permission to the Managed Identity Mail.Send (follow step 3 from this article)

You should then be able to send and email as an user using the following method:

Yes! Thanks!

What a great article and script. Thank you Rudy!

Microsoft does not offer much guidance for using the Managed Identity for SharePoint or Exchange Online. Been searching for a while now for a solution to assigning SharePoint PnP permissions to a Managed identity for use in an Automation account, and this was just what I was looking for.

BTW, I had to encase the $managedIdentityName variable on line 11 in single quotes. I was getting a (Invalid filter clause: Syntax error).

Keep up the great work!

You SAVED me. I’ve been working on this problem for over a month, multiple tickets to Microsoft, to get my managed identity permissions. I found your article this morning, and coincidentally, a Senior Escalation Engineer from Azure called me back when I was in the middle of trying it. He said it could be done in the portal.

We ended up doing it your way. The problem was that the identity should be under AD App Registrations and it wasn’t. His fix was to set up a Run As account to start the process but turns out that feature has been depreciated.

After your script, the identity shows up under Enterprise Apps and has all the correct permissions. I just cannot thank you enough.

Not sure why but I am getting following error:

New-MgServicePrincipalAppRoleAssignment : Insufficient privileges to complete the operation.

I connect to graph with following permissions:

“Application.Read.All”,”AppRoleAssignment.ReadWrite.All”,”RoleManagement.ReadWrite.Directory”

Did you select the beta profile?

Yes. This is my whole script:

# Connect to Microsoft Graph Connect-MgGraph -Scopes “Application.Read.All”,”AppRoleAssignment.ReadWrite.All,RoleManagement.ReadWrite.Directory”

# Select beta profile Select-MgProfile Beta

$managedIdentityId = (Get-MgServicePrincipal -Filter “displayName eq ‘xxx'”).id

$graphApp = Get-MgServicePrincipal -Filter “AppId eq ‘00000003-0000-0000-c000-000000000000′”

$graphScopes = @( ‘UserAuthenticationMethod.Read.All’#, ‘Group.ReadWrite.All’, ‘Directory.Read.All’, ‘User.ReadWrite.All’ )

ForEach($scope in $graphScopes){ $appRole = $graphApp.AppRoles | Where-Object {$_.Value -eq $scope} New-MgServicePrincipalAppRoleAssignment -PrincipalId $managedIdentityId -ServicePrincipalId $managedIdentityId -ResourceId $graphApp.Id -AppRoleId $appRole.Id }

Do I actually need a Global Administrator role for this? I have activated Application and Cloud Application Administrator roles.

That is a good one, I tested it with Global admin permissions..

Just confirmed that Privileged Role Administrator role will do the trick.

Very nice! Question: Is there any way to run Connect-MsolService using Azure Managed Identities?

Msol module is being deprecated around June this year, at least that is the plan right now (it has already changed a couple of times)

Leave a Comment Cancel reply

Notify me of followup comments via e-mail. You can also subscribe without commenting.

az role assignment create managed identity

So, about that AdBlocker... Will you consider disabling it?

Yes, ads can be annoying. But they allow me to keep writing content like this. You can also support me by Buying Me a Coffee ☕ or visit the shop to get some Tech-Inspired merchandise | Read more about disabling AdBlockers

Focus on cloud-native and Azure

Authenticate to Azure Resources with Azure Managed Identities

az role assignment create managed identity

In this post, we will take a look at managed identities in general and system-assigned managed identity in particular. Managed identities can be used by your code to authenticate to Azure AD resources from Azure compute resources that support it, like virtual machines and containers.

But first, let’s look at the other option and why you should avoid it if you can: service principals.

Service Principals

If you have code that needs to authenticate to Azure AD-protected resources such as Azure Key Vault, you can always create a service principal. It’s the option that always works. It has some caveats that will be explained further in this post.

The easiest way to create a service principal is with the single Azure CLI command below:

The command results in the following output:

If the service principal needs access to, let’s say, Azure Key Vault, you could use the following command to grant that access:

The next step is to configure your application to use the service principal and its secret to obtain an Azure AD token (or credential) that can be passed to Azure Key Vault to retrieve secrets or keys. That means you need to find a secure way to store the service principal secret with your application, which is something you want to avoid.

In a Python app, you can use the ClientSecretCredential class and pass your Azure tenant id, the service principal appId (or client Id) and the secret. You can then use the secret with a SecretClient like in the snippet below.

Other languages and frameworks have similar libraries to reach the same result. For instance JavaScript and C# .

This is quite easy to do but again, where do you store the service principal’s secret securely?

The command az ad sp create-for-rbac also creates an App Registration (and Enterprise application) in Azure AD:

az role assignment create managed identity

The secret (or password) for our service principal is partly displayed above. As you can see, it expires a year from now (blog post written on January 6th, 2023). You will need to update the secret and your application when that time comes, preferably before that. We all know what expiring secrets and certificates give us: an app that’s not working because we forgot to update the secret or certificate!

💡 Note that one year is the default. You can set the number of years with the --years parameter in az ad sp create-for-rbac .

💡 There will always be cases where managed identities are not supported such as connecting 3rd party systems to Azure. However, it should be clear that whenever managed identity is supported, use it to provide your app with the credentials it needs .

In what follows, we will explain managed identities in general, and system-assigned managed identity in particular. Another blog post will discuss user-assigned managed identity.

Managed Identities Explained

Azure Managed Identities allow you to authenticate to Azure resources without the need to store credentials or secrets in your code or configuration files.

There are two types of Managed Identities:

  • system-assigned
  • user-assigned

System-assigned Managed Identities are tied to a specific Azure resource, such as a virtual machine or Azure Container App. When you enable a system-assigned identity for a resource, Azure creates a corresponding identity in the Azure Active Directory (AD) for that resource, similar to what you have seen above. This identity can be used to authenticate to any service that supports Azure AD authentication. The lifecycle of a system-assigned identity is tied to the lifecycle of the Azure resource. When the resource is deleted, the corresponding identity is also deleted. Via a special token endpoint, your code can request an access token for the resource it wants to access.

User-assigned Managed Identities, on the other hand, are standalone identities that can be associated with one or more Azure resources. This allows you to use the same identity across multiple resources and manage the identity’s lifecycle independently from the resources it is associated with. In your code, you can request an access token via the same special token endpoint. You will have to specify the appId (client Id) of the user-managed identity when you request the token because multiple identities could be assigned to your Azure resource.

In summary, system-assigned Managed Identities are tied to a specific resource and are deleted when the resource is deleted, while user-assigned Managed Identities are standalone identities that can be associated with multiple resources and have a separate lifecycle.

System-assigned managed identity

Virtual machines support system and user-assigned managed identity and make it easy to demonstrate some of the internals.

Let’s create a Linux virtual machine and enable a system-assigned managed identity. You will need an Azure subscription and be logged on with the Azure CLI. I use a Linux virtual machine here to demonstrate how it works with bash. Remember that this also works on Windows VMs and many other Azure resources such as App Services, Container Apps, and more.

Run the code below. Adapt the variables for your environment.

After the creation of the resource group and virtual machine, the portal shows the system assigned managed identity in the virtual machine’s Identity section:

az role assignment create managed identity

We can now run some code on the virtual machine to obtain an Azure AD token for this identity that allows access to a Key Vault. Key Vault is just an example here.

We will first need to create a Key Vault and a secret. After that we will grant the managed identity access to this Key Vault. Run these commands on your own machine, not the virtual machine you just created:

Now we can grant the system assigned managed identity access to Key Vault via Azure RBAC. Let’s look at the identity with the command below:

This returns the information below. Note that principalId was also visible in the portal as Object (principal) ID. Yes, not confusing at all… 🤷‍♂️

Now assign the Key Vault Secrets User role to this identity:

If you check the Key Vault in the portal, in IAM, you should see:

az role assignment create managed identity

Now we can run some code on the VM to obtain an Azure AD token to read the secret from Key Vault. SSH into the virtual machine using its public IP address with ssh azureuser@IPADDRESS . Next, use the commands below:

It might look weird but by sending the curl request to that special IP address on the VM, you actually request an access token to access Key Vault resources (in this case, it could also be another type of resource). There’s more to know about this special IP address and the other services it provides. Check Microsoft Learn for more information.

The result of the curl command is JSON below (nicely formatted with jq):

Note that you did not need any secret to obtain the token. Great!

Now run the following code but first replace <YOUR VAULT NAME> with the short name of your Key Vault:

First, we set the vault URL to the full URL including https:// . Next, we retrieve the full JSON token response but use jq to only grab the access token. The -r option strips the " from the response. Next, we use the Azure Key Vault REST API to read the secret with the access token for authorization. The result should be TOPSECRET ! 😀

Instead of this raw curl code, which is great for understanding how it works under the hood, you can use Microsoft’s identity libraries for many popular languages. For example in Python:

If you are somewhat used to Python, you know you will need to install azure-identity and azure-keyvault-secrets with pip. The DefaultAzureCredential class used in the code automatically works with system managed identity in virtual machines but also other compute such as Azure Container Apps. The capabilities of this class are well explained in the docs: https://learn.microsoft.com/en-us/python/api/overview/azure/identity-readme?view=azure-python . The identity libraries for other languages work similarly.

What about Azure Arc-enabled servers?

Azure Arc-enabled servers also have a managed identity. It is used to update the properties of the Azure Arc resource in the portal. You can grant this identity access to other Azure resources such as Key Vault and then grab the token in a similar way. Similar but not quite identical. The code with curl looks like this (from the docs):

On an Azure Arc-enabled machine that runs on-premises or in other clouds, the special IP address 169.254.169.254 is not available. Instead, the token request is sent to http://localhost:40342 . The call is designed to fail and respond with a Www-Authenticate header that contains the path to a file on the machine (created dynamically). Only specific users and groups on the machine are allowed to read the contents of that file. This step was added for extra security so that not every process can read the contents of this file.

The second command retrieves the contents of the file and uses it for basic authentication purposes in the second curl request. It’s the second curl request that will return the access token.

Note that this works for both Linux and Windows Azure Arc-enabled systems. It is further explained here: https://learn.microsoft.com/en-us/azure/azure-arc/servers/managed-identity-authentication .

In contrast with managed identity on Azure compute, I am not aware of support for Azure Arc in the Microsoft identity libraries. To obtain a token with Python, check the following gist with some sample code: https://gist.github.com/gbaeke/343b14305e468aa433fe90441da0cabd .

The great thing about this is that managed identity can work on servers not in Azure as long if you enable Azure Arc on them! 🎉

In this post, we looked at what managed identities are and zoomed in on system-assigned managed identity. Azure Managed Identities are a secure and convenient way to authenticate to Azure resources without having to store credentials in code or configuration files. Whenever you can, use managed identity instead of service principals. And as you have seen, it even works with compute that’s not in Azure, such as Azure Arc-enabled servers.

Stay tuned for the next post about user-assigned managed identity.

Share this:

Leave a reply cancel reply, discover more from baeke.info.

Subscribe now to keep reading and get access to the full archive.

Type your email…

Continue reading

Navigation Menu

Search code, repositories, users, issues, pull requests..., provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

  • Notifications

Julien Corioland

Senior software engineer & cloud architect @ microsoft.

Twitter

Use Azure managed identities with Azure Kubernetes Services (AKS)

In this blog post, I will explain how you can use the aad-pod-identity project (currently in Beta) to get an Azure managed identity bound to a pod running in your Kubernetes cluster. I will illustrate this with a basic sample that consists in retrieving secrets from an Azure Keyvault in a Go application running in a Kubernetes pod.

Azure Keyvault is a great option to externalize the way you are storing secrets and credentials required by your application outside of the application. But you still need to have a credentials to access Azure Keyvault. This issue can now be solved by using Azure Active Directory Managed Identities .

Disclamer: I’ve chosen to illustrate with Azure Keyvault because this sample is really simple and help to understand how managed identites can help in similar scenarios. If you are looking specifically for a solution to get your Azure Keyvault secrets inside Kubernetes automatically, you may want to have a look to the Kubernetes-Keyvault-FlexVolume project instead (btw, this project uses itself aad-pod-identity, for the record).

Azure managed identities allow your application or service to automatically obtain an OAuth 2.0 token to authenticate to Azure resources, from an endpoint running locally on the virtual machine or service (if it supports Managed Service Identities) where your application is executed. Their are two different types of managed identities in Azure: system-assigned identities, that you can enable directly on the Azure services that support it (a virtual machine or Azure App Service, for example) and user-assigned managed identities that are Azure resources created separately.

When using Azure Kubernetes Service you can enable Managed Service Identity on all the nodes that are running in the cluster and then retrieve OAuth 2.0 tokens, like with any workloads running on a virtual machine in Azure. But by doing that you should know that it means that ALL the pods running on the same node will use the same managed identity, even if they are running in different namespaces, for different teams or different customers (if you are running a multi-tenants application). That makes really difficult to assign roles with fine-grade control in Azure RBAC.

This is where the aad-pod-identity project comes up as it provides:

  • CRDs for AzureIdentity and AzureIdentityBinding which are resources definitions for Azure managed identity and the binding to this identity within the Kubernetes cluster
  • Two infrastructure components, Managed Identity Controller (MIC) and Node Managed Identity (NMI) that will handle the managed identities flow for your applications
Note: read the full design docs and the flow diagram for more details.

In the following, I will assume that you already have an Azure Kubernetes Service cluster running. If not, you can deploy one following this documentation . Please pay attention to the service principal you are using to create the cluster, as you will need its identifier to configure Azure AD Pod Identity. If you are not familiar with AKS and Service principals, read this page first .

Create an Azure Keyvault instance

You can create an Azure Keyvault instance using the following command:

Once the Azure Keyvault instance is ready, you can create a secret:

Now, the goal is to retrieve the value of the secret mySecret from inside a pod running in the Kubernetes cluster, without passing any credentials to the application! But first thing first, let’s setup your AKS cluster!

Configure your Kubernetes cluster to run Azure AD Pod Identity infrastructure

If you want the full details, everything to know is well documented on the project page .

In short, if you are not using RBAC you just have to execute this command to install all you need on your Kubernetes cluster:

If you have RBAC on your cluster, use this:

Create an Azure managed identity

Now that your Kubernetes cluster is ready to provide Azure Active Directory tokens to your applications, you need to create an Azure Managed Identity and assign role to it. This is the identity that you will later bind on your pod running the sample application.

To create a managed identity, you can use this command:

Note: keep the principalId and clientId from the output of this command, you will need it later.

Then you need to make sure the managed identity has Reader role on the Azure KeyVault resource:

And that it can access the secrets:

aad-pod-identity uses the service principal of your Kubernetes cluster to access the Azure managed identity resource and work with it.

This is why you need to give this service principal the rights to use the managed identity created before:

Note: if you did not define a specific service principal when you’ve deployed your AKS cluster, you will find the identifier of the service principal that has been used in ~/.azure/aksServicePrincipal.json

Create Kubernetes AzureIdentity and AzureIdentityBinding

To be able to bind the managed identity you’ve created to the pod that will run the sample application, you need to define two new Kubernetes resources: an AzureIdentity and an AzureIdentityBinding.

azureidentity.yaml:

Note: you will find the clientid field the output of the identity creation command.

azureidentitybinding.yaml:

Note: the value of the Selector property in the YAML definition above will be used to bind the Azure identity to your pod, using labels in its specifications.

Deploy the sample application

To demonstrate this blog post, I’ve written a basic web server in Go that uses the Azure SDK for Go to interact with Azure Keyvault. You can check the code here .

The important part is:

Note: By default, the NewAuthorizerFromEnvironment retrieve the authorization token automatically from the local managed identity endpoint (the aad-pod-identity server). You can read more details about how the Azure Authorization Go SDK works here .

The YAML definition below defines a deployment to run the sample application using a pre-built Docker image. You can build your own from the sample GitHub repository if you prefer.

keyvaultsample.yaml:

As you can see in the YAML file above, the Selector that has been defined earlier in the AzureIdentityBinding is used with the aadpodidbinding label. This is where the binding between the Azure identity and the pod is done.

Note: pay attention to replace the environment variable for the containers with the appropriate values. You can find the secret version using az keyvault secret show (last part of its id).

Deploy the sample application:

Once the pod has started and a public IP address has been assigned to your service, you can just browse http://{PUBLIC_IP}/keyvault and you should see the value of the secret stored in your Azure Keyvault:

keyvault-result.png

Using Azure Managed identities and aad-pod-identity you’ve been able to give access rights to a given pod to Azure Keyvault resource, without having to pass credentials in a config file or any environment variable, and this is really awesome!

Hope this helps!

Any question about this post? Feel free to drop a comment below or contact me on Twitter @jcorioland

Using Managed Identity with Kubernetes in Azure

If your application is running on a Kubernetes cluster in Azure (AKS, ACS or ACS Engine), then it is likely that you will need to access other Azure resources from your pods that are secured with Azure AD. These operations could include retrieving secrets from Key Vault, files from Blob storage or just interacting with other applications or API’s that use Azure AD as their identity provider. To be able to do this your application needs to be able to provide an identity to access these resources securely.

Up until recently, this has required the use of an Azure Service Principal. A Service Principal is essentially an application created in Azure AD with either a password or a certificate. Using a Service Principal can be a pain as it means that you have to either pass this password to your application or make sure the certificate is loaded. It also means that it is your responsibility to keep this identity secure, roll the keys on a regular basis and so on.

Microsoft’s solution to this is Managed Identity. Managed Identity allows you to assign an Azure AD identity to your virtual machine, web application, function app etc. This identity is then used by your application to access resources. The management of the identity is taken care of by Microsoft; they are the ones rolling the keys and keeping the credentials secure. Most importantly you don’t need to worry about passing in passwords or certificates to your application, you assign the identity to the Azure object, and that is it.

While this works great for VMs and Web apps, it didn’t work with things like AKS in Azure. When you deploy an AKS cluster, the object you see in Azure is the cluster. However, we don’t want to assign identities to the cluster; we want to assign them to individual pods and probably have different identities for different pods. Out of the box, this was not possible, but now with a new open source project called “Pod Identity” we can now achieve this and simplify our application identity workload significantly.

Demo Scenario

For the rest of this article, we are going to look at a simple scenario where we have a pod that needs access to some secrets from Key Vault. We are going to revisit a previous article where we used the Kubernetes Key Vault Flex Volume project to mount Key Vault secrets as volumes on our pods.

In the previous demo, we used a service principal to grant access to our Key Vault resource. This worked, but it meant that we needed to maintain a Kubernetes secret to store our Service Principal password, which needed updating any time this changed or expired. In this demo, we will replace the Service Principal with Managed Identity so that we can let Microsoft take care of managing the lifecycle of that identity.

If you want to follow along with this demo, you may want to start by deploying the Service Principal example in the previous article , so you can then convert it to using Managed Identity.

Deploying Pod Identity

To be able to make use of Pod Identity we need to deploy some resource into our Kubernetes cluster.

Managed Identity Control (MIC)

The Managed Identity Controller is a single pod that watches your running and checks whether they are tagged to have identities assigned to them. If these pods are tagged appropriately, it maintains an identity map connectivity pods to identities

Node Managed Identity (NMI)

The NMI pods are in a DaemonSet to ensure there is one running on every node. NMI is the resource that is used when your pods look to use their identity. The applications running in the pod make a call to get their identity in the same way you would do so for an app running on a VM, web app or function, using the same libraries you are used to using. When this happens, a call is made to the Azure instance metadata URL. This URL normally does not exist inside a pod, but with a pod, identity deployed these requests are routed to the NMI instance on the node. NMI then talks to the MIC to get the identity mapping and then makes a request to Azure to retrieve the actual identity.

Deploying the resource required for Pod Identity can be done with a single Kubernetes command. This command pulls the configuration from Github , so be sure to review this file to ensure you are comfortable with it. If you prefer you can download a copy and then run from this locally. Note that this deployment puts these in the default namespace, if you want them somewhere different you need to amend this. We’ll go ahead and deploy using this command:

You should get a success response that creates the required custom resources, pods and daemonset.

You can check they are all running using

Identity Creation

Now we have the required resource running in our cluster we need to create the managed identity we want to use. There are two types of Managed Identity available in Azure:

  • System Assigned - These identities are enabled directly on the Azure object you want to provide an identity. They are bound to the lifecycle of this resource and cannot be used by any other resource
  • User Assigned identity - These identities are created as a standalone object and can be assigned to one or more Azure resource. Their lifecycle is not bound to these objects.

We will be using user assigned identities, as a system assigned identities do not work in this scenario. We need to be able to assign identities to pods, which are not native Azure resources.

Create User Assigned Identity

The first thing we need to do is create the identity. We can do this through the portal, CLI or Powershell.

  • Click the create resource button and search for “Managed Identity.”
  • Click create
  • Enter a name for the identity and select a subscription, resource group and region for this to be in

**PowerShell

Get Identity Details

Once you have created your identity we need to note down a couple of pieces of information:

In the portal, this can be found by clicking on the identity and looking at the overview. It is labelled as “Client ID”.

In the CLI or PowerShell, when you created the identity, it should have outputted some information on the identity, one of which is the Client ID.

Resource ID

We also need the full resource ID of the identity. In the portal, you can find this by clicking on the “Properties” option. The ID should be listed on the page that opens.

In PowerShell or CLI it is again listed in the output from the create command.

Grant Permissions to Resources

Now we have an identity created we need to go ahead and grant it permissions on whatever resources we want it to access. In this case, we are looking to grant the identity the ability to read secrets from Key Vault. Using the “Client ID” you noted down in the previous step you should:

  • Grant this identity read access on the Key Vault object using RBAC permissions
  • Grant this identity the ability to read the secrets in the vault using the vault permissions. This is done by selecting the vault in the portal and going to “Access Policies”. The only rights required for this demo are get and list on secrets.

Grant Cluster Permission to Identity

For the cluster to be able to read and assign this identity to a pod we also need to grant the service principal that your AKS (or ACS) cluster is running as permissions on this identity. To achieve this, you need to know the Client ID of this service principal. If you are using AKS the easiest way to achieve this is to run this command in the CLI:

This command should output information about the cluster, including the Client ID.

Now we have the client ID we can grant the “Managed Identity Operator” role to it on our Identity.

  • Locate the Managed Identity you created in the portal and select it
  • Go to “Access Control (IAM)
  • Click “Role Assignments”
  • Click “Add Role Assignment”
  • In the “Role” drop-down select “Managed Identity Operator”
  • In the search box enter the Client ID of the AKS cluster Service Principal

Create Identity and Binding

Now we have everything set up we need to create two custom objects in our Kubernetes cluster:

  • Pod identity - this is the actual identity object that will be used by the pods
  • Pod Identity Binging - This maps pods to the identity they should use

Pod Identity

To create the identity, we create a Kubernetes YAML file that defines the resource ID and client ID of the identity we wish to create. We give this identity a name, this can be anything, but it is what we will use to reference the identity in the binding.

Save this file somewhere locally then deploy using this command:

Pod Identity Binding

Now we have created an identity object in Kubernetes; we need to determine what pods we want to bind the identity to. We are not going to bind it to a specific pod here directly but instead, bind to a label. This way any time a pod is created with that label it will get the ID assigned automatically. The name of the label will always be “aadpodidbinding”, but the value is what we define in this binding. When the value of aadpodidbinding matches what we define here, the role will be assigned.

We use the name of the identity we created in the previous step, then define a label value of “demo-kv-access”. The label value can be anything you want, so long as you use the same value on your pods.

A Note on Security

Now that we have created Identity and Binding objects in the cluster it is possible for anyone who has access to these to be able to assign them to their pods and use them to access resources. Because of this, it is essential to make sure that these identities are scoped appropriately not to be a security risk:

  • Access to use the Kubernetes identity objects should be locked down using Kubernetes RBAC to only users who are allowed to make use of them
  • The Managed Identity object in Azure should only be granted rights to do what it needs to do and nothing more

Deploying Pods

We now have an identity created in Kubernetes and a binding ready to attach to any pods that have a specific label. All we need to do now is deploy a pod that is ready to use this identity to access key vault. This pod needs to be running an application or service that can make use of Managed Identity once the binding is attached.

In our example, we are using the Keyvault Flex volume service which will use this binding to talk to Key Vault and retrieve secrets. We’re going to make 2 changes to the YAML file to deploy our pod:

  • Add a label called “aadpodidbinding” with a value of “demo-kv-access” to attach the binding
  • Amend the Flex Volume parameters to change to using Managed Identity and remove the secret reference to the service principal.

Our YAML file now looks like this:

Once the Pod has started, we can exec onto it and confirm that we now have a mount point at /secret1

If we move into this folder, we should see a file with the name of the secret we mounted, in this case, “appsecret1” and if we output the value of that file, we see our secret value.

The Pod Identity project provides a relatively simple way to switch from using Service Principals inside your pods to using Managed Identity. Managed Identity removes many headaches around providing secure access to identities as well as dealing with things like key rotation and renewals.

By utilising User Assigned identities and Kubernetes tags, it offers a flexible way to set up your identities in advance and assign them to pods as required.

Image Attribution

Fingerprinted flickr photo by Jeremy Brooks shared under a Creative Commons (BY-NC) license

az role assignment create managed identity

  • Adding or removing role assignments using Azure Portal

Go back to AZ-304 Tutorials

In this article you will learn about assigning roles using Azure portal and the process of adding and removing role assignments. 

However, Azure’s role-based access control (RBAC) refers to the authorization system for managing access to Azure resources. And, to grant access, you assign roles to users, groups, service principals, or managed identities at a particular scope. 

Prerequisites

For adding or removing role assignments, you must have:

  • Firstly, Microsoft.Authorization/roleAssignments/write 
  • Secondly, Microsoft.Authorization/roleAssignments/delete permissions, such as User Access Administrator or Owner

Access control (IAM)

Access control (IAM) is the page that is for assigning roles to grant access to Azure resources. It’s also known as identity and access management and appears in several locations in the Azure portal. There are questions for assigning roles to help in understanding about the Access control (IAM) page.

  • Who needs access? This refers to a user, group, service principal, or managed identity. 
  • What role do they need? Permissions are grouped together into roles, so you can select from a list of several built-in roles orcan use custom roles.
  • Where do they need access? This refers to the set of resources that the access applies to. However, “where” can be a management group, subscription, resource group, or a single resource such as a storage account.

Adding a role assignment

  • Firstly, in the Azure portal, click All services and then select the scope that you want to grant access to. 
  • Secondly, click the specific resource for that scope.
  • Then, Click Access control (IAM).
  • Fourthly, click the Role assignments tab for viewing the role assignments at this scope.
  • After that, click Add > Add role assignment. However, if you don’t have permissions to assign roles, the Add role assignment option will be disabled.

adding role assignments

  • Then, in the Role drop-down list, select a role such as Virtual Machine Contributor.
  • There in the Select list, select a user, group, service principal, or managed identity. And, if you don’t see the security principal in the list, you can type in the Select box to search the directory for display names, email addresses, and object identifiers.
  • Lastly, click Save to assign the role.

Assigning a user as an administrator of a subscription

For giving users the role of an administrator of an Azure subscription, first assign them the Owner role at the subscription scope. As the Owner role gives the user full access to all resources in the subscription, including the permission to grant access to others. However, these steps are the same as any other role assignment.

  • Firstly, in the Azure portal, click All services and then Subscriptions.
  • Then, click the subscription where you want to grant access.
  • Thirdly, click Access control (IAM).
  • After that, click the Role assignments tab to view the role assignments for this subscription.
  • Then, click Add > Add role assignment. However, if you don’t have permissions to assign roles, the Add role assignment option will be disabled.
  • And, in the Role drop-down list, select the Owner role.
  • Then, in the Select list, select a user.

AZ-304 Practice tests

Adding a role assignment for a managed identity

For adding role assignments for a managed identity use the Access control (IAM) page. However, when you use the Access control (IAM) page, you start with the scope and then select the managed identity and role. In this section, you will learn about an alternate way to add role assignments for a managed identity. Using these steps, you start with the managed identity and then select the scope and role.

System-assigned managed identity

  • Use these steps for assigning a role to a system-assigned managed identity by starting with the managed identity.
  • Firstly, in the Azure portal, open a system-assigned managed identity. Then, in the left menu, click Identity.

system assign role assignments

  • After that, under Permissions, click Azure role assignments. However, if roles are already assigned to the selected system-assigned managed identity then you will see the list of role assignments.
  • For changing the subscription, click the Subscription list. Then, click Add role assignment.
  • Then, use the drop-down lists to select the set of resources that the role assignment applies to such as Subscription, Resource group, or resource. And, if you don’t have role assignment write permissions for the selected scope, an inline message will be displayed.
  • After that, in the Role drop-down list, select a role such as Virtual Machine Contributor.

User-assigned managed identity

  • Use these steps for assigning a role to a user-assigned managed identity by starting with the managed identity.
  • Firstly, in the Azure portal, open a user-assigned managed identity. Then, in the left menu, click Identity.
  • After that, under Permissions, click Azure role assignments. However, if roles are already assigned to the selected user-assigned managed identity then you will see the list of role assignments.

user assign role assignments

Removing a role assignment

In Azure RBAC, for removing access from an Azure resource, you first remove a role assignment. Use these steps to remove a role assignment.

  • Firstly, Open Access control (IAM) at a scope, such as management group, subscription, resource group, or resource, where you want to remove access.
  • Then, click the Role assignments tab to view all the role assignments for this subscription.
  • After that, in the list of role assignments, add a checkmark next to the security principal with the role assignment you want to remove.
  • Then, Click Remove.
  • Lastly, in the remove role assignment message that appears, click Yes.

However, if you see a message that inherited role assignments cannot be removed, then you are trying to remove a role assignment at a child scope. So, you should open Access control (IAM) at the scope where the role was assigned and try again. 

AZ-304 online course

Reference: Microsoft Documentation

Prepare for Assured Success

Generating Sas Tokens using Azure Managed Identity (User Delegation)

az role assignment create managed identity

Fullstack C# Developer | Azure Cloud Engineer | DevOps & SRE Advocate

More posts by Adam White .

Adam White

It’s possible with Azure Blob Storage to generate a Shared Access Signature (SAS) which you can allow any third party limited access to a blob. This access can be limited in time and actions such as Read, Write, or more to a specific file held within blob storage. You can also provide access to the entire blob container if you wish.

There is a new way to generate in the new Blob Storage SDK , and the big thing here is the ability to generate those SAS tokens without a storage account key.

User Delegation SAS

The typical way to generate a SAS token in code requires the storage account key. This assumes you have the storage account key, and there are scenarios where you just won’t have access to that. This is the situation I found myself in. You’ll find many answers online, but none of them lead you down the right path if you are as unlucky as I was. If you need to use “Managed Identity” to control access to your storage accounts in code, which is something I highly recommend wherever possible as this is a security best practice. In this scenario, you won’t have a storage account key, so you’ll need to find another way to generate the shared access signatures.

To do that, we need to use an approach called “user delegation” SAS . By using a user delegation SAS, we can sign the signature with the Azure Ad credentials instead of the storage account key.

I’ll show you below exactly what code you need to generate the user delegation SAS URI with the .Net storage SDK; I’ll also cover a few gotchas that caught me out and how to test this within visual studio locally.

Generating a User Delegation SAS

Connecting to Azure Storage using Azure Active Directory Credentials is made incredibly easy thanks to the DefaultAzureCredential . This helper class tries a variety of different techniques to source the credentials required to access a storage account.

Firstly it checks for environment variables. If these aren’t present, it attempts to use a managed identity (this is what you want in production!). Should that fail, it has a range of fallback options that it will try, and these are great for local development. It can use the credentials you logged into visual studio, Visual Studio (VS) Code, Azure CLI with. So in a range of development environments, this will work. I’ll show you below how to set the managed identity you want to use in Visual Studio, which can be the one you’ve logged in with or something else entirely.

Here’s how you would use the DefaultAzureCredential to create a BlobServiceClient :

With that, you’ve successfully created a blob service client using managed identity. You can test this by uploading a file into the storage account.

All being well, you should have a file in your blob storage container. Which proves that managed identity is working.

Now let’s generate a shared access signature. The first start is to create a user delegation key .

The duration of this SAS token can only be set to a maximum of 7 days Otherwise, you’ll get an error if you request a longer duration. You also get an error if you mess up the dates, I sent in the same start and end date of “Now” due to a config issue. When that happens, you’ll see an error with an HTTP status code of 400 (bad request) with the error being "The value for one of the XML nodes is not in the correct format," which isn’t the most helpful error. If you get this, check the values, make sure they make sense! Asking for a SAS token that immediately expires isn’t sensible!

To get the user delegation key is this simple:

We can use the user delegation key with the BlobSasBuilder and BlobUriBuilder helpers to generate the SAS token URI. You can access the file or provide a token allowing someone write access to upload a file to your container. In the example below, I’m asking for a SAS token that’s valid for 7 days for a specific file. Do not that the SAS token doesn’t need to have the same lifetime as the user delegation key, but it cannot be longer If you attempt to create a SAS token URI with a lifespan that’s longer than the lifespan of the user delegation key, you will get a 403 error response.

The sasUri can be used to download the file until the SAS token expires or the user delegation key expires. Whichever happens first will invalidate this SAS token.

To test the SAS token URI, here’s a simple bit of code that will download the file’s contents.

Testing Locally

If you attempt to test this locally or use a service in Azure, you may find that this doesn’t work. There’s a reason for that. You need to give the identity accessing the storage account some RBAC permissions.

  • Storage Account Contributor
  • Storage Blob Data Contributor

This may surprise you, as being the owner of the storage account isn’t sufficient.

You can test this in Azure CLI and even see if you can tighten the permissions by attempting the following.

If you haven’t assigned the right RBAC permissions within the storage account, the above will fail. Head on into Azure, go to your storage account, then Access Control (IAM), then role assignments to set the permissions. Take a look at this article to see the various ways to grant the relevant RBAC permissions.

I personally do this within the CLI myself, and it’s this simple. Firstly look you our Azure AD object ID using our email address:

Now we need the id of the storage account to set the RBAC permissions on:

This will return a string that contains the subscriptionId, resource group, and the storage account name. For example: /subscriptions/770476dd-69ac-465d-96cc-gh12bc676chk/resourceGroups/badger-rg/providers/Microsoft.Storage/storageAccounts/ducksandbadgersstore

We can add the RBAC permissions Storage Blob Data Contributor role scoped to this storage account container with this information.

If this still doesn’t work for you, there is a gotcha to get around when working within visual studio. The DefaultAzureCredential may not select the correct Azure AD tenant id. There are two ways to get around this. Firstly you can set it in code like this:

Setting Visual Studio’s Managed Identity

Secondly, you can go into Visual Studio, go to Tools -> Options. Then Azure Service Authentication. It’s here where you can select an account. Or even add another account. I mentioned above about using an account that isn’t specifically the one you are logged into Visual Studio with. This is the settings section you would use to set another managed identity to use.

Managed Identities can sound a bit scary to those who haven’t used them, but actually, they are incredibly simple to use and end up making code much simpler and more secure. In the past, I’ve had to manage load balancing of storage queues and passing in storage account keys by using Azure Key Vault. It’s just a complication you can get rid of.

On top of that, Managed Identities are a much more secure way for you to access your cloud resources, giving a fine grained control as to what can be done to those resources, an account key gives complete access, RBAC gives you the ability to use the principle of least privilege. Sure, when it comes to generating SAS tokens, there is an additional hoop to jump through, but it’s still less of a hassle than setting up KeyVault and passing the secret into the code.

Hopefully, the steps above have shown you how to set the correct RBAC roles to your local user or managed identity. The C# example code is enough to help you generate that user delegation key, which is the key to SAS token generation with managed identity.

You are limited to a lifetime of 7 days with this approach, but that’s a good thing. The longer something is open, the more likely it will be attacked. It’s best practice to only have your SAS tokens alive for the shortest amount of time necessary.

Buy Me A Coffee

Configure Azure Functions to use Identity Based Connections

  • Azure Functions

Whenever you use an Azure Functions trigger or binding, you need to give Azure Functions the ability to connect to the target service. For example, if you want to bind to blob storage, you'd typically have a connection string to a Storage Account in your application settings (and there's one there by default called AzureWebJobsStorage which can be convenient to use for small and simple Azure Functions applications). And similarly for services like Azure Service Bus, Azure Cosmos DB, or Azure SQL Database, you'd put a connection string in your Application Settings.

However, from a security perspective, many people are trying to move away from connection strings. That's because that if the connection string was leaked, then whoever had it would be able to use it to gain access to the data in the service.

A better approach is to use "identity-based connections" . With this approach, your Azure Functions application has a "managed identity", and that identity is granted access to the services that you are binding to. This means that there are no secrets to be leaked in your Function App.

It is unfortunately, a little bit more difficult to set up, so in this article, I want to guide you through the steps I went through to create an Azure Functions app with it. I'll be using the Azure CLI and PowerShell for most of it. The whole project is available here on GitHub , including the powershell for deployment.

Step 1 - Create the Azure Functions App

First of all, you need to create a Function App, which requires you to first log in to the Azure CLI, select a subscription to use, create a resource group and a storage account to use.

Creating the Azure Function app itself is fairly straightforward. The key for our purposes is that the --assign-identity flag ensures that our function app has a managed identity.

Step 2 - Grant the Function App's managed identity access to the storage account

The exact roles that you need to grant your managed identity depend on exactly what you are doing, and whether you are using the built-in AzureWebJobsStorage account which Azure Functions uses for its own purposes, or your own storage account. In my demo, I am using AzureWebJobsStorage and I also want to be able to use Durable Functions which means we need privileges to use queues and tables as well as blobs.

The official Microsoft Learn documentation has a helpful table that you can use to decide what roles you need. Obviously, the "principle of least privilege" should be applied and so you should try to avoid granting more roles than are necessary.

For the scope, we get the resource identifier of the storage account with az storage account show and then apply the roles with calls to az role assignment create .

Step 3 - Get rid of the connection string

By default, our Function App has been set up with a connection string called AzureWebJobsStorage in its application settings. We can delete that, and replace it with the specially named AzureWebJobsStorage__accountName setting, which points only to the storage account name. This essentially tells Azure Functions that we are using identity-based connections. Note that in some circumstances there may be additional settings you need to add which are described here although for our use case, this single setting is all that is needed.

Now at this point, we've actually already done everything necessary for our Functions App to use Azure Storage triggers and bindings to the AzureWebJobsStorage connection, without needing a connection string. And if you wanted to bind to a different storage account, then you'd just go through exactly the same steps to grant permissions to that storage account, and add another application setting with the __accountName suffix.

However, we'd also like to use this same identity-based connection technique for Azure Service Bus, so let's do that next.

Step 4 - Create Service Bus Namespace and queue

Obviously we need an Azure Service Bus namespace, so I'm using az servicebus namespace create for that. And I've also chosen to create the queue up front with az servicebus queue create .

Step 5 - Grant the managed identity access to the Service Bus

And now we need to grant the Azure Function app's managed identity access to the Service Bus namespace. Again, the scope is just the resource id of the Service Bus namespace. And the roles I'm granting it are "Azure Service Bus Data Sender" and "Azure Service Bus Data Receiver" to allow posting messages to queues and receiving them.

Step 6 - Set the Service Bus connection up in Azure Functions App Settings

Finally, we need to add an Application Setting that lets Azure Functions know which Service Bus namespace we're connecting to. Instead of creating an Application Setting called ServiceBusConnection with the connection string, we create one called ServiceBusConnection__fullyQualifiedNamespace which just has the domain name of the Service Bus namespace as its value.

Step 7 - Using the connections in function code

The great thing about these identity-based connections is that they require no code changes at all, compared to code that used connection strings directly.

For example, this storage queue-triggered function will work if there is an Application Setting called AzureWebJobsStorage with a connection string, but it also works for our application which only has a AzureWebJobsStorage__accountName setting.

And the same applies for Service Bus triggered functions. This function just refers to the ServiceBusConnection setting, and Azure Functions knows it is an identity-based connection because of the ServiceBusConnection__fullyQualifiedNamespace Application Setting.

The full code for these sample functions can be found in the example demo application .

Step 8 - Deploy and Testing

If you want to try this out with the demo app, then you can use the func azure functionapp publish command to build the code and publish it to Azure. And the az functionapp keys list command enables you to access the function code to grant you permission to call the HTTP-triggered endpoints that can be used to test the functionality.

In summary, Azure Functions offers support for identity-based connections for the majority of bindings , and for most production applications, I recommend that you consider this a security best-practice and configure it by default. The only complex thing is making sure that you assign the right roles to the right identity, with the right scope, and I hope my instructions above have made that a bit easier for you.

IMAGES

  1. Assign Azure roles to a managed identity (Preview)

    az role assignment create managed identity

  2. Exam AZ-500: Create and manage a managed identity for Azure resources

    az role assignment create managed identity

  3. Create an Azure storage account with managed identity

    az role assignment create managed identity

  4. What is Azure role-based access control (Azure RBAC)?

    az role assignment create managed identity

  5. Assign Azure resource roles in Privileged Identity Management

    az role assignment create managed identity

  6. Assign Azure roles to a managed identity (Preview)

    az role assignment create managed identity

VIDEO

  1. Colorado woman finishes astronaut training

  2. EDUBED-109(B) Unit-1 Guidance Programme, Concept, Principles, Need, Scope, Significance, Types

  3. DO NOT MORTGAGE THE PLANS OF GOD || MORNING WATCH PROPHETIC PRAYERS WITH PROPHETESS AKUWAA

  4. This Is Unbelievable! Police Informant Turned Serial Killer

  5. final assignment from LC class "favorite motivating figure"

  6. AC S05 Week 05 Speaking Task Assignment Today, things are different

COMMENTS

  1. Assign Azure roles using Azure CLI

    Step 1: Determine who needs access. You can assign a role to a user, group, service principal, or managed identity. To assign a role, you might need to specify the unique ID of the object. The ID has the format: 11111111-1111-1111-1111-111111111111. You can get the ID using the Azure portal or Azure CLI. User.

  2. How to use Azure Managed Identity

    Step 1 - Enabling System-Assigned Managed Identity. The first step is to enable the system assigned managed identity. If you open your Azure service, in this case, the Automation Account, you will find in the left menu the item Identity (might need to scroll a bit down). Select this and enable the system-assigned identity and click on save.

  3. Using User-assigned Managed Identities in Azure

    Previous guides have covered using system assigned managed identities with Azure Stroage Blobs and using system assigned managed Identity with Azure SQL Database.However, Azure imposes a limit of 2,000 role assignments per Azure subscription. If you have a lot of Azure resources, each with their own individual system-assigned identity and granular role assignments, you can quickly run into ...

  4. Setup managed identities for workload federation in Azure ...

    This post will show how to create a user assigned managed identity, assign roles to it and configure it for workload identity federation using the Azure CLI in PowerShell. ... az role assignment ...

  5. Authenticate to Azure Resources with Azure Managed Identities

    System-assigned managed identity. Virtual machines support system and user-assigned managed identity and make it easy to demonstrate some of the internals. Let's create a Linux virtual machine and enable a system-assigned managed identity. You will need an Azure subscription and be logged on with the Azure CLI.

  6. How to add existing User Assigned Managed Identity to new Resource

    az role assignment create --resource-group '<resourcegroupname>' --role 'Contributor' --assignee '<service principal objectId>' Check in the portal: Besides, you could find the ObjectId in Azure Active Directory -> Enterprise applications(All applications), just search for your User Assigned Managed Identity name.

  7. Creating a Custom Role for an Azure Managed Identity

    Azurerm resource block to create a custom role for a managed identity. As before, this is quite straightforward, but I found that I needed to have an explicit "depends_on" statement in my ...

  8. role-assignments-cli.md

    If you create a new service principal and immediately try to assign a role to that service principal, that role assignment can fail in some cases. For example, if you use a script to create a new managed identity and then try to assign a role to that service principal, the role assignment might fail.

  9. Use Azure managed identities with Azure Kubernetes Services (AKS)

    To create a managed identity, you can use this command: az identity create -n keyvaultsampleidentity -g keyvault-aad-pod-identity-rg. Note: keep the principalId and clientId from the output of this command, you will need it later. Then you need to make sure the managed identity has Reader role on the Azure KeyVault resource:

  10. Using Managed Identity with Kubernetes in Azure

    Portal. Locate the Managed Identity you created in the portal and select it. Go to "Access Control (IAM) Click "Role Assignments". Click "Add Role Assignment". In the "Role" drop-down select "Managed Identity Operator". In the search box enter the Client ID of the AKS cluster Service Principal. Click Save. CLI.

  11. Adding or removing role assignments using Azure Portal

    Adding a role assignment. Firstly, in the Azure portal, click All services and then select the scope that you want to grant access to. Secondly, click the specific resource for that scope. Then, Click Access control (IAM). Fourthly, click the Role assignments tab for viewing the role assignments at this scope.

  12. Generating Sas Tokens using Azure Managed Identity (User Delegation)

    To get the user delegation key is this simple: var userDelegationKey = await blobServiceClient. .GetUserDelegationKeyAsync(DateTimeOffset.UtcNow, DateTimeOffset.UtcNow.AddDays(7)); We can use the user delegation key with the BlobSasBuilder and BlobUriBuilder helpers to generate the SAS token URI.

  13. How to assign correct roles on Service Bus entities to Azure functions

    The Azure functions deployment is running under a managed identity. And as we want to deploy everything automatically, using Azure Bicep, I want to automatically give the correct role assignment on the Service Bus namespace (or entities) for that managed identity, in an Azure Bicep file. But I don't seem to find out how to do that.

  14. Configure Azure Functions to use Identity Based Connections

    Whenever you use an Azure Functions trigger or binding, you need to give Azure Functions the ability to connect to the target service. For example, if you want to bind to blob storage, you'd typically have a connection string to a Storage Account in your application settings (and there's one there by default called AzureWebJobsStorage which can be convenient to use for small and simple Azure ...

  15. Managed Identity to Connect AKS with Azure SQL

    Comparing the official documentation about Azure AD Pod Identity for AKS versus the role assignment you mentioned you did, the following role assignment to the cluster system assigned managed identity may be missed: "Virtual Machine Contributor". Without the proper role assignments, your Azure cluster will not have the correct permission to assign and un-assign identities from the underlying ...