I’m looking for a way to programmatically log in to Azure without needing to install the Azure CLI. Currently, I use the following commands:
az login --service-principal -u <user_credentials> -p <password> --tenant <tenant_id>
az account set -s <subscription_id>
However, these require the Azure CLI to be pre-installed. Is there an alternative method to authenticate with the same credentials (service principal, tenant, subscription ID) in Python without relying on the Azure CLI? Any suggestions or guidance would be greatly appreciated. Thanks!
3
Answers
For programmatically logging in and acquiring tokens in Python, the package you would want to use is
azure-identity
.Since you are using a Service Principal for logging in, you would want to use
ClientSecretCredential
to create a credential object which you would use later on with other Azure SDKs to authorize requests.Here’s some sample code:
I would suggest that you check the following libraries and their documentation:
They also come with code samples for different tasks.
You can use
clientId
,clientSecret
to get access_token, then request azure rest api with the access_token, which case azure cli installation is not required. Even many azure-related modules do not need to be installed, using the primitive method