Friday, November 27, 2026

Azure CLI: Working with Multiple Tenants Side by Side using AZURE_CONFIG_DIR

In this post, let's have a look at how I work with multiple Azure tenants, signed in with different accounts, at the same time using the Azure CLI.

I use az a lot, and I often work across tenants that belong to different accounts. A single az sign-in can hold more than one account, but it has only one current subscription, and every terminal shares it. Run az account set in one terminal, and the command you run in another terminal a minute later goes to a different subscription, possibly in a different tenant. That's quite a pain.

I am using Azure CLI 2.93.0 (latest as of today, it will change).

What is AZURE_CONFIG_DIR

AZURE_CONFIG_DIR is an environment variable that tells the Azure CLI where to keep its state. When it's not set, it defaults to %USERPROFILE%\.azure on Windows ($HOME/.azure on Linux and macOS). Every time az runs, it reads and writes everything in that folder.

If you look inside, these are the files that matter:
  • azureProfile.json: the signed-in accounts, the subscriptions you can see, and which one is current (isDefault). This is what az account set changes.
  • msal_token_cache.bin (on Windows): the token cache. Your tokens live here, not in azureProfile.json.
  • config: whatever you set with az config (default resource group, location, output and so on).
  • cliextensions and bin: installed extensions and the Bicep CLI.
So the folder is basically your Azure CLI identity. Point AZURE_CONFIG_DIR at a different folder, and you get a completely separate sign-in, current subscription and token cache. And since environment variables are per process, each terminal can point at its own folder.

I have one folder per account.
C:\Users\Jaliya\.azure            # Personal (the default)
C:\Users\Jaliya\.azure-contoso    # Contoso tenant
C:\Users\Jaliya\.azure-fabrikam   # Fabrikam tenant
...
To set one up, point the variable at a new folder and sign in. The folder gets created the first time az runs.
$env:AZURE_CONFIG_DIR = "$HOME\.azure-contoso"

