Getting DefaultAzureCredentials to Work on Linux-Based Operating Systems
Using Azure Active Directory Service Principals
In this article, we will guide you through setting up DefaultAzureCredentials on Linux-based operating systems by using Azure Active Directory Service Principals. This process includes creating a Service Principal in the Azure Portal and configuring your environment to automatically load the necessary credentials when starting your IDE.
Preamble
Before we dive into the code, let's first talk about what DefaultAzureCredentials are and why you might want to use them. DefaultAzureCredentials is a type of credentials object in the Azure SDK for .NET that automatically determines the correct set of credentials to use based on the environment in which the application is running. This means that you can write code that works in a variety of scenarios, whether you're running your application locally, in a container, or in a cloud environment like Azure.
Using DefaultAzureCredentials is a best practice for securing your Azure resources, as it allows you to use a single codebase that works across multiple environments, without exposing your credentials in your code or configuration files.
Code example:
Here's an example of how to use DefaultAzureCredentials in C# to authenticate with Azure and get a list of virtual machines in a resource group:
using Azure.Identity;
using Azure.ResourceManager.Compute;
using Azure.ResourceManager.Compute.Models;
// Replace <subscription-id>, <resource-group-name>, and <region> with your own values
string subscriptionId = "<subscription-id>";
string resourceGroupName = "<resource-group-name>";
string region = "<region>";
var credential = new DefaultAzureCredential();
var vmClient = new VirtualMachinesClient(subscriptionId, credential);
vmClient.BaseUri = new Uri($"https://management.{region}.azure.com/");
var vms = vmClient.VirtualMachines.ListByResourceGroupAsync(resourceGroupName);
await foreach (VirtualMachine vm in vms)
{
Console.WriteLine(vm.Name);
}
In this example, we first create a new instance of the DefaultAzureCredential class, which will automatically determine the correct set of credentials to use based on the environment in which the application is running. We then create a new instance of the VirtualMachinesClient class, passing in our subscription ID and the credential object. Finally, we use the ListByResourceGroupAsync method to get a list of all virtual machines in the specified resource group, and print out their names to the console.
Using DefaultAzureCredentials in this way allows you to write code that is secure, portable, and easy to maintain, while still providing access to all of the powerful features of the Azure SDK for .NET.
Step 1: Create a Service Principal in the Azure Portal
Log in to the Azure Portal.
Click on Azure Active Directory from the left-hand menu.
In the Azure Active Directory blade, click on App registrations.
Click on New registration at the top of the App registrations blade.
Provide a name for your new application, and choose a supported account type. Leave the Redirect URI field empty as it's not required for our purposes.
Click on Register to create the new application.
After the application is created, you will be redirected to the Overview page. Take note of the Application (client) ID and Directory (tenant) ID as you'll need these values later.
Click on Certificates & secrets from the left-hand menu.
In the Certificates & secrets blade, click on New client secret.
Provide a description for the client secret, choose an expiration period, and click Add.
Copy the generated client secret value, as you won't be able to see it again. Save this value securely as you'll need it later.
Step 2: Create and Configure Scripts
Create an azure-service-principal.json
file in your $HOME
directory with the following content:
{
"clientId": "<your_client_id>",
"tenantId": "<your_tenant_id>",
"clientSecret": "<your_client_secret>"
}
Replace <your_client_id>
, <your_tenant_id>
, and <your_client_secret>
with the values obtained from the Azure Portal.
Create a script called load_azure_credentials.sh
in your $HOME
directory with the following content:
#!/bin/bash
# Read Azure credentials from JSON file
AZURE_CREDENTIALS_FILE_PATH="/Users/imbak/azure-service-principle.json";
if [ -f "$AZURE_CREDENTIALS_FILE_PATH" ]; then
AZURE_CLIENT_ID=$(jq -r '.clientId' "$AZURE_CREDENTIALS_FILE_PATH")
AZURE_TENANT_ID=$(jq -r '.tenantId' "$AZURE_CREDENTIALS_FILE_PATH")
AZURE_CLIENT_SECRET=$(jq -r '.clientSecret' "$AZURE_CREDENTIALS_FILE_PATH")
# Export environment variables
export AZURE_CLIENT_ID
export AZURE_TENANT_ID
export AZURE_CLIENT_SECRET
else
echo "Azure credentials file not found at $AZURE_CREDENTIALS_FILE_PATH"
fi
echo "Azure Credentials Loaded from $AZURE_CREDENTIALS_FILE_PATH";
Make the script executable:
chmod +x $HOME/load_azure_credentials.sh
Step 3: Add Script to Bash Profile
To execute this script as part of your shell profile, add the following line to your profile file (e.g., ~/.bashrc
or ~/.zshrc
):
source $HOME/load_azure_credentials.sh
Step 4: Restart Your Terminal
Restart your terminal to apply the changes. If everything is set up correctly, the environment variables AZURE_CLIENT_ID
, AZURE_TENANT_ID
, and AZURE_CLIENT_SECRET
will all be populated in every terminal that uses your default shell.
**
Step 5: Add Service Principal to Azure Key Vault (Additional Step)**
If you plan on using Azure Key Vault to store your secrets, you'll need to grant your Service Principal access to the Key Vault.
Open the Azure Portal and navigate to your Key Vault.
Click on the Access policies tab in the left-hand menu.
Click on the Add Access Policy button to add a new access policy.
In the Add access policy blade, select the Secret Management option under Configure from template.
In the Secret Permissions section, select the permissions you want to grant to your Service Principal. For example, you might want to grant Get and List permissions.
In the Select principal section, search for your Service Principal by name or by Application ID.
Click on the Add button to add the access policy.
After you've added the access policy, your Service Principal will have the necessary permissions to access the secrets stored in the Key Vault. You can then use the Azure.Identity library in your C# code to authenticate with Azure and retrieve the secrets from the Key Vault using the DefaultAzureCredential class.
This additional step ensures that your Service Principal has the necessary permissions to access your secrets stored in Azure Key Vault, which is a best practice for securing your application's credentials and other sensitive data.
Conclusion
This will allow you to initiate applications from your IDE of choice without requiring licensing or additional plugins to operate and puts you a step closer to managing your applications using Azure Managed Identities. Which, in this developer's opinion, is where you want to go!