Dela via


Använda taggar med Python

Den här artikeln beskriver hur du använder Python för att tagga resurser, resursgrupper och prenumerationer. Taggrekommendationer och begränsningar finns i Använda taggar för att organisera dina Azure-resurser och hanteringshierarki.

Förutsättningar

  • Python 3.8 eller senare installerat. Information om hur du installerar det senaste finns i Python.org

  • Följande Azure-bibliotekspaket för Python installerade i din virtuella miljö. Om du vill installera något av paketen använder du pip install {package-name}

    • azure-identity
    • azure-mgmt-resource

    Om du redan har äldre versioner av dessa paket installerade i den virtuella miljön kan du behöva uppdatera dem med pip install --upgrade {package-name}

  • Exemplen i den här artikeln använder CLI-baserad autentisering (AzureCliCredential). Beroende på din miljö kan du behöva köra az login först för att autentisera.

  • En miljövariabel med ditt Azure-prenumerations-ID. Om du vill hämta ditt Azure-prenumerations-ID använder du:

    az account show --name 'your subscription name' --query id -o tsv
    

    Om du vill ange värdet använder du alternativet för din miljö.

    setx AZURE_SUBSCRIPTION_ID your-subscription-id
    

    Kommentar

    Om du bara behöver komma åt miljövariabeln i den aktuella konsolen som körs kan du ange miljövariabeln med set i stället för setx.

    När du har lagt till miljövariablerna kan du behöva starta om alla program som körs och som behöver läsa miljövariabeln, inklusive konsolfönstret. Om du till exempel använder Visual Studio som redigerare startar du om Visual Studio innan du kör exemplet.

Tillämpa taggar

Azure Python erbjuder ResourceManagementClient.tags.begin_create_or_update_at_scope metod för att tillämpa taggar. Den ersätter alla taggar på resursen, resursgruppen eller prenumerationen. När du anropar kommandot skickar du resurs-ID:t för den entitet som du vill tagga.

I följande exempel tillämpas en uppsättning taggar på ett lagringskonto:

import os
from azure.identity import AzureCliCredential
from azure.mgmt.resource import ResourceManagementClient
from azure.mgmt.resource.resources.models import TagsResource

credential = AzureCliCredential()
subscription_id = os.environ["AZURE_SUBSCRIPTION_ID"]

resource_client = ResourceManagementClient(credential, subscription_id)

resource_group_name = "demoGroup"
storage_account_name = "demostore"

tags = {
    "Dept": "Finance",
    "Status": "Normal"
}

tag_resource = TagsResource(
    properties={'tags': tags}
)

resource = resource_client.resources.get_by_id(
    f"/subscriptions/{subscription_id}/resourceGroups/{resource_group_name}/providers/Microsoft.Storage/storageAccounts/{storage_account_name}",
    "2022-09-01"
)

resource_client.tags.begin_create_or_update_at_scope(resource.id, tag_resource)

print(f"Tags {tag_resource.properties.tags} were added to resource with ID: {resource.id}")

Om du kör kommandot igen, men den här gången med olika taggar, ser du att de tidigare taggarna försvinner.

tags = {
    "Team": "Compliance",
    "Environment": "Production"
}

Om du vill lägga till taggar i en resurs som redan har taggar använder du ResourceManagementClient.tags.begin_update_at_scope. I objektet TagsPatchResource anger du parametern operation till Merge.

import os
from azure.identity import AzureCliCredential
from azure.mgmt.resource import ResourceManagementClient
from azure.mgmt.resource.resources.models import TagsPatchResource

credential = AzureCliCredential()
subscription_id = os.environ["AZURE_SUBSCRIPTION_ID"]

resource_client = ResourceManagementClient(credential, subscription_id)

resource_group_name = "demoGroup"
storage_account_name = "demostore"

tags = {
    "Dept": "Finance",
    "Status": "Normal"
}

tag_patch_resource = TagsPatchResource(
    operation="Merge",
    properties={'tags': tags}
)