az login `
    --tenant contoso.onmicrosoft.com

az account show `
    --query user.name `
    --output tsv
Open another terminal without the variable, run az account show, and you are still signed in with your personal account. Neither terminal can affect the other.

Switching automatically by folder

Setting the variable by hand gets old fast, and forgetting to set it is exactly the mistake we are trying to avoid. All my code for a given client lives under one root folder, so I let my PowerShell profile pick the config folder based on the current location.
# One Azure CLI profile per folder root; the default ~/.azure everywhere else
$env:AZURE_EXTENSION_DIR = "$HOME\.azure\cliextensions"

$script:AzureConfigDirByRoot = [ordered]@{
    'D:\Repos\Contoso'  = "$HOME\.azure-contoso"
    'D:\Repos\Fabrikam' = "$HOME\.azure-fabrikam"
}

function Set-AzureConfigForLocation {
    $path = (Get-Location).ProviderPath
    foreach ($root in $script:AzureConfigDirByRoot.Keys) {
        if ($path -eq $root -or $path.StartsWith("$root\", 'OrdinalIgnoreCase')) {
            $script:AzureConfigDirAuto = $env:AZURE_CONFIG_DIR = $script:AzureConfigDirByRoot[$root]
            return
        }
    }
    # Only undo a value set here, so a manually set or inherited AZURE_CONFIG_DIR survives.
    if ($env:AZURE_CONFIG_DIR -and $env:AZURE_CONFIG_DIR -eq $script:AzureConfigDirAuto) {
        $env:AZURE_CONFIG_DIR = $null
    }
}

Set-AzureConfigForLocation
$previousLocationChangedAction = $ExecutionContext.SessionState.InvokeCommand.LocationChangedAction
$ExecutionContext.SessionState.InvokeCommand.LocationChangedAction = {
    Set-AzureConfigForLocation
    if ($previousLocationChangedAction) {
        & $previousLocationChangedAction @args
    }
}.GetNewClosure()
LocationChangedAction runs every time the location changes, so cd D:\repos\contoso\some-repo switches me to the Contoso sign-in, and leaving the folder clears the variable and takes me back to my personal one. The call at startup covers a terminal that opens straight into one of those folders.

It only clears a value it set itself, so an AZURE_CONFIG_DIR you set by hand (like in the example above), or one the terminal inherited, is left alone. And instead of replacing LocationChangedAction, it calls whatever handler was already registered, so it plays nicely with other modules that use it.

A nice side effect: anything started from that terminal inherits the variable. AzureCliCredential (and DefaultAzureCredential when it falls back to it) gets its token by running az, so an app I dotnet run from a Contoso repo authenticates as my Contoso account.

What about extensions

You might have noticed AZURE_EXTENSION_DIR at the top. By default, extensions are installed into cliextensions under the config folder. That means each new profile starts with no extensions at all, and you end up running az extension add for each profile and updating each one separately.

AZURE_EXTENSION_DIR overrides that location. I point it at the extensions folder of my primary profile, so I install an extension once and every profile has it.
$env:AZURE_CONFIG_DIR = "$HOME\.azure-contoso"

az extension list `
    --query "[].name" `
    --output tsv
# (nothing)

$env:AZURE_EXTENSION_DIR = "$HOME\.azure\cliextensions"

az extension list `
    --query "[].name" `
    --output tsv
# account
# containerapp
# resource-graph
# Omitted for brevity
Sharing is safe because extensions are just code; there are no accounts or tokens in there. If you need a client to stay on a specific extension version (say a preview build of containerapp), simply don't set AZURE_EXTENSION_DIR for that folder, and it gets its own extensions. Just remember the Bicep CLI that az bicep install downloads still goes into bin under each config folder.

What it doesn't cover

This is an Azure CLI thing, so tools that don't go through az won't follow it.
  • Azure PowerShell (the Az module) keeps its own context and doesn't read AZURE_CONFIG_DIR.
  • Azure Developer CLI (azd) has its own AZD_CONFIG_DIR.
  • Anything not started from that terminal (Visual Studio or VS Code opened from the Start menu, for example) never sees the variable.

Is this a standard approach?

The variable is. Microsoft documents AZURE_CONFIG_DIR, and even recommends giving each script its own config folder when you run az concurrently, to avoid write conflicts on the token cache. What the Azure CLI doesn't have is named profiles, so one folder per account is the way to get them. It has been working great for me.

More read:

Hope this helps.

Happy Coding.

Regards,
Jaliya

Sunday, November 22, 2026

Microsoft Agent Framework: Durable Workflows on Azure Functions with .NET

In Microsoft Ignite 2026, there are a lot of new announcements for Azure Functions: What's new in Azure Functions and Durable Task Scheduler at Microsoft Ignite 2026.

One of them is the Durable Task extension for Microsoft Agent Framework going GA.

Earlier I blogged about running agents on Azure Functions (with Durable Functions, with Durable Task Scheduler) and about coordinating multiple agents from a Durable Functions orchestrator, where we wrote the orchestrator ourselves. I have also blogged about workflows: handoff, hosting it in Microsoft Foundry and human in the loop. Those were built with AgentWorkflowBuilder, where the agents decide among themselves who answers next.

In this post, let's see how we can run a Microsoft Agent Framework Workflow durably on Azure Functions. This time the workflow is built with WorkflowBuilder, where we connect the steps ourselves with edges, and the Durable Task extension runs it as an orchestration, so there is no orchestrator code to write.

A workflow in Agent Framework is a graph: agents and executors are the nodes, edges connect them, and the output of one node becomes the input of the next. The Durable Task extension can run that graph as a Durable Functions orchestration.

We are going to build a small weekend planner with two agents. The first one checks whether the weather is good for outdoor activities, and the second one builds an itinerary based on that.

Setup

Let's start by creating an Azure Functions worker project targeting .NET 10 (isolated worker model). These are the packages we need (latest as of today, it will change).
<ItemGroup>
  <PackageReference Include="Microsoft.Agents.AI.Foundry" Version="1.28.0-preview.261106.1" />
  <PackageReference Include="Microsoft.Agents.AI.Hosting.AzureFunctions" Version="1.16.0" />
  <PackageReference Include="Microsoft.Azure.Functions.Worker" Version="2.52.0" />
  <PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.DurableTask" Version="1.22.0" />
  <PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.DurableTask.AzureManaged" Version="1.12.0" />
  <PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.Http.AspNetCore" Version="2.1.1" />
  <PackageReference Include="Microsoft.Azure.Functions.Worker.Sdk" Version="2.1.0" />
</ItemGroup>
Microsoft.Agents.AI.Hosting.AzureFunctions is the package that does the heavy lifting. Note that Microsoft.Agents.AI.Foundry is still in preview.

For the durable backend, we will be using the Durable Task Scheduler emulator, along with Azurite for the Functions host storage.
docker run `
    --detach `
    --name dts-emulator `
    --publish 8080:8080 `
    --publish 8082:8082 `
    mcr.microsoft.com/dts/dts-emulator:latest
