I am trying to add a new datasource using API and need to to be scripted. I can’t find a way to set the “token” in the InfluxDB details field.
I’ve looked and the following documentation and able to create a new influxdb datasource except the token, see snapshot below.
The curl command below works but looking from the gui, obviously “Token” field is blank. How do I set the token field using api?
curl -X POST --insecure “Authorization: Bearer <MY_TOKEN>” -H “Content-Type: application/json” -d ‘{
“name”:“InfluxDB”,
“type”:“influxdb”,
“typeName”:“InfluxDB”,
“access”:“proxy”,
“url”:“http://MY_INFLUXDB:8086”,
“basicAuth”:false,
“jsonData”: {
“defaultBucket”:“MY_BUCKET”,
“httpMode”:“POST”,
“organization”:“MY_ORG”,
“version”:“Flux”
},
“readOnly”:false
}’ http://admin:admin@community.grafana.com/api/datasources
lgki
June 17, 2021, 12:51pm
2
Here is an example of my python script, “<>” are my variables that you have to replace with yours
import requests
import json
apiKey1 = "<MyApiKey>"
token = "<MyInfluxDBToken>"
server = "http://grafana.staged-by-discourse.com/"
url = server + "api/datasources/"
headers = {"Authorization":"Bearer "+apiKey1,
"Content-Type":"application/json",
"Accept":"application/json"
}
my_json = {
"orgId":1,
"name":"InfluxDB",
"type":"influxdb",
"typeLogoUrl":"",
"access":"proxy",
"url":"http://localhost:8086",
"password":"",
"user":"",
"database":"",
"basicAuth":False,
"basicAuthUser":"",
"basicAuthPassword":"",
"withCredentials":False,
"isDefault":False,
"jsonData":{
"defaultBucket":"test_bucket",
"httpMode":"POST",
"organization":"<OrgName>",
"version":"Flux"
},
"secureJsonData":{
"token": token
},
"version":2,
"readOnly":False
}
r = requests.post(url = url.format('/api/datasources'), headers = headers, json = my_json, verify=False)
data = r.json()
print(data)
To see what you need (because it depends on your version) you can see the POST request with a valid datasource and using the GUI. In dev tools record the network to see the request.
When you get it, you can delete id, uid and replace secureJsonField with secureJsonData.
Your token have to be in secureJsonData.
I tried this and it works fine,
But I have 2 organizations with OrgID:2, I tried to change OrgId to 2, but the datasources was still added on my first organization with OrgId:1.
Have you experienced this?
yosiasz
November 3, 2023, 12:16pm
4
Are you sure the second organization’s org id is 2?
Make sure to always add try catch to your code
I get it, OrgId is assigned automatically based on Token as per documentation. So it seems like it doesn’t important in JSON anymore.