Compartilhar via


Aplicar marcas com o Python

Este artigo descreve como usar o Python para marcar recursos, grupos de recursos e assinaturas. Para obter recomendações e limitações de marcas, consulte Usar marcas para organizar sua hierarquia de recursos e gerenciamento do Azure.

Pré-requisitos

  • Python 3.8 ou posterior instalado. Para instalar o mais recente, confira Python.org

  • Os seguintes pacotes da biblioteca do Azure para Python instalados em seu ambiente virtual. Para instalar qualquer um dos pacotes, use pip install {package-name}

    • azure-identity
    • azure-mgmt-resource

    Se você tiver versões mais antigas desses pacotes já instaladas em seu ambiente virtual, talvez seja necessário atualizá-los com pip install --upgrade {package-name}

  • Os exemplos nesse artigo usam a autenticação baseada em CLI (AzureCliCredential). Dependendo do seu ambiente, talvez seja necessário executar az login primeiro para autenticar.

  • Uma variável de ambiente com sua ID de assinatura do Azure. Para obter sua ID de assinatura do Azure, use:

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

    Para definir o valor, use a opção para seu ambiente.

    setx AZURE_SUBSCRIPTION_ID your-subscription-id
    

    Observação

    Se for necessário somente acessar a variável de ambiente no console em execução atual, você poderá definir a variável de ambiente com set em vez de setx.

    Depois de adicionar as variáveis de ambiente, talvez seja necessário reiniciar todos os programas em execução que precisarem ler a variável de ambiente, incluindo a janela do console. Por exemplo, se estiver usando o Visual Studio como seu editor, reinicie-o antes de executar o exemplo.

Aplicar marcas

O Python do Azure oferece o método ResourceManagementClient.tags.begin_create_or_update_at_scope para aplicar marcas. Ele substitui todas as marcas no recurso, no grupo de recursos ou na assinatura. Ao chamar do comando, passe a ID de recurso da entidade que deseja marcar.

O exemplo a seguir aplica um conjunto de marcas a uma conta de armazenamento:

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

Se executar o comando novamente, mas desta vez com marcas diferentes, observe que as marcas anteriores desaparecem.

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

Para adicionar as marcas a um recurso que já tem marcas, use ResourceManagementClient.tags.begin_update_at_scope. No objeto TagsPatchResource, defina o operation parâmetro como 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}")

Observe que as marcas existentes crescem com a adição das duas novas marcas.

Cada nome de marca pode ter apenas um valor. Se você fornecer um novo valor para uma marca, ele substituirá o valor antigo mesmo que você use a operação de mesclagem. O exemplo a seguir altera a marca de Status de Normal para Verde.

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

Quando você define o parâmetro operation como Replace, o novo conjunto de marcas substitui as marcas existentes.

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

Somente as novas marcas permanecem no recurso.

Os mesmos comandos também funcionam com grupos de recursos ou assinaturas. Passe-os no identificador do grupo de recursos ou assinatura que deseja marcar. Para adicionar um novo conjunto de marcas a um grupo de recursos, use:

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

Para atualizar as marcas para um grupo de recursos, use:

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

Para atualizar as marcas de uma assinatura, use:

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

É possível ter mais de um recurso com o mesmo nome em um grupo de recursos. Nesse caso, é possível definir cada recurso com os seguintes comandos:

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

Listar marcas

Para obter as marcas de um recurso, grupo de recursos ou assinatura, use o método ResourceManagementClient.tags.get_at_scope e passe a ID do recurso para a entidade.

Para consultar as marcas para um tipo de recurso, use:

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)

Para consultar as marcas para um grupo de recursos, use:

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)

Para consultar as marcas de uma assinatura, use:

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)

Listar por marca

Para obter recursos que têm um nome e valor de marca específicos, use:

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)

Para obter recursos que têm um nome específico e um valor de marca qualquer, use:

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)

Para obter grupos recursos que têm um nome e valor de marca específicos, use:

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)

Remover Marcas

Para remover marcas específicas, defina operation como Delete. Passe as IDs de recurso das marcas que deseja excluir.

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

As marcas especificadas são removidas.

Para remover todas as marcas, use o método 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)

Próximas etapas