How to create Azure Resource group using Python

Azure libraries for Python simplify provisioning, managing, and using Azure resources from Python application code.This post describes how to create an Azure Resource Group using Python.

Prerequisite: Below are the prerequisites for following this post.

1. Azure CLI. Refer below articles to install Azure CLI.

[Windows]
Install Azure CLI on windows
[Ubuntu]
Install Azure CLI on Ubuntu
2. Python 3.6 or later

Create Azure Resource Group using Python

  • Install required Python Libraries
  •         
                
    pip install azure-identity
    pip install azure-mgmt-resource
    
        
        
  • Login with Azure CLI
  •         
    
    az login
    
        
        
  • Import AzureCliCredential and ResourceManagementClient class
  •         
    
    from azure.identity import AzureCliCredential
    from azure.mgmt.resource import ResourceManagementClient
    
        
        
  • Define SubscriptionName, ResourceGroupName and Location
  •         
    
    subscription_id = "REPLACE_WITH_SUBSCRIPTION_ID"
    
    RESOURCE_GROUP_NAME = "REPLACE_WITH_RESOURCE_GROUP_NAME"
    LOCATION = "REPLACE_WITH_LOCATION" # e.g uswest, uswest2 etc..
    
        
        
  • Get credentials and Obtain the management object for resources
  •         
    
    credential = AzureCliCredential()
    resource_client = ResourceManagementClient(credential, subscription_id)
    
        
        
  • Create Resource Group
  •         
    
    response = resource_client.resource_groups.create_or_update(
    RESOURCE_GROUP_NAME, {"location": LOCATION}
    )
    
    print(f"Resource Group {response.name} has been created in {response.location}")
        
        
  • Complete Code Snippet
  •         
                
    from azure.identity import AzureCliCredential
    from azure.mgmt.resource import ResourceManagementClient
    
    
    subscription_id = "REPLACE_WITH_SUBSCRIPTION_ID"
    
    RESOURCE_GROUP_NAME = "REPLACE_WITH_RESOURCE_GROUP_NAME"
    LOCATION = "REPLACE_WITH_LOCATION" # e.g uswest, uswest2 etc..
    
    
    credential = AzureCliCredential()
    
    resource_client = ResourceManagementClient(credential, subscription_id)
    
    response = resource_client.resource_groups.create_or_update(
    RESOURCE_GROUP_NAME, {"location": LOCATION}
    )
    
    print(f"Resource Group {response.name} has been created in {response.location}")
    
        
        

    Category: Azure