powershell script to retrieve logs from applications insights - api

https://api.applicationinsights.io/v1/query
I am using above endpoint to send a post request in powershell script and getting errors in below script.
# Set the ID of the Application Insights resource you want to query
$appId = "app id"
# Set the access token for the Application Insights resource
$accessToken = "access token"
# Encode the access token as a URL-safe string
$accessToken = [System.Uri]::EscapeDataString($accessToken)
# Set the query you want to execute
$query = "customEvents"
# Construct the request body for the Application Insights query endpoint
$requestBody = #{
appId = $appId
query = $query
} | ConvertTo-Json
# Execute the query and retrieve the results
$queryResponse = Invoke-WebRequest -Method POST -Uri "https://api.applicationinsights.io/v1/query" -Headers #{
"Authorization" = "Bearer $accessToken"
"Content-Type" = "application/json"
} -Body $requestBody
# Extract the results from the response
$results = $queryResponse.Content | ConvertFrom-Json
# Print the results
$results
ERROR :
Invoke-WebRequest : {"error":{"message":"The requested path does not exist","code":"PathNotFoundError","correlationId":"1e33e5cd-43a4-4108-b28d-0b0ef4c3942c"}}
At line:26 char:18
+ ... yResponse = Invoke-WebRequest -Method POST -Uri "https://api.applicat ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand
The access token i am generating through postman for testing purpose and it is correct. Query is just customevents, not sure what is the issue here.
Edit: 9 Jan 2023
Granted read permission like this api permission but getting below error
Invoke-WebRequest : {"error":{"message":"The provided credentials have insufficient access to perform the requested operation","code":"InsufficientAccessError","correlationId":

I tried to reproduce the same in my environment and got below results:
I registered one Azure AD application and granted API permissions like below:
Now I generated the access token via Postman with below parameters:
POST https://login.microsoftonline.com/<tenantID>/oauth2/v2.0/token
grant_type:client_credentials
client_id: <appID>
client_secret: <secret>
scope: https://api.applicationinsights.io/.default
Response:
I got the ID of the Application Insights resource from here:
When I ran the same code by including above details, I got same error as below:
# Set the ID of the Application Insights resource you want to query
$appId = "xxxxxxxxxxxxxxxx"
# Set the access token for the Application Insights resource
$accessToken = "xxxxxxxxxxxxxxxxxxx"
# Encode the access token as a URL-safe string
$accessToken = [System.Uri]::EscapeDataString($accessToken)
# Set the query you want to execute
$query = "customEvents"
# Construct the request body for the Application Insights query endpoint
$requestBody = #{
appId = $appId
query = $query
} | ConvertTo-Json
# Execute the query and retrieve the results
$queryResponse = Invoke-WebRequest -Method POST -Uri "https://api.applicationinsights.io/v1/query" -Headers #{
"Authorization" = "Bearer $accessToken"
"Content-Type" = "application/json"
} -Body $requestBody
# Extract the results from the response
$results = $queryResponse.Content | ConvertFrom-Json
# Print the results
$results
Response:
To resolve the error, modify your code by changing the request URI like below:
# Set the ID of the Application Insights resource you want to query
$appId = "ID"
# Set the access token for the Application Insights resource
$accessToken = "token"
# Encode the access token as a URL-safe string
$accessToken = [System.Uri]::EscapeDataString($accessToken)
# Set the query you want to execute
$query = "customEvents"
# Construct the request body for the Application Insights query endpoint
$requestBody = #{
query = $query
} | ConvertTo-Json
# Execute the query by giving right URI and retrieve the results
$queryResponse = Invoke-WebRequest -Method POST -Uri "https://api.applicationinsights.io/v1/apps/$appID/query" -Headers #{
"Authorization" = "Bearer $accessToken"
"Content-Type" = "application/json"
} -Body $requestBody
# Extract the results from the response
$results = $queryResponse.Content | ConvertFrom-Json
# Print the results
$results
Response:
When I ran $queryResponse, I got the results of the query successfully like below:
Reference: Query - Execute - REST API (Azure Application Insights)
UPDATE:
You are getting InsufficientAccessError as Data.Read permission is removed like below:
If API permissions are removed, they will appear under Other permissions granted for tenant till their admin consent is revoked.
To resolve the error, make sure to add Data.Read permission again and grant admin consent to it.

Related

Create Azure Purview collection using API and Powershell

