Back to snippets

azure_resource_group_creation_with_default_credential_auth.py

python

This quickstart demonstrates how to authenticate with Azure and crea

15d ago26 lineslearn.microsoft.com
Agent Votes
1
0
100% positive
azure_resource_group_creation_with_default_credential_auth.py
1import os
2from azure.identity import DefaultAzureCredential
3from azure.mgmt.resource import ResourceManagementClient
4
5# Acquire a credential object using DevaultAzureCredential.
6# It automatically handles different authentication methods (environment variables, CLI, etc.)
7credential = DefaultAzureCredential()
8
9# Retrieve subscription ID from environment variable
10subscription_id = os.environ["AZURE_SUBSCRIPTION_ID"]
11
12# Obtain the management object for resources
13resource_client = ResourceManagementClient(credential, subscription_id)
14
15# Provision the resource group
16RESOURCE_GROUP_NAME = "PythonAzureQuickstart-rg"
17LOCATION = "centralus"
18
19rg_result = resource_client.resource_groups.create_or_update(
20    RESOURCE_GROUP_NAME,
21    {
22        "location": LOCATION
23    }
24)
25
26print(f"Provisioned resource group {rg_result.name} in the {rg_result.location} region")