Udostępnij za pośrednictwem


Stosowanie tagów przy użyciu języka Python

W tym artykule opisano sposób używania języka Python do tagowania zasobów, grup zasobów i subskrypcji. Aby uzyskać zalecenia i ograniczenia dotyczące tagów, zobacz Organizowanie zasobów platformy Azure i hierarchii zarządzania przy użyciu tagów.

Wymagania wstępne

  • Zainstalowano środowisko Python w wersji 3.8 lub nowszej. Aby zainstalować najnowszą wersję, zobacz Python.org

  • Następujące pakiety bibliotek platformy Azure dla języka Python zainstalowane w środowisku wirtualnym. Aby zainstalować dowolne pakiety, użyj polecenia pip install {package-name}

    • azure-identity
    • azure-mgmt-resource

    Jeśli masz już zainstalowane starsze wersje tych pakietów w środowisku wirtualnym, może być konieczne ich zaktualizowanie za pomocą polecenia pip install --upgrade {package-name}

  • Przykłady w tym artykule używają uwierzytelniania opartego na interfejsie wiersza polecenia (AzureCliCredential). W zależności od środowiska może być konieczne uruchomienie az login pierwszego uruchomienia w celu uwierzytelnienia.

  • Zmienna środowiskowa z identyfikatorem subskrypcji platformy Azure. Aby uzyskać identyfikator subskrypcji platformy Azure, użyj:

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

    Aby ustawić wartość, użyj opcji dla środowiska.

    setx AZURE_SUBSCRIPTION_ID your-subscription-id
    

    Uwaga

    Jeśli musisz uzyskać dostęp tylko do zmiennej środowiskowej w bieżącej uruchomionej konsoli, możesz ustawić zmienną środowiskową z wartością setsetxzamiast .

    Po dodaniu zmiennych środowiskowych może być konieczne ponowne uruchomienie wszystkich uruchomionych programów, które będą musiały odczytać zmienną środowiskową, w tym okno konsoli. Jeśli na przykład używasz programu Visual Studio jako edytora, uruchom ponownie program Visual Studio przed uruchomieniem przykładu.

Stosowanie tagów

Język Azure Python oferuje metodę ResourceManagementClient.tags.begin_create_or_update_at_scope do stosowania tagów. Zastępuje wszystkie tagi zasobu, grupy zasobów lub subskrypcji. Po wywołaniu polecenia przekaż identyfikator zasobu jednostki, którą chcesz oznaczyć.

Poniższy przykład stosuje zestaw tagów do konta magazynu:

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}")

Jeśli ponownie uruchomisz polecenie, ale tym razem z różnymi tagami zwróć uwagę, że wcześniejsze tagi znikną.

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

Aby dodać tagi do zasobu, który ma już tagi, użyj ResourceManagementClient.tags.begin_update_at_scope. W obiekcie TagsPatchResource ustaw operation parametr na Mergewartość .

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}")

Zwróć uwagę, że istniejące tagi rosną wraz z dodaniu dwóch nowych tagów.

Każda nazwa tagu może mieć tylko jedną wartość. Jeśli podasz nową wartość tagu, zastąpi starą wartość, nawet jeśli używasz operacji scalania. Poniższy przykład zmienia Status tag z Normalny na Zielony.

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}")

Po ustawieniu parametru operation na Replacewartość nowy zestaw tagów zastępuje istniejące tagi.

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}")

Tylko nowe tagi pozostają w zasobie.

Te same polecenia działają również z grupami zasobów lub subskrypcjami. Przekaż je w identyfikatorze grupy zasobów lub subskrypcji, którą chcesz oznaczyć. Aby dodać nowy zestaw tagów do grupy zasobów, użyj:

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}")

Aby zaktualizować tagi dla grupy zasobów, użyj:

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}")

Aby zaktualizować tagi dla subskrypcji, użyj:

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}")

Być może istnieje więcej niż jeden zasób o tej samej nazwie w grupie zasobów. W takim przypadku można ustawić każdy zasób za pomocą następujących poleceń:

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}")

Tworzenie listy tagów

Aby uzyskać tagi zasobu, grupy zasobów lub subskrypcji, użyj metody ResourceManagementClient.tags.get_at_scope i przekaż identyfikator zasobu jednostki.

Aby wyświetlić tagi zasobu, użyj:

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)

Aby wyświetlić tagi dla grupy zasobów, użyj:

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)

Aby wyświetlić tagi subskrypcji, użyj:

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)

Wyświetlanie listy według tagu

Aby uzyskać zasoby, które mają określoną nazwę i wartość tagu, użyj:

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)

Aby uzyskać zasoby, które mają określoną nazwę tagu z dowolną wartością tagu, użyj:

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)

Aby uzyskać grupy zasobów, które mają określoną nazwę i wartość tagu, użyj:

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)

Usuwanie tagów

Aby usunąć określone tagi, ustaw wartość operationDelete. Przekaż identyfikatory zasobów tagów, które chcesz usunąć.

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}")

Określone tagi są usuwane.

Aby usunąć wszystkie tagi, użyj metody 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)

Następne kroki