This is the first time I am working with API.
I am trying to create a purview subcollection using API and powershell.
$tenantID = "XXXXXXXXXXXXXXXXXXXXXXX"
$url = "https://login.microsoftonline.com/$tenantID/oauth2/token"
$params = #{ client_id = "XXXXXXXXXXXXXXXXXXXXXXX"; client_secret = "XXXXXXXXXXXXXXXXXXXXXXXXX"; grant_type = "client_credentials"; resource = ‘https://purview.azure.net’ }
$bearertoken = Invoke-WebRequest $url -Method Post -Body $params -UseBasicParsing | ConvertFrom-Json
$accesstoken = ConvertTo-SecureString $bearertoken.access_token -AsPlainText -Force
$purviewendpoint = "https://testpurview.purview.azure.com/account"
$url = "$purviewendpoint/collections/newcollection1?api-version=2019-11-01-preview"
$childcollection = #"
{
"parentCollection": {
"referenceName": "**testpurview**"
}
}
"#
Invoke-RestMethod -Method PUT -Uri $url -Body $childcollection -Token $accesstoken
Steps I tried:
Created a bearer token.
Created a variable for access_token from bearer token.
newcollection1: new subcollection which I want to create.
testpurview : This is the root collection of my Purview account.
Can someone help me if this is the correct way to create collection?

Getting Invalid JWT when creating project

When I get the token from the itwin-developer-console, the below PowerShell works. However, when I generate my own token, which appears to be valid per all the parsing I do of it, I get 401 Invalid JWT. I can use the token I generate to query and manipulate work area connections with no problems as long as I provide the product-settings-service scope. I've limited the scopes to just be projects:read projects:modify like the token I get from the console, but no joy. I notice that my token does not populate entitlements. Could that be it?
$url = "https://api.bentley.com/projects/"
$authVal = "Bearer $($oidcClientToken.access_token)"
$today = Get-Date -Format "yyyy-MM-dd"
$projectName = $today + " " + (Get-RandomString -Length 12 -Characters "ABCDEFGHIJKLMNOPQRSTUVWXYZ")
$bodyCreate = ConvertTo-Json -Depth 4 #{
project = #{
displayName = $projectName
projectNumber = $projectName
industry = "Oil and Gas"
projectType = "Offshore Structures"
billingCountry = "US"
status = "active"
allowExternalTeamMembers = $true
}
}
$resp5 = Invoke-RestMethod -ContentType "Application/Json" -Method Post -Uri $url -Body $bodyCreate -Headers #{'Authorization' = $authVal; 'Content-Type' = 'application/json'; 'Accept' = 'application/vnd.bentley.itwin-platform.v1+json' }
You need a different token for calling iTwin Platform APIs, please read the Authorization documentation on this.
Specifically in this case, the token needs to be issued by https://ims.bentley.com instead of https://imsoidc.bentley.com, which is currently used by itwin.js applications. The same client will work.

Azure Data Factory API Connector

I am trying to access an application via API REST but I am stuck in the process using ADF.
Basically this process consists in 2 steps.
1 - Getting a session (https://horizon.akixi.com/CCS/API/v1/session)
2 - Authenticating (https://horizon.akixi.com/CCS/API/v1/login?locale=en_GB") using Username and Password.
I have created a Linked Service (Rest) and set the Base URL as (https://horizon.akixi.com/CCS/API/v1/session)
Authentication Anonymous.
Then I create a Data Set to point this API and finally I create a "Copy Data" and tried to set on the Additional Header the authentication's details, but it is not working, I got an error 405.
Basically I can run the below script using Powershell and it is working as expected, but is required to use it on ADF instead.
The script in Powershell is this one.
$user = "xxxxxx#mail.com"
$pass = "123456789"
$secpasswd = ConvertTo-SecureString $pass -AsPlainText -Force
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user,$pass)))
#Get Session
$url = "https://horizon.akixi.com/CCS/API/v1/session"
$response = Invoke-RestMethod -uri $url -Method Post -SessionVariable se
#Authentication
Write-Host "Authenticating" -ForegroundColor Green
$headers = #{
'Authorization' = "Basic $base64AuthInfo"
}
$headers
$url = "https://horizon.akixi.com/CCS/API/v1/login?locale=en_GB"
$response = Invoke-RestMethod -uri $url -Headers $headers -Method Get -WebSession $se
#List Reports
$url = "https://horizon.akixi.com/CCS/API/v1/report"
$response = Invoke-RestMethod -uri $url -Method Get -WebSession $se
$response
Thank you all.
As the 3 steps are separate, and only the last one fetches data, you should break up the process into multiple activities.
Use Web Activity for the first two steps,
https://horizon.akixi.com/CCS/API/v1/session
https://horizon.akixi.com/CCS/API/v1/login?locale=en_GB"
extract the session variable or Authentication from the web activities. Pass it to the copy activity. The copy activity should target
https://horizon.akixi.com/CCS/API/v1/report

EDIT the Azure databrics cluster's SPARK configuration using PowerShell and REST API

