Продажи: 1-800-867-1389

Create Deployment

Обновлено: Июль 2014 г.

The Create Deployment asynchronous operation uploads a new service package and creates a new deployment in the staging or production environments.

Before you can run this operation, you must complete the following tasks:

The Create Deployment request is specified as follows. Replace <subscription-id> with your subscription ID, <cloudservice-name> with the name of the cloud service, and <deployment-slot> with staging or production.

 

Method Request URI

POST

https://management.core.windows.net/<subscription-id>/services/hostedservices/<cloudservice-name>/deploymentslots/<deployment-slot>

You must make sure that the request that is made to the management service is secure. For additional details, see Authenticating Service Management Requests.

The following table describes the request headers.

 

Request Header Description

Content-Type

Required. Set this header to application/xml.

x-ms-version

Required. Specifies the version of the operation to use for this request. This header should be set to 2009-10-01 or higher. For more information about versioning headers, see Работа с версиями при управлении службами.

The format of the request body is as follows:


<?xml version="1.0" encoding="utf-8"?>
<CreateDeployment xmlns="http://schemas.microsoft.com/windowsazure">
  <Name>deployment-name</Name>
  <PackageUrl>package-url-in-blob-storage</PackageUrl>
  <Label>base64-encoded-deployment-label</Label>
  <Configuration>base64-encoded-configuration-file</Configuration>
  <StartDeployment>start-deployment</StartDeployment>
  <TreatWarningsAsError>prioritize-warnings</TreatWarningsAsError>
  <ExtendedProperties>
    <ExtendedProperty>
      <Name>property-name</Name>
      <Value>property-value</Value>
    </ExtendedProperty>
  </ExtendedProperties>
  <ExtensionConfiguration>
    <AllRoles>
      <Extension>
        <Id>identifier-of-extension</Id>
        <State>state-of-extension</State>
      </Extension>
    </AllRoles>
    <NamedRoles>
      <Role>
        <RoleName>role_name1</RoleName>
        <Extensions>
          <Extension>
            <Id>identifier-of-extension</Id>
            <State>state-of-extension</State>
          </Extension>
        </Extensions>
      </Role>
    </NamedRoles>
  </ExtensionConfiguration>
</CreateDeployment>

The following table describes the elements in the request body.

 

Element name Description

Name

Required. Specifies the name of the deployment.

PackageUrl

Required. Specifies a URL that refers to the location of the service package in the Blob service. The service package can be located either in a storage account beneath the same subscription or a Shared Access Signature (SAS) URI from any storage account. For more info about Shared Access Signatures, see Делегирование доступа с помощью подписанного URL-адреса.

Configuration

Required. Specifies the base-64 encoded service configuration file for the deployment.

Label

Required. Specifies an identifier for the deployment that is base-64 encoded. The identifier can be up to 100 characters in length. It is recommended that the label be unique within the subscription. The label can be used for your tracking purposes.

StartDeployment

Optional. Indicates whether to start the deployment immediately after it is created. The default value is false.

If false, the service model is still deployed, but the code is not run immediately. Instead, the service is Suspended until you call Update Deployment Status and set the status to Running, at which time the service will be started. A deployed service still incurs charges, even if it is suspended.

The StartDeployment element is only available using version 2010-04-01 or higher.

TreatWarningsAsError

Optional. Indicates whether to treat package validation warnings as errors. The default value is false. If set to true, the Created Deployment operation fails if there are validation warnings on the service package.

The TreatWarningsAsError element is only available using version 2011-04-01 or higher.

Name

Optional. Specifies the name of an extended deployment property. Each extended property must have both a defined name and value. You can have a maximum of 25 extended property name and value pairs.

The maximum length of the Name element is 64 characters, only alphanumeric characters and underscores are valid in the Name, and the name must start with a letter.

The Name element is only available using version 2012-03-01 or higher.

Value

Optional. Specifies the value of an extended cloud service property. Each extended property must have both a defined name and value. You can have a maximum of 25 extended property name and value pairs, and each extended property value has a maximum length of 255 characters.

The Value element is only available using version 2012-03-01 or higher.

ExtensionConfiguration

Optional. Specifies an extension that is added to the cloud service. In Azure, a process can run as an extension of a cloud service. You must add an extension to the cloud service by using Добавление расширения before it can be added to the deployment.

The ExtensionConfiguration element is only available using version 2013-03-01 or higher.

Specifies an extension that is added to the cloud service.

 

Element name Description

AllRoles

Optional. Specifies a list of extensions that are applied to all roles in a deployment.

