简体   繁体   English

Azure REST Api创建经典的部署模型存储帐户

[英]Azure REST Api to create classic deployment model storage account

I'm trying to create Azure storage account kind: Storage (classic) via REST APi. 我正在尝试创建Azure存储帐户类型:通过REST APi Storage (classic)

When I'm sending this request: 当我发送此请求时:

PUT https://management.azure.com/subscriptions/{{subscriptionId}}/resourceGroups/{{resourceGroupName}}/providers/Microsoft.Storage/storageAccounts/{{name}}?api-version=2019-04-01

with body: 与身体:

{
  "sku": {
    "name": "Standard_GRS"
  },
  "kind": "Storage",
  "location": "eastus2"
}

It works perfectly fine, but my created storage is kind: Storage (general purpose v1) . 它工作得很好,但是我创建的存储是一种: Storage (general purpose v1)

I've tried to send request with Microsoft.ClassicStorage like so: 我试图用Microsoft.ClassicStorage发送请求,如下所示:

PUT https://management.azure.com/subscriptions/{{subscriptionId}}/resourceGroups/{{resourceGroupName}}/providers/Microsoft.ClassicStorage/storageAccounts/{{name}}?api-version=2016-11-01

same body as before (and also tried without "kind" parameter), and I get response: 400 Bad Request 与以前相同的正文(并且也尝试不使用"kind"参数),并且得到响应: 400 Bad Request

{
    "error": {
        "code": "InvalidStorageAccountRequest",
        "message": "The storage account '{{validname}}' request is invalid."
    }
}

Any idea what should be placed in request body? 任何想法都应该放在请求正文中吗? Or is it possible to create Storage(classic) via REST API or by c# code? 还是可以通过REST API或c#代码创建Storage(经典)?

Please try by changing your request body to something like the following: 请尝试将您的请求正文更改为以下内容:

{
  "properties": {
    "accountType": "Standard-GRS"
  },
  "location": "eastus2"
}

The account kind for classic storage accounts are different than those of new storage accounts. 经典存储帐户的帐户类型与新存储帐户的帐户类型不同。 They are Standard-GRS , Standard-LRS , Standard-RAGRS , Standard-ZRS and Premium-LRS . 它们是Standard-GRSStandard-LRSStandard-RAGRSStandard-ZRSPremium-LRS

I have got this kind of issue before and it seems to be because of the name you are giving to your storage account but for me the invalid code was the one bellow: 我以前遇到过这种问题,这似乎是因为您要给存储帐户指定的名称,但是对我来说,无效的代码是一个波纹管:

Code=AccountNameInvalid 代码= AccountNameInvalid

It is not a valid storage account name. 这不是有效的存储帐户名称。 Storage account name must be between 3 and 24 characters in length and use numbers and lower-case letters only. 存储帐户名称的长度必须在3到24个字符之间,并且只能使用数字和小写字母。

you can check it out in the Azure documentation link . 您可以在Azure文档链接中进行检查

Solution (.NET) 解决方案(.NET)

Storage Account (classic) doesn't have option to "Export template", but it can be found in another place, as follow: 存储帐户(经典)没有“导出模板”选项,但可以在其他地方找到,如下所示:

  1. Go to https://portal.azure.com 前往https://portal.azure.com
  2. Create a resource (Storage Account) 创建资源(存储帐户)
  3. Click on "Choose classic deployment model" 点击“选择经典的部署模型”
  4. Chose tab "Review + create" 选择选项卡“审阅并创建”
  5. Click "Download a template for automation" 点击“下载自动化模板”

You should get two JSON files: 您应该获得两个JSON文件:

  • parameter.json (here you can change parameters values): parameter.json(您可以在此处更改参数值):
{
    "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentParameters.json#",
    "contentVersion": "1.0.0.0",
    "parameters": {
        "location": {
            "value": "westeurope"
        },
        "storageAccountName": {
            "value": "testtemplate"
        },
        "accountType": {
            "value": "Standard_GRS"
        }
    }
}
  • template.json template.json
{
    "$schema": "http://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
    "contentVersion": "1.0.0.0",
    "parameters": {
        "location": {
            "type": "string"
        },
        "storageAccountName": {
            "type": "string"
        },
        "accountType": {
            "type": "string"
        }
    },
    "variables": {},
    "resources": [
        {
            "name": "[parameters('storageAccountName')]",
            "type": "Microsoft.ClassicStorage/storageAccounts",
            "apiVersion": "2016-11-01",
            "location": "[parameters('location')]",
            "properties": {
                "accountType": "[parameters('accountType')]"
            },
            "dependsOn": []
        }
    ],
    "outputs": {}
}

And now to deploy it, you just need to past it below, with all private credentials (code is copied from Storage Account kind V2 "Export template" tab) 现在要部署它,您只需将其粘贴在下面,并保留所有私有凭据(代码是从存储帐户类型V2 “导出模板”标签中复制的)

