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?
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)"
}
]
}
}