resource = resource_client.resources.get_by_id(
    f"/subscriptions/{subscription_id}/resourceGroups/{resource_group_name}/providers/Microsoft.Storage/storageAccounts/{storage_account_name}",
    "2022-09-01"
)

resource_client.tags.begin_update_at_scope(resource.id, tag_patch_resource)

print(f"Tags {tag_patch_resource.properties.tags} were added to existing tags on resource with ID: {resource.id}")

Observera att de befintliga taggarna växer med tillägg av de två nya taggarna.

Varje taggnamn kan bara ha ett värde. Om du anger ett nytt värde för en tagg ersätter det det gamla värdet även om du använder sammanslagningsåtgärden. I följande exempel ändras taggen Status från Normal till Grön.

import os
from azure.identity import AzureCliCredential
from azure.mgmt.resource import ResourceManagementClient
from azure.mgmt.resource.resources.models import TagsPatchResource

credential = AzureCliCredential()
subscription_id = os.environ["AZURE_SUBSCRIPTION_ID"]

resource_client = ResourceManagementClient(credential, subscription_id)

resource_group_name = "demoGroup"
storage_account_name = "demostore"

tags = {
    "Status": "Green"
}

tag_patch_resource = TagsPatchResource(
    operation="Merge",
    properties={'tags': tags}
)

resource = resource_client.resources.get_by_id(
    f"/subscriptions/{subscription_id}/resourceGroups/{resource_group_name}/providers/Microsoft.Storage/storageAccounts/{storage_account_name}",
    "2022-09-01"
)

resource_client.tags.begin_update_at_scope(resource.id, tag_patch_resource)

print(f"Tags {tag_patch_resource.properties.tags} were added to existing tags on resource with ID: {resource.id}")

När du anger parametern operation till Replaceersätter den nya uppsättningen taggar de befintliga taggarna.

import os
from azure.identity import AzureCliCredential
from azure.mgmt.resource import ResourceManagementClient
from azure.mgmt.resource.resources.models import TagsPatchResource

credential = AzureCliCredential()
subscription_id = os.environ["AZURE_SUBSCRIPTION_ID"]

resource_client = ResourceManagementClient(credential, subscription_id)

resource_group_name = "demoGroup"
storage_account_name = "demostore"

tags = {
    "Project": "ECommerce",
    "CostCenter": "00123",
    "Team": "Web"
}

tag_patch_resource = TagsPatchResource(
    operation="Replace",
    properties={'tags': tags}
)

resource = resource_client.resources.get_by_id(
    f"/subscriptions/{subscription_id}/resourceGroups/{resource_group_name}/providers/Microsoft.Storage/storageAccounts/{storage_account_name}",
    "2022-09-01"
)

resource_client.tags.begin_update_at_scope(resource.id, tag_patch_resource)

print(f"Tags {tag_patch_resource.properties.tags} replaced tags on resource with ID: {resource.id}")

Endast de nya taggarna finns kvar på resursen.

Samma kommandon fungerar också med resursgrupper eller prenumerationer. Skicka dem i identifieraren för den resursgrupp eller prenumeration som du vill tagga. Om du vill lägga till en ny uppsättning taggar i en resursgrupp använder du:

import os
from azure.identity import AzureCliCredential
from azure.mgmt.resource import ResourceManagementClient
from azure.mgmt.resource.resources.models import TagsResource

credential = AzureCliCredential()
subscription_id = os.environ["AZURE_SUBSCRIPTION_ID"]

resource_client = ResourceManagementClient(credential, subscription_id)

resource_group_name = "demoGroup"

tags = {
    "Dept": "Finance",
    "Status": "Normal"
}

tag_resource = TagsResource(
    properties={'tags': tags}
)

resource_group = resource_client.resource_groups.get(resource_group_name)

resource_client.tags.begin_create_or_update_at_scope(resource_group.id, tag_resource)

print(f"Tags {tag_resource.properties.tags} were added to resource group: {resource_group.id}")