The local.settings.json looks like below.
{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "UseDevelopmentStorage=true",
    "FUNCTIONS_WORKER_RUNTIME": "dotnet-isolated",
    "DTS_CONNECTION_STRING": "Endpoint=http://localhost:8080;Authentication=None",
    "TASKHUB_NAME": "default",
    "AZURE_AI_ENDPOINT": "https://<resource>.services.ai.azure.com/api/projects/<project>",
    "AZURE_AI_MODEL": "<model-deployment-name>"
  }
}
And in host.json, we point Durable Functions to the scheduler.
{
  "version": "2.0",
  "logging": {
    "logLevel": {
      "default": "Error",
      "Host.Function.Console": "Information"
    }
  },
  "extensions": {
    "durableTask": {
      "hubName": "%TASKHUB_NAME%",
      "storageProvider": {
        "type": "azureManaged",
        "connectionStringName": "DTS_CONNECTION_STRING"
      }
    }
  }
}

The agents

The agents are created the usual way. Each one has a couple of tools: GetWeather and GetCurrentDate for the first one, GetActivities and GetCurrentDate for the second one. GetWeather and GetActivities return hard-coded values, and every tool prints a line to the console when it gets called.
var endpoint = Environment.GetEnvironmentVariable("AZURE_AI_ENDPOINT")!;
var deploymentName = Environment.GetEnvironmentVariable("AZURE_AI_MODEL")!;

// For local development, using AzureCliCredential
var credential = new AzureCliCredential();
var projectClient = new AIProjectClient(new Uri(endpoint), credential);

AIAgent weatherAssessor = projectClient
    .AsAIAgent(
        model: deploymentName,
        name: "WeatherAssessor",
        instructions: """
            You are given a city. Determine whether the weather there is suitable for outdoor leisure activities this weekend.
            Use the available tools to check the weather and current date.
            Respond with the city, the weather, and whether it is suitable for outdoor activities.
            """,
        tools: [
            AIFunctionFactory.Create(Tools.GetWeather),
            AIFunctionFactory.Create(Tools.GetCurrentDate)
        ]);

AIAgent itineraryPlanner = projectClient
    .AsAIAgent(
        model: deploymentName,
        name: "ItineraryPlanner",
        instructions: """
            You are given a weather assessment for a city. Build a weekend itinerary using the available activities for that city.
            If the weather is not suitable for outdoor activities, only include indoor activities.
            Include the date of the weekend in the itinerary.
            """,
        tools: [
            AIFunctionFactory.Create(Tools.GetActivities),
            AIFunctionFactory.Create(Tools.GetCurrentDate)
        ]);

The workflow

Now the workflow. We start from the first agent and add an edge to the second one, so the answer of WeatherAssessor becomes the input of ItineraryPlanner.
Workflow workflow = new WorkflowBuilder(weatherAssessor)
    .WithName("WeekendPlan")
    .AddEdge(weatherAssessor, itineraryPlanner)
    .Build();
Then we register the workflow with the Functions host.
using IHost app = FunctionsApplication
    .CreateBuilder(args)
    .ConfigureFunctionsWebApplication()
    .ConfigureDurableAgents(options =>
    {
        options.AddAIAgent(weatherAssessor, timeToLive: null, configureHistory: h => h.ProviderKey = new("foundry.v1"));
        options.AddAIAgent(itineraryPlanner, timeToLive: null, configureHistory: h => h.ProviderKey = new("foundry.v1"));
    })
    .ConfigureDurableWorkflows(options => options.AddWorkflow(workflow, enableStatusEndpoint: true))
    .Build();

app.Run();
ConfigureDurableWorkflows is where the magic happens. It turns the workflow into an orchestration, each agent into a durable entity, and creates the HTTP endpoints to run it. We don't write an orchestrator function or an HTTP trigger ourselves.

So why ConfigureDurableAgents? The workflow registers its agents on its own, but Foundry agents keep their conversation history in Foundry, and the durable session needs a stable key to know who owns that history. Registering the agents explicitly lets us set that key through ProviderKey. Without it, every agent call fails with:
History ownership 'Service' requires an explicit stable logical provider key. Set ProviderKey in the agent registration's history options before running this durable session.
The key can be any stable value, just don't change it once you have sessions, since it gets saved with them.

Running it

