Condividi tramite


Rigenerare le chiavi dell'account di archiviazione

 

L'operazione asincrona Regenerate Keys rigenera la chiave di accesso primaria o secondaria per l'account di archiviazione specificato.

Richiesta

La richiesta di Regenerate Keys può essere specificata come indicato di seguito. Sostituire <subscription-id> con l'ID sottoscrizione e <service-name> con il nome dell'account di archiviazione desiderato.

Metodo URI della richiesta
POST https://management.core.windows.net/<subscription-id>/services/storageservices/<service-name>/keys?action=regenerate

È necessario verificare che la richiesta eseguita al servizio di gestione sia sicura. Per ulteriori dettagli, vedere l'autenticazione di richieste di gestione del servizio.

Parametri URI

Parametro URI Descrizione
action=regenerate Obbligatorio. Specifica che la chiave di accesso primaria o secondaria per l'account di archiviazione specificato deve essere rigenerata.

Intestazioni della richiesta

La tabella seguente descrive le intestazioni della richiesta.

Intestazione della richiesta Descrizione
Content-Type Obbligatorio. Impostare questa intestazione su application/xml.
x-ms-version Obbligatorio. Specifica la versione dell'operazione da usare per questa richiesta. Questa intestazione deve essere impostata su 2009-10-01 o versione successiva. Per ulteriori informazioni sulle intestazioni di controllo delle versioni, vedere il controllo delle versioni di Service Management.

Corpo della richiesta

Il corpo della richiesta indica la chiave da rigenerare, la chiave primaria o la chiave secondaria. Il formato del corpo della richiesta è il seguente:

  
<?xml version="1.0" encoding="utf-8"?> <RegenerateKeys xmlns="https://schemas.microsoft.com/windowsazure"> <KeyType>Primary|Secondary</KeyType> </RegenerateKeys>  
  

Nella tabella indicata di seguito vengono descritti gli elementi del corpo della richiesta.

Nome elemento Descrizione
KeyType Specifica quale chiave rigenerare. I valori validi sono:

- Principale
- Secondario

Risposta

Nella risposta sono inclusi un codice di stato HTTP, un set di intestazioni per la risposta e il corpo di una risposta.

Codice di stato

Un'operazione completata correttamente restituisce 200 (OK). Per informazioni sui codici di stato, vedere stato di gestione del servizio e i codici di errore.

Intestazioni della risposta

Nella risposta per questa operazione sono incluse le intestazioni riportate di seguito; inoltre, possono essere incluse intestazioni HTTP standard aggiuntive. Tutte le intestazioni standard sono conformi alla specifica del protocollo HTTP/1.1.

Intestazione della risposta Descrizione
x-ms-request-id Valore che identifica in modo univoco una richiesta eseguita nel servizio di gestione. Per un'operazione asincrona, è possibile chiamare Ottenere lo stato di operazione con il valore dell'intestazione per determinare se l'operazione è stata completata, ha avuto esito negativo o è ancora in corso.

Corpo della risposta

La risposta restituisce le chiavi di accesso primarie e secondarie. Il formato del corpo della risposta è il seguente:

  
<?xml version="1.0" encoding="utf-8"?> <StorageService xmlns="https://schemas.microsoft.com/windowsazure"> <Url>storage-service-request-uri</Url> <StorageServiceKeys> <Primary>primary-key</Primary> <Secondary>secondary-key</Secondary> </StorageServiceKeys> </StorageService>  
  

Nella tabella indicata di seguito vengono descritti gli elementi del corpo della risposta.

Nome elemento Descrizione
URL URI della richiesta API di gestione dei servizi usato per eseguire le richieste Recupero delle proprietà dell'account di archiviazione nell'account di archiviazione.
Principale La chiave primaria dell'account di archiviazione specificato.
Secondario La chiave secondaria dell'account di archiviazione specificato.

Osservazioni

L'operazione Regenerate Storage Account Keys causa la rigenerazione della chiave di accesso primaria o secondaria per un servizio dell'account di archiviazione. Questa operazione può essere utilizzata con gli account di archiviazione restituiti dall'operazione Elenco degli account di archiviazione, per automatizzare la gestione degli aggiornamenti della chiave di archiviazione.

Esempio