Om du vill uppdatera taggarna för en resursgrupp använder du:

import os
from azure.identity import AzureCliCredential
from azure.mgmt.resource import ResourceManagementClient
from azure.mgmt.resource.resources.models import TagsPatchResource

credential = AzureCliCredential()
subscription_id = os.environ["AZURE_SUBSCRIPTION_ID"]

resource_client = ResourceManagementClient(credential, subscription_id)

resource_group_name = "demoGroup"

tags = {
    "CostCenter": "00123",
    "Environment": "Production"
}

tag_patch_resource = TagsPatchResource(
    operation="Merge",
    properties={'tags': tags}
)

resource_group = resource_client.resource_groups.get(resource_group_name)

resource_client.tags.begin_update_at_scope(resource_group.id, tag_patch_resource)

print(f"Tags {tag_patch_resource.properties.tags} were added to existing tags on resource group: {resource_group.id}")

Om du vill uppdatera taggarna för en prenumeration använder du:

import os
from azure.identity import AzureCliCredential
from azure.mgmt.resource import ResourceManagementClient
from azure.mgmt.resource.resources.models import TagsPatchResource

credential = AzureCliCredential()
subscription_id = os.environ["AZURE_SUBSCRIPTION_ID"]

resource_client = ResourceManagementClient(credential, subscription_id)

tags = {
    "Team": "Web Apps"
}

tag_patch_resource = TagsPatchResource(
    operation="Merge",
    properties={'tags': tags}
)

resource_client.tags.begin_update_at_scope(f"/subscriptions/{subscription_id}", tag_patch_resource)

print(f"Tags {tag_patch_resource.properties.tags} were added to subscription: {subscription_id}")

Du kan ha fler än en resurs med samma namn i en resursgrupp. I så fall kan du ange varje resurs med följande kommandon:

import os
from azure.identity import AzureCliCredential
from azure.mgmt.resource import ResourceManagementClient
from azure.mgmt.resource.resources.models import TagsPatchResource

credential = AzureCliCredential()
subscription_id = os.environ["AZURE_SUBSCRIPTION_ID"]

resource_client = ResourceManagementClient(credential, subscription_id)

resource_group_name = "demoGroup"

tags = {
    "Dept": "IT",
    "Environment": "Test"
}

tag_patch_resource = TagsPatchResource(
    operation="Merge",
    properties={'tags': tags}
)

resources = resource_client.resources.list_by_resource_group(resource_group_name, filter="name eq 'sqlDatabase1'")

for resource in resources:
    resource_client.tags.begin_update_at_scope(resource.id, tag_patch_resource)
    print(f"Tags {tag_patch_resource.properties.tags} were added to resource: {resource.id}")

Visa en lista över taggar

Om du vill hämta taggarna för en resurs, resursgrupp eller prenumeration använder du metoden ResourceManagementClient.tags.get_at_scope och skickar resurs-ID:t för entiteten.

Om du vill se taggarna för en resurs använder du:

import os
from azure.identity import AzureCliCredential
from azure.mgmt.resource import ResourceManagementClient

credential = AzureCliCredential()
subscription_id = os.environ["AZURE_SUBSCRIPTION_ID"]

resource_group_name = "demoGroup"
storage_account_name = "demostorage"

resource_client = ResourceManagementClient(credential, subscription_id)

resource = resource_client.resources.get_by_id(
    f"/subscriptions/{subscription_id}/resourceGroups/{resource_group_name}/providers/Microsoft.Storage/storageAccounts/{storage_account_name}",
    "2022-09-01"
)

resource_tags = resource_client.tags.get_at_scope(resource.id)
print (resource_tags.properties.tags)

Om du vill se taggarna för en resursgrupp använder du:

import os
from azure.identity import AzureCliCredential
from azure.mgmt.resource import ResourceManagementClient

credential = AzureCliCredential()
subscription_id = os.environ["AZURE_SUBSCRIPTION_ID"]

resource_client = ResourceManagementClient(credential, subscription_id)