When we run the Function App, we can see the functions that got created for us.
Functions
The workflow is exposed at /api/workflows/WeekendPlan/run. Because we registered the agents explicitly, each agent also gets its own endpoint. Let's call the workflow using the following .http file.
@host = http://localhost:7071

### Run the WeekendPlan workflow and wait up to 60 seconds for the result
# @name startWithWait
POST {{host}}/api/workflows/WeekendPlan/run?waitForResponse=true&timeoutSeconds=60
Content-Type: text/plain
Accept: text/plain

Auckland

### Run it without waiting, the response has the run id
# @name start
POST {{host}}/api/workflows/WeekendPlan/run
Content-Type: text/plain

Auckland

### Check the status of the run started above
# @name status
GET {{host}}/api/workflows/WeekendPlan/status/{{start.response.body.$.runId}}
With waitForResponse=true, the request waits for the workflow to finish, but only for 10 seconds by default. Two agents with tool calls can take longer than that, so we set timeoutSeconds (up to 200). If it times out, we get a 202 with the run id instead, same as the second request, and we can check the status with the third one.

The first request comes back with the itinerary.
POST {{host}}/api/workflows/WeekendPlan/run?waitForResponse=true&timeoutSeconds=60
And in the Function App console, we can see the tools ran in order: the weather first, then the activities.
Function App: Workflow
We can also open the Durable Task Scheduler dashboard (http://localhost:8082) to see the run.

Tip: you can run .http files from the command line using dotnet-http-file. When a request depends on another one, like the status request here, it runs that one first.
dotnet-http-file DurableWorkflow.http --name status

A few things to note

At the time of writing, there's an issue (microsoft/agent-framework-durable-extension#193) where agent names with hyphens (for example, weather-assessor) don't work in a workflow. The workflow can't find the agent and the run fails with Agent 'weather_assessor' not found. It's easy to miss, because with waitForResponse=true, the response is still a 200 with the error as the body. The status endpoint shows the run as Failed. Until it's fixed, use names without hyphens.

Agents in a workflow pass plain text to each other. Here, it's the ItineraryPlanner that decides indoor or outdoor based on the weather assessment. If you need that decision to be made in code, have a look at conditional edges.

The complete sample is here:

More read:

Hope this helps.

Happy Coding.

Regards,
Jaliya

Wednesday, November 18, 2026

Azure DevOps: Dry Run a Pipeline with the Preview REST API

In this post, let's have a look at the Azure DevOps Pipelines Preview REST API, and how we can use it to validate a YAML pipeline without actually running it.

The only way to know what a YAML pipeline really turns into is usually to queue it. The Preview API does a dry run instead: Azure DevOps compiles the YAML exactly as it would for a real run, and gives us back the final YAML. Nothing is queued, so nothing shows up under the pipeline's runs.

The pipeline

Let's take a simple pipeline with one parameter.
trigger: none

parameters:
  - name: environment
    type: string
    default: dev
    values:
      - dev
      - qa

pool:
  vmImage: ubuntu-latest

steps:
  - script: echo Deploying to ${{ parameters.environment }}
    displayName: Deploy

Calling the Preview API

It's a POST against the pipeline, with previewRun set to true (api-version 7.1, latest as of today, it will change).
POST https://dev.azure.com/{organization}/{project}/_apis/pipelines/{pipelineId}/preview?api-version=7.1
Let's call it from PowerShell. For the token, I am using the Azure CLI. 499b84ac-1321-427f-aa17-267ca6975798 is the resource ID of Azure DevOps, and it is the same for every organization. And we are passing a value for the environment parameter through templateParameters, the same way we would when queuing a run.
$azureDevOpsResourceId = "499b84ac-1321-427f-aa17-267ca6975798"
$organization = "<Organization>"
$project = "<Project>"
$pipelineId = "<PipelineId>"

$token = az account get-access-token `
    --resource $azureDevOpsResourceId `
    --query accessToken `
    --output tsv

$uri = "https://dev.azure.com/$organization/$project/_apis/pipelines/$pipelineId/preview?api-version=7.1"

$body = @{
    previewRun = $true
    templateParameters = @{
        environment = "qa"
    }
} | ConvertTo-Json

$response = Invoke-RestMethod `
    -Method Post `
    -Uri $uri `
    -Headers @{ Authorization = "Bearer $token" } `
    -ContentType "application/json" `
    -Body $body

$response.finalYaml
The response has a single property, finalYaml.
trigger:
  enabled: false
parameters:
- name: environment
  type: string
  default: dev
  values:
  - dev
  - qa
stages:
- stage: __default
  jobs:
  - job: Job
    pool:
      vmImage: ubuntu-latest
    steps:
    - task: CmdLine@2
      displayName: Deploy
      inputs:
        script: echo Deploying to qa

The expression is resolved to qa, and we can see what Azure DevOps does behind the scenes: the steps are wrapped in a default stage and job, the pool is moved down to the job, and script becomes the CmdLine@2 task.

If we pass a value that isn't allowed, say prod, the call fails with the same error a real run would give us.
{
  "message": "The 'environment' parameter value 'prod' is not a valid value.",
  "typeKey": "PipelineValidationException"
  // Omitted for brevity
}

After all of these calls, the pipeline still has no runs.

There are two more properties worth knowing. yamlOverride lets us send YAML that isn't committed yet and preview that instead. And resources.repositories.self.refName (for example refs/heads/feature/my-change) previews another branch, which is handy for diffing the finalYaml of a branch against main before merging.

Keep in mind this only covers what's known at compile time. It won't tell you whether a service connection is authorized, an agent is available, or a runtime variable resolves.

More read:

Hope this helps.

Happy Coding.

Regards,
Jaliya

Sunday, November 15, 2026

Introducing dotnet-http-file: Run Visual Studio .http Files from the Command Line

In this post, let's have a look at dotnet-http-file, a small .NET tool I put together that runs Visual Studio .http files from the command line.

I use .http files a lot. They live next to the code, they are plain text and they are easy to share. But they only run inside the IDE. I wanted to run the same files from a terminal, from a script, on Windows, Linux or macOS, without copying anything into another tool.

The tool reads the same syntax Visual Studio does: variables, http-client.env.json environments, request variables and so on. It adds one thing of its own: a provider that gets a Microsoft Entra access token from your existing sign-in, so you don't have to paste tokens into files.

Installing

It's on NuGet as a .NET global tool. It needs .NET 11, and the version is 0.1.0 (latest as of today, it will change).
dotnet tool install --global dotnet-http-file

Running a request

Let's take a simple .http file against JSONPlaceholder Fake REST API.
@BaseUrl=https://jsonplaceholder.typicode.com

# @name getToDos
GET {{BaseUrl}}/todos?_limit=2

###

# @name getToDo
GET {{BaseUrl}}/todos/{{getToDos.response.body.$[1].id}}
When the file has more than one request, it asks which one to run.
dotnet http-file Basics.http
dotnet http-file Basics.http
You can directly pick the request by its name.
dotnet http-file Basics.http --name getToDo
 dotnet http-file Basics.http --name getToDo
That's the nice part. getToDo uses a value from getToDos, so the tool sends getToDos first. In Visual Studio, you'd have to send it yourself before this one.

No more pasting tokens

A lot of times, when calling Entra protected APIs, you will have to separately run az account get-access-token, copy the token and paste it into a @token variable. Then it expires within the hour and you do it again.

With dotnet-http-file, you put the scope in http-client.env.json using the EntraAccessToken provider.
{
  "dev": {
    "GraphToken": {
      "provider": "EntraAccessToken",
      "scope": "https://graph.microsoft.com/.default"
    }
  }
}
And use it like any other variable.
# @name getMe
GET https://graph.microsoft.com/v1.0/me?$select=displayName,userPrincipalName
Authorization: Bearer {{GraphToken}}
Accept: application/json
dotnet http-file Entra.http --name getMe --env dev
dotnet http-file Entra.http --name getMe --env dev
The token comes from DefaultAzureCredential, so it works with whatever you're already signed in with: az login, Visual Studio, azd auth login and so on. Every run gets a fresh token, and the tool never opens a browser. You can also add a tenantId when your account lives in more than one tenant.

Using it in scripts

In a terminal, the tool prints the request, status, headers and the formatted body, with secrets masked. When the output is piped, it writes only the raw body to stdout, so it plays well with other tools.
dotnet http-file Basics.http --name getToDos | jq '.[0].title'
dotnet http-file Basics.http --name getToDos | jq '.[0].title'
You can use --show with full, headers, status or body to choose what gets printed. 
dotnet http-file Basics.http --name getToDos --show body
A failed request gives a non-zero exit code, so it works as a quick smoke test in a pipeline too.

The source and the samples are on GitHub. Give it a try, and if something in your .http files doesn't work, please open an issue.

More read:

Hope this helps.

Happy Coding.

Regards,
Jaliya