As you are using curl, I thought it may be helpful for me to extend the previous answer with some additional context specific to curl. To help you transition from using instrumentation keys to using Azure Active Directory (Azure AD) authentication for retrieving data from Application Insights with curl
, here is a detailed explanation along with relevant samples.
Transitioning from Instrumentation Keys to Azure AD Authentication
Step 1: Register an Application in Azure AD
- Go to the Azure portal and navigate to Azure Active Directory.
- Select App registrations and click on New registration.
- Provide a name for the application and click Register.
- Once registered, note down the Application (client) ID and Directory (tenant) ID.
Step 2: Configure API Permissions
- In the registered application, go to API permissions.
- Click on Add a permission and select APIs my organization uses.
- Search for Application Insights and select it.
- Choose Application permissions and select Telemetry.Read.
- Click Add permissions and then Grant admin consent.
Step 3: Create a Client Secret
- In the registered application, go to Certificates & secrets.
- Click on New client secret and provide a description.
- Set an expiration period and click Add.
- Note down the Value of the client secret as it will be used in the
curl
command.
Step 4: Retrieve Data Using curl
- Obtain an access token using the client credentials flow.
- Use the access token to make requests to the Application Insights API.
Here is a sample script to achieve this:
# Variables
TENANT_ID="your-tenant-id"
CLIENT_ID="your-client-id"
CLIENT_SECRET="your-client-secret"
RESOURCE="https://api.applicationinsights.io"
APP_ID="your-application-insights-app-id"
# Get the access token
ACCESS_TOKEN=$(curl -X POST -H "Content-Type: application/x-www-form-urlencoded" \
-d "grant_type=client_credentials&client_id=$CLIENT_ID&client_secret=$CLIENT_SECRET&resource=$RESOURCE" \
"https://login.microsoftonline.com/$TENANT_ID/oauth2/token" | jq -r '.access_token')
# Use the access token to query Application Insights
curl -X GET -H "Authorization: Bearer $ACCESS_TOKEN" \
"https://api.applicationinsights.io/v1/apps/$APP_ID/metrics/requests/duration?timespan=P1D&interval=PT1H"
The key in this example is that once you have retrieved the access token, you need to add it in the authorization header of subsequent calls using the -H
argument.