This repository was archived by the owner on Jan 24, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathget_or_create_token.py
44 lines (38 loc) · 1.56 KB
/
get_or_create_token.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import httplib
import sys
import json
import argparse
from base64 import b64encode
URI = "/api/auth/keys"
parser = argparse.ArgumentParser()
parser.add_argument("--user", default="admin", help="login for basic authentication")
parser.add_argument("--passwd", default="admin", help="password for basic authentication")
parser.add_argument("--host", default="127.0.0.1", help="Grafana host address")
parser.add_argument("--port", default="3000", help="Grafana listen port")
args = parser.parse_args()
cred = "%s:%s" % (args.user, args.passwd)
HEADERS = {"Content-Type": "application/json", "Authorization": "Basic %s" % b64encode(cred).decode('ascii')}
http = httplib.HTTPConnection(args.host, args.port)
http.request("GET", URI, headers=HEADERS)
response = http.getresponse()
if response.status != 200:
print response.read()
tokens = json.loads(response.read())
token_id = None
for token in tokens:
if token.get("name") == "ansible-module":
token_id = token.get('id')
if token_id:
http = httplib.HTTPConnection(args.host, args.port)
http.request("DELETE", "%s/%d" % (URI, token_id), headers=HEADERS)
response = http.getresponse()
if response.status != 200:
print "Failed to remove 'ansible-module' token [%s]" % response.read()
sys.exit(1)
http = httplib.HTTPConnection(args.host, args.port)
http.request("POST", URI, '{"name": "ansible-module", "role": "Editor"}', headers=HEADERS)
response = http.getresponse()
if response.status != 200:
print "Failed to create 'ansible-module' token"
sys.exit(1)
print json.loads(response.read())["key"]