// Requires the following Azure NuGet packages and related dependencies:
// package id="Microsoft.Azure.Management.Authorization" version="2.0.0"
// package id="Microsoft.Azure.Management.ResourceManager" version="1.4.0-preview"
// package id="Microsoft.Rest.ClientRuntime.Azure.Authentication" version="2.2.8-preview"

using Microsoft.Azure.Management.ResourceManager;
using Microsoft.Azure.Management.ResourceManager.Models;
using Microsoft.Rest.Azure.Authentication;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.IO;

namespace PortalGenerated
{
    /// <summary>
    /// This is a helper class for deploying an Azure Resource Manager template
    /// More info about template deployments can be found here https://go.microsoft.com/fwLink/?LinkID=733371
    /// </summary>
    class DeploymentHelper
    {
        string subscriptionId = "your-subscription-id";
        string clientId = "your-service-principal-clientId";
        string clientSecret = "your-service-principal-client-secret";
        string resourceGroupName = "resource-group-name";
        string deploymentName = "deployment-name";
        string resourceGroupLocation = "resource-group-location"; // must be specified for creating a new resource group
        string pathToTemplateFile = "path-to-template.json-on-disk";
        string pathToParameterFile = "path-to-parameters.json-on-disk";
        string tenantId = "tenant-id";

        public async void Run()
        {
            // Try to obtain the service credentials
            var serviceCreds = await ApplicationTokenProvider.LoginSilentAsync(tenantId, clientId, clientSecret);

            // Read the template and parameter file contents
            JObject templateFileContents = GetJsonFileContents(pathToTemplateFile);
            JObject parameterFileContents = GetJsonFileContents(pathToParameterFile);

            // Create the resource manager client
            var resourceManagementClient = new ResourceManagementClient(serviceCreds);
            resourceManagementClient.SubscriptionId = subscriptionId;

            // Create or check that resource group exists
            EnsureResourceGroupExists(resourceManagementClient, resourceGroupName, resourceGroupLocation);

            // Start a deployment
            DeployTemplate(resourceManagementClient, resourceGroupName, deploymentName, templateFileContents, parameterFileContents);
        }

        /// <summary>
        /// Reads a JSON file from the specified path
        /// </summary>
        /// <param name="pathToJson">The full path to the JSON file</param>
        /// <returns>The JSON file contents</returns>
        private JObject GetJsonFileContents(string pathToJson)
        {
            JObject templatefileContent = new JObject();
            using (StreamReader file = File.OpenText(pathToJson))
            {
                using (JsonTextReader reader = new JsonTextReader(file))
                {
                    templatefileContent = (JObject)JToken.ReadFrom(reader);
                    return templatefileContent;
                }
            }
        }

        /// <summary>
        /// Ensures that a resource group with the specified name exists. If it does not, will attempt to create one.
        /// </summary>
        /// <param name="resourceManagementClient">The resource manager client.</param>
        /// <param name="resourceGroupName">The name of the resource group.</param>
        /// <param name="resourceGroupLocation">The resource group location. Required when creating a new resource group.</param>
        private static void EnsureResourceGroupExists(ResourceManagementClient resourceManagementClient, string resourceGroupName, string resourceGroupLocation)
        {
            if (resourceManagementClient.ResourceGroups.CheckExistence(resourceGroupName) != true)
            {
                Console.WriteLine(string.Format("Creating resource group '{0}' in location '{1}'", resourceGroupName, resourceGroupLocation));
                var resourceGroup = new ResourceGroup();
                resourceGroup.Location = resourceGroupLocation;
                resourceManagementClient.ResourceGroups.CreateOrUpdate(resourceGroupName, resourceGroup);
            }
            else
            {
                Console.WriteLine(string.Format("Using existing resource group '{0}'", resourceGroupName));
            }
        }

        /// <summary>
        /// Starts a template deployment.
        /// </summary>
        /// <param name="resourceManagementClient">The resource manager client.</param>
        /// <param name="resourceGroupName">The name of the resource group.</param>
        /// <param name="deploymentName">The name of the deployment.</param>
        /// <param name="templateFileContents">The template file contents.</param>
        /// <param name="parameterFileContents">The parameter file contents.</param>
        private static void DeployTemplate(ResourceManagementClient resourceManagementClient, string resourceGroupName, string deploymentName, JObject templateFileContents, JObject parameterFileContents)
        {
            Console.WriteLine(string.Format("Starting template deployment '{0}' in resource group '{1}'", deploymentName, resourceGroupName));
            var deployment = new Deployment();

            deployment.Properties = new DeploymentProperties
            {
                Mode = DeploymentMode.Incremental,
                Template = templateFileContents,
                Parameters = parameterFileContents["parameters"].ToObject<JObject>()
            };

            var deploymentResult = resourceManagementClient.Deployments.CreateOrUpdate(resourceGroupName, deploymentName, deployment);
            Console.WriteLine(string.Format("Deployment status: {0}", deploymentResult.Properties.ProvisioningState));
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM