以编程方式启动服务器并部署API

时间:2017-06-09 21:27:16

标签: c# azure .net-core

我使用.NET Core(C#)并创建API。根据我们的应用程序,我们知道什么时候会有高低时间,因此我们希望抢先启动具有额外api端点的服务器。有没有办法以API的方式编程部署新服务器并准备就绪?

我们将持续运行一个(管理员/主服务器)服务器来处理可能正在通过cron作业观看的部署。

任何提示都会有所帮助。我们是否创建了一个克隆的基础服务器?我们的zip是否需要上传?

1 个答案:

答案 0 :(得分:0)

首先,我建议您尝试使用VMSS启用自动缩放。

虚拟机规模集是Azure计算资源,可用于部署和管理一组相同的VM。在所有VM配置相同的情况下,扩展集旨在支持真正的自动缩放,并且不需要预先配置VM。因此,构建针对大型计算,大数据和容器化工作负载的大规模服务更容易。

更多细节,您可以参考此article

  

有没有办法以编程方式部署新服务器并启动API并准备就绪?

据我所知,我们有多种方法可以部署新VM并启动它。

我建议你可以使用C#代码来使用azure fluent api或azure模板进行部署。

更多细节,您可以参考此fluent code sample

注意:无论使用流畅的api或azure模板,您首先需要创建Azure Active Directory应用程序和服务主体。生成服务主体后,您可以获取applicationid,访问密钥和talentid。更多细节,您可以参考此article

  

我们是否创建了一个克隆的基础服务器?我们的zip是否需要上传?

在我看来,我建议您可以创建当前虚拟机的托管映像。

然后,可以使用流畅的api或azure模板部署将图像用于创建多个VM。所有这些VM都具有相同的C盘,因此它将包含所有相同的设置。

更多细节,您可以参考以下步骤:

1.您可以先安装并设置虚拟机。

2.您可以按照此article创建图片。

创建图像后,您将找到如下图像资源:

enter image description here

3.单击图像资源并创建VM。

enter image description here

4.Notice:您需要选择与基本VM的网络安全组相同的网络安全组。

enter image description here

5.下载模板。

enter image description here

6.然后,您可以使用C#代码使用模板部署VM。

代码如下:

// 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));
        }
    }
}