Extension

Required. Specifies an extension that is to be deployed to a role in a cloud service.

NamedRoles

Optional. Specifies a list of extensions that are applied to specific roles in a deployment.

Specifies an extension that is to be deployed to a role in a cloud service.

 

Element name Description

Id

Required. Specifies the identifier of the extension. The identifier is created when the extension is added to the cloud service. You can find the identifier of an extension that was added to a cloud service by using Перечисление расширений.

State

Optional. Specifies the state of the extension. This element only applies to JSON configured extensions.

Possible values are:

  • Enable

  • Disable

  • Uninstall

The default value is Enable.

The State element is only available using version 2014-06-01 or higher.

Specifies a list of extensions that are applied to specific roles in a deployment.

 

Element name Description

Role

Required. Specifies a specific role to which the extension is added.

RoleName

Required. Specifies the name of the role.

Extension

Required. Specifies an extension that is to be deployed to a role in a cloud service.

The response includes an HTTP status code and a set of response headers.

A successful operation returns status code 200 (OK). For information about status codes, see Service Management Status and Error Codes.

The response for this operation includes the following headers. The response may also include additional standard HTTP headers. All standard headers conform to the HTTP/1.1 protocol specification.

 

Response Header Description

x-ms-request-id

A value that uniquely identifies a request made against the management service. For an asynchronous operation, you can call Get Operation Status with the value of the header to determine whether the operation is complete, has failed, or is still in progress.

The following console application example shows you how to deploy an application. Replace the following variable values:

  • Thumbprint – with the thumbprint of a management certificate in your subscription

  • SubscriptionId – with the subscription identifier that you obtained from the Management Portal

  • ServiceName – with the name of the cloud service that you created

  • DeploymentName – with the name that you want to use for the deployment



    noteПримечание
    You can use List Locations to obtain the appropriate location.

  • PackageName – with the path in Blob storage to the package file

  • ConfigFile – with the name of the service configuration file


using System;
using System.Collections.Generic;
using System.Xml.Linq;
using System.Text;
using System.Security.Cryptography.X509Certificates;
using System.Net;
using System.IO;
using System.Xml;

namespace CreateDeployment
{
  class Program
  {
    private static XNamespace wa = "http://schemas.microsoft.com/windowsazure";
    private const string Thumbprint = "certificate-thumbprint";
    private const string SubscriptionId = "identifier-of-subscription";
    private const string ServiceName = "name-of-cloud-service";
    private const string DeploymentName = "name-of-deployment-name";
    private const string PackageName = "location-of-package";
    private const string ConfigFile = "name-of-configuration-file";
    private const string Version = "2013-08-01";

    static void Main(string[] args)
    {
      // Set the certificate that matches the Thumbprint value.
      X509Certificate2 certificate = GetStoreCertificate(Thumbprint);
      
       // Create the URI for the request
      string uriFormat = "https://management.core.windows.net/{0}/" +
        "services/hostedservices/{1}/deploymentslots/production";
      Uri uri = new Uri(String.Format(uriFormat, SubscriptionId, ServiceName));
      
      // Base-64 encode the label of the deployment   
      byte[] bytes = System.Text.Encoding.UTF8.GetBytes(ServiceName);
      string base64Label = Convert.ToBase64String(bytes);

       // Create the request body
      XDocument requestBody = new XDocument(
      new XDeclaration("1.0", "UTF-8", "no"),
        new XElement(wa + "CreateDeployment",
          new XElement(wa + "Name", DeploymentName),
          new XElement(wa + "PackageUrl", PackageName),
          new XElement(wa + "Label", base64Label),
          new XElement(wa + "Configuration", ConvertFile(ConfigFile)),
          new XElement(wa + "StartDeployment", true)));

       // Submit the request and get the response
      XDocument responseBody;
      HttpWebResponse response = InvokeRequest(uri, "POST", certificate, requestBody, out responseBody);
      string requestId = String.Empty;
      if (response.Headers != null)
      {
        requestId = response.Headers["x-ms-request-id"];
      }

      if (responseBody != null)
      {
        Console.WriteLine(responseBody.ToString(SaveOptions.OmitDuplicateNamespaces));
      }
      
      XDocument statusResponse = GetStatus(requestId);
      if (statusResponse != null)
      {
        Console.WriteLine(statusResponse.ToString(SaveOptions.OmitDuplicateNamespaces));
      }
      Console.Write("Press any key to continue:");
      Console.ReadKey();
    }

