Azure Python SDK Authentication

Written By Ronnie Quan


Python is widely used in infrastructure as code type of project, I started my cloud journey utilizing Java and Python, then abandon them all to work in windows and Azure world.

Now finally I have chance to start from scratch again with Python.

In this article, I will install PyCharm, create a project from scratch, authenticate to Azure and work with keyvault.

The goal is to test from local without any credential stored in local, either in IDE or environment variable. We will utilize DefaultAzureCredential class instead of UsernamePasswordCredential.

When run the code from Azure, the best option is to use managed identity.



Download PyCharm Community Version(Free), and install in your local environment.

Project and Virtual Environment

Create your first project and let the IDE to create Python virtual environment for you.

Azure Packages


Configure KeyVault Name

I put keyvault name in PyCharm run configurations

Hello World Code

Sign In to Azure

az login

  1. If the CLI can open your default browser, it will do so and load an Azure sign-in page.
  2. Otherwise, open a browser page at and enter the authorization code displayed in your terminal.
  3. Sign in with your account credentials in the browser.

Execute Code

From PyCharm, click run or debug button from top right, or use short cut key shift + F10, we retrieved our secret from Azure keyvault.

More About DefaultAzureCredential

In our code, we added multiple exclude arguments, why?

The default credential class get access token from following identity options, it evaluates the option one by one and stops when a token is provided.

  1. A service principal configured by environment variables.
  2. An Azure managed identity.
  3. On Windows only: a user who has signed in with a Microsoft application, such as Visual Studio. If multiple identities are in the cache, then the value of the environment variable AZURE_USERNAME is used to select which identity to use. See SharedTokenCacheCredential for more details.
  4. The user currently signed in to Visual Studio Code.
  5. The identity currently logged in to the Azure CLI.
  6. The identity currently logged in to Azure PowerShell.

In our case, we would like to use az cli logged in user to authenticate to Azure keyvault, since we don’t prefer service principal, we don’t have managed identity in local and we are not using Visual Studio, so we skip all the first four identity options.

By the way, when I don’t have exclude argument, the execution failed with exception in managed identity option. Not sure this is by design, but I just include exclude argument to get around.


Azure Key Vault Secret client library for Python | Microsoft Docs

azure.identity.DefaultAzureCredential class | Microsoft Docs

azure.identity.UsernamePasswordCredential class | Microsoft Docs

Download PyCharm: Python IDE for Professional Developers by JetBrains