I am trying to EDIT the Azure databrics cluster's SPARK configuration using PowerShell and REST API. However I am getting an error which I am unable to understand/fix. I have provided the 'required' fields as parameters, however, the error states that I haven't passed them
CODE:
$DBAPIRootUrl = "dec" # example: https://uksouth.azuredatabricks.net
$DBAPIKey = "abc" # Example dapi601e67891a9d1f7886e40916479aaa
[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12
$ClustersAPIListUrl = $DBAPIRootUrl.Trim('/') + "/api/2.0/clusters/list"
$ClustersAPIEditUrl = $DBAPIRootUrl.Trim('/') + "/api/2.0/clusters/edit"
$headers = #{
Authorization = "Bearer $DBAPIKey"
"Content-Type" = "application/json"
}
$response = Invoke-WebRequest -Uri $ClustersAPIListUrl -Method GET -Headers $headers #-Body $parameters
$json_response = ($response.Content | ConvertFrom-Json)
$jsonDoc = [pscustomobject]#{
cluster_id = $json_response.clusters.cluster_id
spark_version = $json_response.clusters.spark_version
node_type_id = $json_response.clusters.node_type_id
spark_conf = "
javax.jdo.option.ConnectionPassword
datanucleus.fixedDatastore false
javax.jdo.option.ConnectionURL jdbc:sqlserver://metadatasrvr.database.windows.net:1433;database=emptydb
datanucleus.schema.autoCreateAll true
spark.hadoop.hive.metastore.schema.verification false
datanucleus.autoCreateSchema true
spark.sql.hive.metastore.jars maven
javax.jdo.option.ConnectionDriverName com.microsoft.sqlserver.jdbc.SQLServerDriver
spark.sql.hive.metastore.version 1.2.0
javax.jdo.option.ConnectionUserName"
}
$jsonDoc | ConvertTo-Json
#$parameters | ConvertTo-Json
$response = Invoke-WebRequest -Uri $ClustersAPIEditUrl -Method POST -Headers $headers -Body $jsonDoc
ERROR:
Invoke-WebRequest : {"error_code":"INVALID_PARAMETER_VALUE","message":"Missing required fields: cluster_id, size"}
At line:21 char:13
+ $response = Invoke-WebRequest -Uri $ClustersAPIEditUrl -Method POST - ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand
The error message clearly explains ""error_code":"INVALID_PARAMETER_VALUE","message":"Missing required fields: cluster_id, size"}".
Note: While editing Databricks cluster, make sure to pass the "cluster_id" and "node_type_id" as a mandatory expecting fields.
To Edit the configuration of a cluster to match the provided attributes and size.
An example request:
{
"cluster_id": "1202-211320-brick1",
"num_workers": 10,
"spark_version": "5.3.x-scala2.11",
"node_type_id": "Standard_D3_v2"
}
Reference: Databricks - REST API EDIT clusters
Hope this helps.

PowerShell Invoke-WebRequest error with Go Daddy API

Following a script (from here) that many others have suggested works OK, I am having an error that is just outside my ability to understand. I am novice-to-intermediate with Power Shell and just beginning with API's.
The script is:
$domain = 'example.com' # your domain
$name = 'xyz' # name of the A record to update
$key = 'myKey # key for godaddy developer API
$secret = 'mySecret' # Secret for godday developer API
$headers = #{}
$headers["Authorization"] = 'sso-key ' + $key + ':' + $secret
$result = Invoke-WebRequest https://api.godaddy.com/v1/domains/$domain/records/A/$name -method get -headers $headers
$content = ConvertFrom-Json $result.content
$dnsIp = $content.data
# Get public ip address
$currentIp = Invoke-RestMethod http://ipinfo.io/json | Select -exp ip
# THE CODE WORKS FINE UP TO HERE
if ( $currentIp -ne $dnsIp) {
$Request = #{ttl=3600;data=$currentIp }
$JSON = Convertto-Json $request
# THE FOLLOWING LINE FAILS WITH THE ERROR NOTED BELOW
Invoke-WebRequest https://api.godaddy.com/v1/domains/$domain/records/A/$name -method put -headers $headers -Body $json -ContentType "application/json"
}
The following error is returned for the final Invoke-WebRequest:
Invoke-WebRequest : {"code":"INVALID_BODY","fields":[{"code":"UNEXPECTED_TYPE","message":"is not a array","path":"records"}],"message":"Request body doesn't fulfill schema, see details in `fields`"}
At C:\tfsCode\tfs\api.ps1:25 char:5
+ Invoke-WebRequest https://api.godaddy.com/v1/domains/$domain/reco ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand
The Go Daddy reference page for the Get API is here and for the Put API is here.
The PUT API documentation says it’s expecting the body to be an array. This is also what the error message is saying. Try changing this line:
$Request = #{ttl=3600;data=$currentIp }
to
$Request = #(#{ttl=3600;data=$currentIp })
#() creates an array in PowerShell, when converted to JSON it will still be an array
#{} creates a hashtable in PowerShell, when converted to JSON it will be an object