This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Note
Access to this page requires authorization. You can trysigning in orchanging directories.
Access to this page requires authorization. You can trychanging directories.
This example demonstrates how to use the Azure SDK management libraries in a Python script to create a resource group. (TheEquivalent Azure CLI command is given later in this article. If you prefer to use the Azure portal, seeCreate resource groups.)
All the commands in this article work the same in Linux/macOS bash and Windows command shells unless noted.
If you haven't already, set up an environment where you can run this code. Here are some options:
Configure a Python virtual environment usingvenv or your tool of choice. To start using the virtual environment, be sure to activate it. To install python, seeInstall Python.
#!/bin/bash# Create a virtual environmentpython -m venv .venv# Activate the virtual environmentsource .venv/Scripts/activate # only required for Windows (Git Bash)Use aconda environment. To install Conda, seeInstall Miniconda.
Use aDev Container inVisual Studio Code orGitHub Codespaces.
In your console, create arequirements.txt file that lists the management libraries used in this example:
azure-mgmt-resourceazure-identityIn your console with the virtual environment activated, install the requirements:
pip install -r requirements.txtIn this step, you set environment variables for use in the code in this article. The code uses theos.environ method to retrieve the values.
#!/bin/bashexport AZURE_RESOURCE_GROUP_NAME=<ResourceGroupName> # Change to your preferred resource group nameexport LOCATION=<Location> # Change to your preferred regionexport AZURE_SUBSCRIPTION_ID=$(az account show --query id --output tsv)In this step, you create a Python file namedprovision_blob.py with the following code. This Python script uses the Azure SDK for Python management libraries to create a resource group in your Azure subscription.
Create a Python file namedprovision_rg.py with the following code. The comments explain the details:
# Import the needed credential and management objects from the libraries.import osfrom azure.identity import DefaultAzureCredentialfrom azure.mgmt.resource import ResourceManagementClient# Acquire a credential object using DevaultAzureCredential.credential = DefaultAzureCredential()# Retrieve subscription ID from environment variable.subscription_id = os.environ["AZURE_SUBSCRIPTION_ID"]# Retrieve resource group name and location from environment variablesRESOURCE_GROUP_NAME = os.environ["AZURE_RESOURCE_GROUP_NAME"]LOCATION = os.environ["LOCATION"]# Obtain the management object for resources.resource_client = ResourceManagementClient(credential, subscription_id)# Provision the resource group.rg_result = resource_client.resource_groups.create_or_update(RESOURCE_GROUP_NAME, { "location": LOCATION })print(f"Provisioned resource group {rg_result.name}")# Within the ResourceManagementClient is an object named resource_groups,# which is of class ResourceGroupsOperations, which contains methods like# create_or_update.## The second parameter to create_or_update here is technically a ResourceGroup# object. You can create the object directly using ResourceGroup(location=# LOCATION) or you can express the object as inline JSON as shown here. For# details, see Inline JSON pattern for object arguments at# https://learn.microsoft.com/azure/developer/python/sdk# /azure-sdk-library-usage-patterns#inline-json-pattern-for-object-argumentsprint( f"Provisioned resource group {rg_result.name} in the {rg_result.location} region")# The return value is another ResourceGroup object with all the details of the# new group. In this case the call is synchronous: the resource group has been# provisioned by the time the call returns.# To update the resource group, repeat the call with different properties, such# as tags:rg_result = resource_client.resource_groups.create_or_update( RESOURCE_GROUP_NAME, { "location": LOCATION, "tags": {"environment": "test", "department": "tech"}, },)print(f"Updated resource group {rg_result.name} with tags")# Optional lines to delete the resource group. begin_delete is asynchronous.# poller = resource_client.resource_groups.begin_delete(rg_result.name)# result = poller.result()Later in this article, you sign in to Azure using the Azure CLI to execute the sample code. If your account has sufficient permissions to create resource groups and storage resources in your Azure subscription, the script should run successfully without additional configuration.
To use this code in a production environment, authenticate using a service principal by setting environment variables. This approach enables secure, automated access without relying on interactive login. For detailed guidance, seeHow to authenticate Python apps with Azure services.
Ensure that the service principal is assigned a role with sufficient permissions to create resource groups and storage accounts. For example, assigning the Contributor role at the subscription level provides the necessary access. To learn more about role assignments, seeRole-based access control (RBAC) in Azure.
If you haven't already, sign in to Azure using the Azure CLI:
az loginRun the script:
python provision_rg.pyYou can verify that the resource group exists through the Azure portal or the Azure CLI.
Azure portal: open theAzure portal, selectResource groups, and check that the group is listed. If necessary, use theRefresh command to update the list.
Azure CLI: use theaz group show command:
#!/bin/bashaz group show -n $AZURE_RESOURCE_GROUP_NAMERun theaz group delete command if you don't need to keep the resource group created in this example. Resource groups don't incur any ongoing charges in your subscription, but resources in the resource group might continue to incur charges. It's a good practice to clean up any group that you aren't actively using. The--no-wait argument allows the command to return immediately instead of waiting for the operation to finish.
#!/bin/bashaz group delete -n $AZURE_RESOURCE_GROUP_NAME --no-waitYou can also use theResourceManagementClient.resource_groups.begin_delete method to delete a resource group from code. The commented code at the bottom of the script in this article demonstrates the usage.
The following Azure CLIaz group create command creates a resource group with tags just like the Python script:
az group create -n PythonAzureExample-rg -l centralus --tags "department=tech" "environment=test"Was this page helpful?
Need help with this topic?
Want to try using Ask Learn to clarify or guide you through this topic?
Was this page helpful?
Want to try using Ask Learn to clarify or guide you through this topic?