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

后端 未结 3 1033
挽巷
挽巷 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;
        }
    
    0 讨论(0)
  • 2021-01-12 20:56

    Consider using Get Cloud Service in the service management API. When you supply the service that your roles are a part of, you can retrieve a response similar to the following. Note the location field that I've starred.

    <?xml version="1.0" encoding="utf-8"?>
    <HostedService xmlns="http://schemas.microsoft.com/windowsazure">
      <Url>hosted-service-url</Url>
      <ServiceName>hosted-service-name</ServiceName>
      <HostedServiceProperties>
        <Description>description</Description>
        <AffinityGroup>name-of-affinity-group</AffinityGroup> 
        **<Location>location-of-service</Location >**
        <Label>base-64-encoded-name-of-service</Label>
        <Status>current-status-of-service</Status>
        <DateCreated>creation-date-of-service</DateCreated>
        <DateLastModified>last-modification-date-of-service</DateLastModified>
        <ExtendedProperties>
          <ExtendedProperty>
            <Name>name-of-property</Name>
            <Value>value-of-property</Value>
          </ExtendedProperty>
        </ExtendedProperties>
        <GuestAgentType>type-of-guest-agent</GuestAgentType>
      </HostedServiceProperties>
      <DefaultWinRmCertificateThumbprint>thumbprint-of-winrm-certificate</DefaultWinRmCertificateThumbprint>
    </HostedService>
    
    0 讨论(0)
  • 2021-01-12 21:08

    That information is available from the Azure Instance Metadata Service (IMDS). The REST endpoint for any VM running in the Azure public cloud is http://169.254.169.254/metadata/instance?api-version=2017-04-02. The metadata object contains two sub-objects, one for "compute" and one for "network". The region name appears in the "location" member of the "compute" object.

    Sample code in multiple languages for accessing various elements of IMDS data are available from the Microsoft/azureimds repo on github. Far more information than I show here is available through the 2018-10-01 version of the IMDS API; see IMDS docs for details.

    $ curl -s -H Metadata:True "http://169.254.169.254/metadata/instance?api-version=2017-04-02&format=json" | jq .
    {
      "compute": {
        "location": "westus2",
        "name": "samplevm",
        "offer": "UbuntuServer",
        "osType": "Linux",
        "platformFaultDomain": "0",
        "platformUpdateDomain": "0",
        "publisher": "Canonical",
        "sku": "18.04-LTS",
        "version": "18.04.201904020",
        "vmId": "(redacted)",
        "vmSize": "Standard_D2s_v3"
      },
      "network": {
        "interface": [
          {
            "ipv4": {
              "ipAddress": [
                {
                  "privateIpAddress": "10.0.0.7",
                  "publicIpAddress": ""
                }
              ],
              "subnet": [
                {
                  "address": "10.0.0.0",
                  "prefix": "24"
                }
              ]
            },
            "ipv6": {
              "ipAddress": []
            },
            "macAddress": "(redacted)"
          }
        ]
      }
    }
    
    0 讨论(0)
提交回复
热议问题