Il programma di esempio seguente accetta l'ID sottoscrizione, un'identificazione personale del certificato di gestione associato, la stringa di versione dell'operazione e il nome dell'account di archiviazione, quindi stampa le chiavi di accesso dell'account di archiviazione restituite sulla console. Chiama quindi l'operazione Regenerate Storage Account Keys per rigenerare la chiave di accesso secondaria per l'account di archiviazione e stampa i risultati della nuova chiave. Per eseguire il codice di esempio inizializzare la costante Version con una stringa dell'intestazione della versione, SubscriptionId con l'identificatore GUID per la sottoscrizione, Thumbprint e il valore di identificazione personale del certificato di gestione e ServiceName con il nome dell'account di archiviazione.

namespace Microsoft.WindowsAzure.ServiceManagementRESTAPI.Samples { using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Security.Cryptography.X509Certificates; using System.Xml; using System.Xml.Linq; public class Program { // Set these constants with your values to run the sample. private const string Version = "2011-10-01"; private const string Thumbprint = "management-certificate-thumbprint"; private const string SubscriptionId = "subscription-id-guid"; private const string ServiceName = "storage-account-name"; // This is the common namespace for all Service Management REST API XML data. private static XNamespace wa = "https://schemas.microsoft.com/windowsazure"; /// <summary> /// Gets or sets the certificate that matches the Thumbprint value. /// </summary> private static X509Certificate2 Certificate { get; set; } static void Main(string[] args) { try { Certificate = GetCertificate(Thumbprint); XElement initialKeys = GetStorageAccountKeys(SubscriptionId, ServiceName); Console.WriteLine( "Storage Account Keys for {0}:{1}{2}", ServiceName, Environment.NewLine, initialKeys.ToString(SaveOptions.OmitDuplicateNamespaces)); string keyType = "Secondary"; XElement regeneratedKeys = RegenerateStorageAccountKeys(SubscriptionId, ServiceName, keyType); Console.WriteLine( "Regenerated {0} Storage Account Key for {1}:{2}{3}", keyType, ServiceName, Environment.NewLine, regeneratedKeys.ToString(SaveOptions.OmitDuplicateNamespaces)); } catch (Exception ex) { Console.WriteLine("Exception caught in Main:"); Console.WriteLine(ex.Message); } Console.Write("Press any key to continue:"); Console.ReadKey(); } /// <summary> /// Gets the certificate matching the thumbprint from the local store. /// Throws an ArgumentException if a matching certificate is not found. /// </summary> /// <param name="thumbprint">The thumbprint of the certificate to find.</param> /// <returns>The certificate with the specified thumbprint.</returns> private static X509Certificate2 GetCertificate(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)); } /// <summary> /// Calls the Get Storage Account Keys operation in the Service Management /// REST API for the specified subscription and storage account name and returns /// the StorageService XML element from the response. /// </summary> /// <param name="subscriptionId">The subscription identifier.</param> /// <param name="serviceName">The name of the storage account.</param> /// <returns>The StorageService XML element from the response.</returns> private static XElement GetStorageAccountKeys( string subscriptionId, string serviceName) { string uriFormat = "https://management.core.windows.net/{0}" + "/services/storageservices/{1}/keys"; Uri uri = new Uri(String.Format(uriFormat, subscriptionId, serviceName)); XDocument responseBody; string requestId; HttpStatusCode statusCode = InvokeRequest(uri, "GET", null, out responseBody, out requestId); VerifyResult(uri, statusCode, HttpStatusCode.OK, responseBody); return responseBody.Element(wa + "StorageService"); } /// <summary> /// Calls the Regenerate Storage Account Keys operation in the Service /// Management REST API for the specified subscription, storage account name, /// and key, and returns the StorageService XML element from the response. /// </summary> /// <param name="subscriptionId">The subscription identifier.</param> /// <param name="serviceName">The name of the storage account.</param> /// <param name="keyType">A value of "Primary" or "Secondary" to specify the key to regenerate.</param> /// <returns>The StorageService XML element from the response.</returns> private static XElement RegenerateStorageAccountKeys( string subscriptionId, string serviceName, string keyType) { string uriFormat = "https://management.core.windows.net/{0}" + "/services/storageservices/{1}/keys?action=regenerate"; Uri uri = new Uri(String.Format(uriFormat, subscriptionId, serviceName)); XDocument requestBody = new XDocument( new XDeclaration("1.0", "UTF-8", "no"), new XElement( wa + "RegenerateKeys", new XElement(wa + "KeyType", keyType))); XDocument responseBody; string requestId; HttpStatusCode statusCode = InvokeRequest(uri, "POST", requestBody, out responseBody, out requestId); VerifyResult(uri, statusCode, HttpStatusCode.OK, responseBody); return responseBody.Element(wa + "StorageService"); } /// <summary> /// A helper function to invoke a Service Management REST API operation. /// </summary> /// <param name="uri">The URI of the operation to invoke using a web request.</param> /// <param name="method">The method of the web request, GET, PUT, POST, or DELETE.</param> /// <param name="requestBody">The XML body to send with the web request. Use null to send no request body.</param> /// <param name="responseBody">The XML body returned by the request, if any.</param> /// <param name="requestId">The requestId returned by the request, if any.</param> /// <returns>The status code returned by the request.</returns> private static HttpStatusCode InvokeRequest( Uri uri, string method, XDocument requestBody, out XDocument responseBody, out string requestId) { responseBody = null; requestId = String.Empty; 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); } } } HttpWebResponse response; HttpStatusCode statusCode = HttpStatusCode.Unused; try { response = (HttpWebResponse)request.GetResponse(); } catch (WebException ex) { // GetResponse throws a WebException for 4XX and 5XX status codes response = (HttpWebResponse)ex.Response; } try { statusCode = response.StatusCode; if (response.ContentLength > 0) { using (XmlReader reader = XmlReader.Create(response.GetResponseStream())) { responseBody = XDocument.Load(reader); } } if (response.Headers != null) { requestId = response.Headers["x-ms-request-id"]; } } finally { response.Close(); } return statusCode; } /// <summary> /// A helper function to throw an ApplicationException on unexpected /// status code responses from Service Management REST API operation calls. /// </summary> /// <param name="uri">The URI of the Service Management operation.</param> /// <param name="statusCode">The status code returned by the operation.</param> /// <param name="expectedCode">The expected status code.</param> /// <param name="responseBody">The response body returned by the operation.</param> private static void VerifyResult( Uri uri, HttpStatusCode statusCode, HttpStatusCode expectedCode, XDocument responseBody) { if (!statusCode.Equals(expectedCode)) { throw new ApplicationException(string.Format( "Call to {0} returned an error:{1}Status Code: {2} ({3}):{1}{4}", uri.ToString(), Environment.NewLine, (int)statusCode, statusCode, responseBody.ToString(SaveOptions.OmitDuplicateNamespaces))); } return; } } }  
  

Questo programma di esempio genera risultati simili al seguente:

Storage Account Keys for myexamplestorage1: <StorageService xmlns="https://schemas.microsoft.com/windowsazure" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"> <Url>https://management.core.windows.net/01234567-89ab-cdef-0123-456789abcdef/services/storageservices/myexamplestorage1</Url> <StorageServiceKeys> <Primary>XrmGWqu6qpgKX5G3lf+V5Bc0nFIGjGWiWhHTdMxkA5Mb4WjJ0rDV+3USWW/9fAWCrszrkr8+JUb1c5mxQdq4nw==</Primary> <Secondary>7jGHqUXHfASoUWeuClG9TXRZ59tTl5Fep8BNi5f86LFuewc0dQjDc6pyyju8BOi5947byrtgKnVtYO4f4cVdcg==</Secondary> </StorageServiceKeys> </StorageService> Regenerated Secondary Storage Account Key for myexamplestorage1: <StorageService xmlns="https://schemas.microsoft.com/windowsazure" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"> <Url>https://management.core.windows.net/01234567-89ab-cdef-0123-456789abcdef/services/storageservices/myexamplestorage1</Url> <StorageServiceKeys> <Primary>XrmGWqu6qpgKX5G3lf+V5Bc0nFIGjGWiWhHTdMxkA5Mb4WjJ0rDV+3USWW/9fAWCrszrkr8+JUb1c5mxQdq4nw==</Primary> <Secondary>2Wd7lP3MesbkFi0LAltwUd40L6uu85N9VBtokOo2RfpqKA8q39orkJ6WUV3jP4TkZuYrSQNYxkQ5axcSzzTu8A==</Secondary> </StorageServiceKeys> </StorageService> Press any key to continue: