How to programatically know the current region in an azure role?

后端 未结 3 1049
挽巷
挽巷 2021-01-12 20:09

I need to programmatically find the current region (e.g \"West US\" or \"East US\") where my current role is running. Is there any API to find this?

3条回答
  •  無奈伤痛
    2021-01-12 20:49

    You can only get that information if you use the Management Api.

    Either by REST or you can use the c# Windows Azure Management Libraries (Prerelease on nuget).

    But due note that you need to set up management certificates to get the information.

    An easier alternative is to create a setting in your cloud service and set the values when you create the deployment configuration. I do this and have deployment configurations for the regions I target.

        using( var azure = CloudContext.Clients.CreateComputeManagementClient(...))
        {
           var service = await  azure.HostedServices.GetDetailedAsync("servicename");
          //   service.Properties.Location
          //  service.Properties.AffinityGroup;
    
        }
        using(var azure = CloudContext.Clients.CreateManagementClient(...))
        {
          var affinityGroup = await  azure.AffinityGroups.GetAsync("name",new CancellationToken());
          //  affinityGroup.Location
        }
    

    Here ... is the credentials, either a management certificate or your WAAD oauth tokens. (ADAL : Active Directory Authentication Library) can be used for tokens.

    here is the code for getting credentials from a certificate:

        public static CertificateCloudCredentials GetCertificateCloudCredentials(
            string certificateThumbprint, string subscriptionId)
        {
            var certificate = CertificateHelper.LoadCertificate(
                StoreName.My,
                StoreLocation.LocalMachine,
                certificateThumbprint);
    
            if (certificate == null)
                throw new Exception(
                    string.Format("Certificate with thumbprint '{0}' not found",
                    certificateThumbprint));
    
            var cred = new CertificateCloudCredentials(
                subscriptionId,
                certificate
             );
            return cred;
        }
    

提交回复
热议问题