Search code examples
azureazure-python-sdkazure-subscription

Azure Python SDK add tag to subscription


I am new to use Azure python sdk. I have been using the following command to add tags to a subscription:

az tag update --operation merge --resource-id /subscriptions/{subscription-id} --tags <tag-name>=<tag-value>

The above command works good and creates the tag with the specified value in the subscription. However, I want to use the similar functionality in Python SDK. I found this to create / update a tag. It is returning a successful message. But I could not find any tag attached to the subscription with the given name. Please find attached code sample:

import os
import json
import csv
from azure.identity import DefaultAzureCredential
from azure.identity import InteractiveBrowserCredential
from azure.mgmt.resource.subscriptions import SubscriptionClient
from azure.mgmt.resource.resources import ResourceManagementClient

# from azure.

def main() :
    header = ("subscription name", "subscription id", "pce-identity-functional-group")
    subscription_client = SubscriptionClient(credential=DefaultAzureCredential())

    result = subscription_client.subscriptions.list()
    for e in result:
        rc = ResourceManagementClient(credential=DefaultAzureCredential(), subscription_id=e.subscription_id)
        print(rc.tags.create_or_update(tag_name="testing_one"))

Could anyone help me find where I am going wrong ? Thanks in advance.


Solution

  • I tried in my environment and got below results:

    Initially I have tried python code to Add the tag in the subscription level.

    enter image description here

    The error show in SDK it updates only Predefined tags .

    According to MS-DOCS it clearly state used to create and update method is used to predefined tags. you can add tags by Powershell as you mentioned in your post.

    enter image description here

    But in python sdk you can update in resource group level.

    Code:

    import os
    from azure.identity import DefaultAzureCredential
    from azure.mgmt.resource import ResourceManagementClient
    from azure.mgmt.resource.subscriptions import SubscriptionClient
    
    
    
    subscription_id = os.environ.get("AZURE_SUBSCRIPTION_ID", "<id>") # your Azure Subscription Id
    credentials = DefaultAzureCredential()
    client = ResourceManagementClient(credentials, subscription_id)
    SubscriptionClient = client
    resource_group_params = {'location':'East US'}
    resource_group_params.update(tags={'environment': 'cloud'})
    client.resource_groups.update('resourcegroup', resource_group_params)
    

    Console: enter image description here

    Portal: enter image description here

    Reference: