Files
Guillaume BOURGEOIS 1ca5597453 feat(servicenow): new ServiceNow ITSM integration
31 commands: ticket lifecycle (create/update/resolve/delete, comments,
work notes, links, tags, journal notes, attachments), generic table
records CRUD and discovery, CMDB/user/group queries, service catalog
ordering, standard change from template, AWA queue routing, generic
API call, plus get_incidents ingestion with a bundled OCSF mapper.
Basic or OAuth 2.0 (password grant) authentication, stdlib-only scripts.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 22:48:50 +02:00

94 lines
3.6 KiB
Python

import base64, json, os, sys, urllib.parse, urllib.request, urllib.error
def _cfg():
return json.loads(os.environ.get("INTEGRATION_SECRETS", "{}"))
def _headers(cfg):
h = {"Accept": "application/json", "Content-Type": "application/json"}
if str(cfg.get("auth_type") or "basic").lower() == "oauth":
data = urllib.parse.urlencode({
"grant_type": "password",
"client_id": cfg.get("client_id", ""),
"client_secret": cfg.get("client_secret", ""),
"username": cfg.get("username", ""),
"password": cfg.get("password", ""),
}).encode("utf-8")
req = urllib.request.Request(
cfg.get("url", "").rstrip("/") + "/oauth_token.do", data=data,
headers={"Content-Type": "application/x-www-form-urlencoded", "Accept": "application/json"}, method="POST")
with urllib.request.urlopen(req, timeout=60) as r:
tok = json.loads(r.read())
if not tok.get("access_token"):
raise Exception("OAuth token request failed: " + json.dumps(tok))
h["Authorization"] = "Bearer " + tok["access_token"]
else:
cred = (cfg.get("username", "") + ":" + cfg.get("password", "")).encode("utf-8")
h["Authorization"] = "Basic " + base64.b64encode(cred).decode("ascii")
return h
def request(method, path, params=None, body=None, root="/api/now", versioned=True):
cfg = _cfg()
v = str(cfg.get("api_version") or "").strip().strip("/")
url = cfg.get("url", "").rstrip("/") + root + ("/" + v if v and versioned else "") + path
q = {k: str(x) for k, x in (params or {}).items() if x not in (None, "")}
if q:
url += "?" + urllib.parse.urlencode(q)
data = json.dumps(body).encode("utf-8") if body is not None else None
req = urllib.request.Request(url, data=data, headers=_headers(cfg), method=method)
with urllib.request.urlopen(req, timeout=90) as r:
raw = r.read()
return json.loads(raw) if raw else {}
def split_fields(s, prefix_custom=False):
out = {}
for part in str(s or "").split(";"):
if "=" not in part:
continue
k, v = part.split("=", 1)
k = k.strip()
if prefix_custom and k and not k.startswith("u_"):
k = "u_" + k
if k:
out[k] = v
return out
NAMED_FIELDS = [
"short_description", "description", "urgency", "impact", "priority", "state",
"category", "subcategory", "caller_id", "assigned_to", "assignment_group",
"comments", "work_notes", "close_code", "close_notes",
]
def main():
inputs = json.loads(os.environ.get("INTEGRATION_INPUTS", "{}"))
ticket_id = str(inputs.get("id") or "")
if not ticket_id:
raise Exception("id is required")
table = str(inputs.get("ticket_type") or _cfg().get("ticket_type") or "incident")
body = {}
for k in NAMED_FIELDS:
v = inputs.get(k)
if v not in (None, ""):
body[k] = v
body.update(split_fields(inputs.get("fields")))
body.update(split_fields(inputs.get("custom_fields"), prefix_custom=True))
if not body:
raise Exception("nothing to update")
params = {"sysparm_input_display_value": "true"} if inputs.get("input_display_value") else None
print(json.dumps(request("PATCH", "/table/" + urllib.parse.quote(table) + "/" + urllib.parse.quote(ticket_id), params=params, body=body)))
try:
main()
except urllib.error.HTTPError as e:
print(json.dumps({"error": "HTTP " + str(e.code), "detail": e.read().decode("utf-8", "replace")}))
sys.exit(1)
except Exception as e:
print(json.dumps({"error": str(e)}))
sys.exit(1)