resource_group = resource_client.resource_groups.get("demoGroup")

resource_group_tags = resource_client.tags.get_at_scope(resource_group.id)
print (resource_group_tags.properties.tags)

Om du vill se taggarna för en prenumeration använder du:

import os
from azure.identity import AzureCliCredential
from azure.mgmt.resource import ResourceManagementClient

credential = AzureCliCredential()
subscription_id = os.environ["AZURE_SUBSCRIPTION_ID"]

resource_client = ResourceManagementClient(credential, subscription_id)

subscription_tags = resource_client.tags.get_at_scope(f"/subscriptions/{subscription_id}")
print (subscription_tags.properties.tags)

Lista efter tagg

Om du vill hämta resurser som har ett specifikt taggnamn och -värde använder du:

import os
from azure.identity import AzureCliCredential
from azure.mgmt.resource import ResourceManagementClient

credential = AzureCliCredential()
subscription_id = os.environ["AZURE_SUBSCRIPTION_ID"]

resource_client = ResourceManagementClient(credential, subscription_id)

resources = resource_client.resources.list(filter="tagName eq 'CostCenter' and tagValue eq '00123'")

for resource in resources:
    print(resource.name)

Om du vill hämta resurser som har ett specifikt taggnamn med valfritt taggvärde använder du:

import os
from azure.identity import AzureCliCredential
from azure.mgmt.resource import ResourceManagementClient

credential = AzureCliCredential()
subscription_id = os.environ["AZURE_SUBSCRIPTION_ID"]

resource_client = ResourceManagementClient(credential, subscription_id)

resources = resource_client.resources.list(filter="tagName eq 'Dept'")

for resource in resources:
    print(resource.name)

Om du vill hämta resursgrupper som har ett specifikt taggnamn och -värde använder du:

import os
from azure.identity import AzureCliCredential
from azure.mgmt.resource import ResourceManagementClient

credential = AzureCliCredential()
subscription_id = os.environ["AZURE_SUBSCRIPTION_ID"]

resource_client = ResourceManagementClient(credential, subscription_id)

resource_groups = resource_client.resource_groups.list(filter="tagName eq 'CostCenter' and tagValue eq '00123'")

for resource_group in resource_groups:
    print(resource_group.name)

Ta bort taggar

Om du vill ta bort specifika taggar anger du operation till Delete. Skicka resurs-ID:t för de taggar som du vill ta bort.

import os
from azure.identity import AzureCliCredential
from azure.mgmt.resource import ResourceManagementClient
from azure.mgmt.resource.resources.models import TagsPatchResource

credential = AzureCliCredential()
subscription_id = os.environ["AZURE_SUBSCRIPTION_ID"]

resource_client = ResourceManagementClient(credential, subscription_id)

resource_group_name = "demoGroup"
storage_account_name = "demostore"

tags = {
    "Dept": "IT",
    "Environment": "Test"
}

tag_patch_resource = TagsPatchResource(
    operation="Delete",
    properties={'tags': tags}
)

resource = resource_client.resources.get_by_id(
    f"/subscriptions/{subscription_id}/resourceGroups/{resource_group_name}/providers/Microsoft.Storage/storageAccounts/{storage_account_name}",
    "2022-09-01"
)

resource_client.tags.begin_update_at_scope(resource.id, tag_patch_resource)

print(f"Tags {tag_patch_resource.properties.tags} were removed from resource: {resource.id}")

De angivna taggarna tas bort.

Om du vill ta bort alla taggar använder du metoden ResourceManagementClient.tags.begin_delete_at_scope .

import os
from azure.identity import AzureCliCredential
from azure.mgmt.resource import ResourceManagementClient

credential = AzureCliCredential()
subscription_id = os.environ["AZURE_SUBSCRIPTION_ID"]

resource_client = ResourceManagementClient(credential, subscription_id)

subscription = resource_client.subscriptions.get(subscription_id)

resource_client.tags.begin_delete_at_scope(subscription.id)

Nästa steg