通过 Azure CLI 在资源创建阶段设置标签

Posted

技术标签:

【中文标题】通过 Azure CLI 在资源创建阶段设置标签【英文标题】:Setting up tags on resource creation stage through Azure CLI 【发布时间】:2018-11-22 08:28:12 【问题描述】:

可以通过 Azure CLI 命令在 Azure 中创建资源:

az functionapp create                               \
    --name                "function-name"           \
    --resource-group      "resource-group-name"     \
    --storage-account     "gl0unique0storage0name"

及以后 - 作为下一步 - 在separate command 设置标签中:

az resource tag --tags "environment=development"   \
    --name               "function-name"           \
    --resource-group     "resource-group-name"

这会将标签“environment”设置为“development”。

如果一个人强制执行一项订阅策略,以便在每个资源上都有一个特定的标签。 必须在创作时设置标签。 文档说可以通过 ARM 模板实现。

Q1(复杂):如何通过 Azure CLI 在任何资源类型创建步骤上设置标签? Q2:我至少可以为 Azure Function 执行此操作,因为 documentation 说我可以吗?

当我尝试关注第二季度链接的文档时,使用以下命令:

az functionapp create                               \
    --name                "function-name"           \
    --resource-group      "resource-group-name"     \
    --storage-account     "gl0unique0storage0name"  \
    --tags                "environment=development"

我收到此错误:az: error: unrecognized arguments: --tags environment=development

【问题讨论】:

【参考方案1】:

Q1(复杂):如何通过 Azure CLI 在任何资源类型创建步骤上设置标签?

AFAIK,您可以使用 Azure Policy 来执行此操作,请遵循此文档:Apply tag and its default value。

Sample for CLI:

# Create the Policy Definition (Subscription scope)
definition=$(az policy definition create --name 'apply-default-tag-value' --display-name 'Apply tag and its default value' --description 'Applies a required tag and its default value if it is not specified by the user' --rules 'https://raw.githubusercontent.com/Azure/azure-policy/master/samples/built-in-policy/apply-default-tag-value/azurepolicy.rules.json' --params 'https://raw.githubusercontent.com/Azure/azure-policy/master/samples/built-in-policy/apply-default-tag-value/azurepolicy.parameters.json' --mode All)

# Set the scope to a resource group; may also be a subscription or management group
scope=$(az group show --name 'YourResourceGroup')

# Set the Policy Parameter (JSON format)
policyparam=' "tagName":  "value": "costCenter" , "tagValue":  "value": "headquarter"  '

# Create the Policy Assignment
assignment=$(az policy assignment create --name 'apply-default-tag-value' --display-name 'Apply tag and its default value Assignment' --scope `echo $scope | jq '.id' -r` --policy `echo $definition | jq '.name' -r` --params "$policyparam")

Q2:我至少可以为 Azure Function 执行此操作,因为文档说我可以吗?

是的,你可以,该命令看起来不错,请确保您使用最新版本的 CLI,或者您可以尝试下面的命令 az functionapp create -g joywebapp -p joyplan -n joytest1111 -s joystoragev2 --tags 'environment=development',它在我这边运行良好。

【讨论】:

以上是关于通过 Azure CLI 在资源创建阶段设置标签的主要内容,如果未能解决你的问题,请参考以下文章

Azure CLI - 删除资源而不删除资源组

使用Azure CLI创建Linux虚拟机

我如何使用curl请求使用CLI通过yaml文件创建Azure管道?

使用 azure cli/bash 在 Azure VM 的“实时”数据磁盘上更新缓存设置

创建没有标记的资源组时 Azure Policy 的奇怪行为

Azure 策略要求创建某个标记,但不使用默认值?