    //Get the status of the request    
    private static XDocument GetStatus(string requestId)
    {
      // Set the certificate that matches the Thumbprint value.
      X509Certificate2 certificate = GetStoreCertificate(Thumbprint);
      
       // Create the URI for the request
      string uriFormat = "https://management.core.windows.net/{0}/" + "operations/" + requestId;
      Uri uri = new Uri(String.Format(uriFormat, SubscriptionId));
      HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
      request.Method = "GET";
      request.Headers.Add("x-ms-version", Version);
      request.ClientCertificates.Add(certificate);
      request.ContentType = "application/xml";

       // Submit the request and get the response
      XDocument responseBody = null;
      HttpWebResponse response;
      try
      {
        response = (HttpWebResponse)request.GetResponse();
      }
      catch (WebException ex)
      {
        response = (HttpWebResponse)ex.Response;
      }

      if (response.ContentLength > 0)
      {
        using (XmlReader reader = XmlReader.Create(response.GetResponseStream()))
        {
          responseBody = XDocument.Load(reader);
        }
      }
      response.Close();
      return responseBody;
    }
        
    // Add the request headers and get the response from the request
    private static HttpWebResponse InvokeRequest(
      Uri uri,
      string method,
      X509Certificate2 certificate,
      XDocument requestBody,
      out XDocument responseBody)
    {
      HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
      request.Method = method;
      request.Headers.Add("x-ms-version", Version);
      request.ClientCertificates.Add(certificate);
      request.ContentType = "application/xml";

      if (requestBody != null)
      {
        using (Stream requestStream = request.GetRequestStream())
        {
          using (StreamWriter streamWriter = new StreamWriter(
            requestStream, System.Text.UTF8Encoding.UTF8))
          {
            requestBody.Save(streamWriter, SaveOptions.DisableFormatting);
          }
        }
      }

      responseBody = null;
      HttpWebResponse response;
      try
      {
        response = (HttpWebResponse)request.GetResponse();
      }
      catch (WebException ex)
      {
        response = (HttpWebResponse)ex.Response;
      }

      XmlReaderSettings settings = new XmlReaderSettings();
      settings.DtdProcessing = DtdProcessing.Ignore;
      if (response.ContentLength > 0)
      {
        using (XmlReader reader = XmlReader.Create(response.GetResponseStream(), settings))
        {
          try
          {
            responseBody = XDocument.Load(reader);
          }
          catch
          {
            responseBody = null;
          }
        }
      }
      response.Close();
      return response;
    }
    
    // Base-64 encode the contents of the service configuration file.
    private static string ConvertFile(string configFileName)
    {
      string fileContents;
      string base64String = "";
      try
      {
        using (StreamReader reader = new StreamReader(
          File.Open(configFileName, System.IO.FileMode.Open, System.IO.FileAccess.Read)))
        {
          fileContents = reader.ReadToEnd();
        }
      }
      catch (System.Exception exp)
      {
        Console.WriteLine(exp.Message);
        return base64String;
      }

      // Convert the binary input into base-64 encoded output. 
      try
      {
        base64String = Convert.ToBase64String(Encoding.UTF8.GetBytes(fileContents));
        return base64String;
      }
      catch (System.ArgumentNullException)
      {
        Console.WriteLine("Binary data array is null.");
        return base64String;
      }
    }

    // Gets the certificate matching the thumbprint from the local store.
    // Throws an ArgumentException if a matching certificate is not found.
    private static X509Certificate2 GetStoreCertificate(string thumbprint)
    {
      List<StoreLocation> locations = new List<StoreLocation>
      { 
        StoreLocation.CurrentUser, 
        StoreLocation.LocalMachine
      };

      foreach (var location in locations)
      {
        X509Store store = new X509Store("My", location);
        try
        {
          store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
          X509Certificate2Collection certificates = store.Certificates.Find(
            X509FindType.FindByThumbprint, thumbprint, false);
          if (certificates.Count == 1)
          {
            return certificates[0];
          }
        }
        finally
        {
          store.Close();
        }
      }
      throw new ArgumentException(string.Format(
        "A Certificate with Thumbprint '{0}' could not be located.",
        thumbprint));
    }
  }
}

Была ли вам полезна эта информация?
(1500 символов осталось)
Спасибо за ваш отзыв
Корпорация Майкрософт проводит интернет-опрос, чтобы выяснить ваше мнение о веб-сайте MSDN. Если вы желаете принять участие в этом интернет-опросе, он будет отображен при закрытии веб-сайта MSDN.

Вы хотите принять участие?
Показ:
© 2014 Microsoft