你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

使用 Azure CLI 在订阅中查找现有 Azure Cosmos DB 免费层帐户

适用对象: NoSQL MongoDB Cassandra Gremlin

本文中的脚本演示如何在订阅中找到 Azure Cosmos DB 免费层帐户。

每个 Azure 订阅最多可以有一个 Azure Cosmos DB 免费层帐户。 Azure 门户中可能已禁用创建免费层帐户的选项,或者在尝试创建免费层帐户时收到错误消息。 如果出现上述任一问题,请使用此脚本查找现有免费层帐户的名称及其所属的资源组。

如果没有 Azure 订阅,请在开始之前创建一个 Azure 免费帐户

先决条件

  • 本文需要 Azure CLI 版本 2.9.1 或更高版本。 如果使用 Azure Cloud Shell,则最新版本已安装。

示例脚本

启动 Azure Cloud Shell

Azure Cloud Shell 是免费的交互式 shell,可以使用它运行本文中的步骤。 它预安装有常用 Azure 工具并将其配置与帐户一起使用。

若要打开 Cloud Shell,只需要从代码块的右上角选择“试一试”。 也可以通过转到 https://shell.azure.com 在单独的浏览器标签页中启动 Cloud Shell。

当 Cloud Shell 打开时,请验证是否为环境选择了“Bash”。 后续会话将在 Bash 环境中使用 Azure CLI,选择“复制”以复制代码块,将其粘贴到 Cloud Shell 中,然后按 Enter 来运行它。

登录 Azure

Cloud Shell 会在登录时使用的初始帐户下自动进行身份验证。 使用以下脚本通过其他订阅登录,将 <Subscription ID> 替换为 Azure 订阅 ID。 如果没有 Azure 订阅,请在开始之前创建一个 Azure 免费帐户

subscription="<subscriptionId>" # add subscription here

az account set -s $subscription # ...or use 'az login'

有关详细信息,请参阅设置有效的订阅以交互方式登录

运行脚本

# Azure Cosmos DB offers one free-tier account per subscription
# This script will find if you have a free-tier account and output 
# the name of the Cosmos DB account and its resource group 


# These can remain commented out if running in Azure Cloud Shell

#az login
#az account set -s {your subscription id}

isFound=0

# Iterate through all the resource groups in the subscription
for rg in $(az group list --query "[].name" --output tsv) 
do

    echo "Checking resource group: $rg"
    
    # Return the Cosmos DB account in the resource group marked as free tier
    ft=$(az cosmosdb list -g $rg --query "[?enableFreeTier].name" --output tsv)
    
    if [ ${#ft} -gt 0 ]; then
        
        echo "$ft is a free tier account in resource group: $rg"
        isFound=1
        break
    
    fi

done

if [ $isFound -eq 0 ]; then
    echo "No Free Tier accounts in subscription"
fi

示例参考

此脚本使用以下命令。 表中的每条命令均链接到特定于命令的文档。

命令 说明
az group list 列出 Azure 订阅中的所有资源组。
az cosmosdb list 列出资源组中的所有 Azure Cosmos DB 帐户。

后续步骤

有关 Azure Cosmos DB CLI 的详细信息,请参阅 Azure Cosmos DB CLI 文档

有关特定 API 的 Azure CLI 示例,请参阅: