Problem Description
Through the Metrics monitoring page, we can know the running status and various indicators of the current resources (such as Redis). What if we need to download indicators locally or generate JSON data and import it to a third-party monitoring platform? Can Azure export various indicator data through Python code or Powershell script?
Solution
Yes! PowerShell command can use Get-AzMetric or az monitor metrics list command to obtain the Metrics value of the resource.
Get-AzMetric:Gets the metric values of a resource. https://docs.microsoft.com/en-us/powershell/module /az.monitor/get-azmetric?view=azps-5.4.0&viewFallbackFrom=azps-5.2.0
## az monitor metrics list: List the metric values for a resource. https://docs.microsoft.com/en-us/cli/azure/monitor/metrics?view=azure-cli-latest#az_monitor_metrics_list
And Using Python code, you can use Metrics' REST API to implement
Note: You must first log in to Azure to use Powershell. Use the command Connect-AzAccount -Environment AzureChinaCloud or az cloud set –name AzureChinaCloud and az login.
To use Python code, you need to first obtain the Token to access Redis Metrics. To obtain the Token, you can register an application in Azure AD, and then give the application the reader permission in Redis access control to read Metris data.
Execution steps
Python
Step 1: Register AAD application, copy application ID, client access password
- Log in to the Azure platform, enter the AAD page, click
App registrations: https://portal.azure.cn/?l=en.en-us#blade/Microsoft_AAD_IAM/ActiveDirectoryMenuBlade/RegisteredApps
- Click the "
New Registration" button, enter the application name, leave other values as default, click Save
- After the creation is successful, enter the application page , import it to the "
Certificates & secrets" page, create the Client Secret you need to use and copy it. In the third step, you need to use
- to copy the ## on the application page. #Tenant ID, Applicaiton ID
needs to be used in the third step of the code
See the following animation for the specific operation process:
Step 2: Grant permission to obtain Metrics
In the Access control (IAM) page of Redis, search through the application name in step 1 and grant permission to Monitoring Reader
Note: If permission is not granted, a similar error will be reported in the code:
##Status Code: Response Content: b'{"error":{"code":"AuthorizationFailed","message":"The client 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' with object id 'xxxxxxxx -xxxx-xxxx-xxxx-36166b5f7276' does not have authorization to perform action 'microsoft.insights/metrics/read' over scope '/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/xxxx-rg/providers/Microsoft .Cache/Redis/xxxx/providers/microsoft.insights' or the scope is invalid. If access was recently granted, please refresh your credentials."}}'
|
Step 3: Write Python code, use requests to send psot, get request
There are two main parts in the code: one is to obtain Access Token, and the other is to obtain Metrics Data
The highlighted content needs to be replaced with the corresponding resource information and the information prepared in the first step
After obtaining the Access Token In the Body content, grant_type is a fixed value, which is client_credentials. The value of resource is the management endpoint of azure in China: https://management.chinacloudapi.cn
import requestsimport json##Part 1: Get Access Tokenaadurl="https://login.chinacloudapi.cn/<your aad tenant id>/oauth2/token"aadbody={'grant_type':'client_credentials','client_id':'your aad client id','client_secret':'your aad client secret','resource':'https://management.chinacloudapi.cn'}
rtoken= requests.post(aadurl, data=aadbody)##print(rtoken)objtoken = json.loads(rtoken.text)##print(obj['access_token'])##Part 2: Get the Metrics Value by Tokenheaders = {'content-type': "application/json", 'Authorization': 'Bearer '+objtoken['access_token']
}
url= "https://management.chinacloudapi.cn/subscriptions/<subscriptions>/resourceGroups/<resourceGroups>/providers/Microsoft.Cache/Redis/<your redis name>/providers/microsoft.insights/metrics?api-version=2018-01-01&metricnames=expiredkeys,usedmemory"r = requests.get(url, headers=headers)print('Status Code: ' + str(r))print('Response Content: ' + str(r.content))
Copy after login
The operation effect is as follows:
Powershell
az cloud set --name AzureChinaCloud
az login
az monitor metrics list --resource /subscriptions/<your subscriptions>/resourceGroups/<resourceGroups>/providers/Microsoft.Cache/Redis/<your redis name> --metric usedmemory --aggregation Maximum --interval PT1M
Copy after login
The execution effect is as follows:
The above is the detailed content of How to use Python code to obtain monitoring indicator values of Azure Redis. For more information, please follow other related articles on the PHP Chinese website!