Skip to content

Commit

Permalink
Snow issue402 (#404)
Browse files Browse the repository at this point in the history
* bumping version to force rebuild

* Change to private account

* #402: Adding logic for action

* #402: fix step.yaml syntax

* #402: smaller SVG icon

* 402: new smaller logo in svg format

* #402: adding code for closing CR

* : use all CAPS for parameters to get consistency

* #402: Fixing python script
Adding code for modifying a CR as well

* #402: test for empty CR_DATA

* #402: test for empty CR_DATA

* #402: test for empty CR_DATA

* #402: test for empty CR_DATA

* #402: step.yaml syntax?

* #402: remvoing blank lines

* #402: fix go template syntax with eq instead of ==

* #402: fix conflict between CR_ACTION to the step and ACTION to the script

* more debug info

* #402: more debug info

* #402: push overwrite of env variable to the end of the block

* #402: minor debug info fixes

* #402: change DEBUG to boolean

* #402: change DEBUG to boolean

* #402: debug info on action

* #402: debug info on action

* #402: debug info on action

* #402: debug info on action

* #402: debug info

* : exit with non-zero on error

* : exit with non-zero on error

* #402: fixed DEBUG var issue

* #402: fixed DEBUG var issue

* Fixing URL in annotation

* #402: link to CR from the step fixed

* #402: reverto to Codefresh official setup - vs. my own private

* #402: Ted notes
remove venonalog.json
Fix branch name for icon
Fix first line

* Ted notes
  • Loading branch information
lrochette authored Oct 14, 2021
1 parent c7af690 commit c1769f0
Show file tree
Hide file tree
Showing 4 changed files with 252 additions and 62 deletions.
Binary file removed incubating/.DS_Store
Binary file not shown.
14 changes: 14 additions & 0 deletions incubating/service-now/images/servicenow-2.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
175 changes: 143 additions & 32 deletions incubating/service-now/lib/snow.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import json
import requests

DEBUG = True
API_NAMESPACE=409723
env_file_path = "/meta/env_vars_to_export"

Expand All @@ -19,33 +18,35 @@ def processCallbackResponse(response):
if (response.status_code != 200 and response.status_code != 201):
print("Callback creation failed with code %s" % (response.status_code))
print("Error: " + response.text)
return response.status_code
sys.exit(response.status_code)

print("Callback creation successful")


def processChangeRequestResponse(response):

print("Processing answer from CR creation REST call")
print("Change Request returned code %s" % (response.status_code))
def processCreateChangeRequestResponse(response):
if DEBUG:
print("Processing answer from CR creation REST call")
print(" Change Request returned code %s" % (response.status_code))
if (response.status_code != 200 and response.status_code != 201):
print("Change Request creation failed with code %s" % (response.status_code))
print("Error: " + response.text)
return response.status_code
print(" Change Request creation failed with code %s" % (response.status_code))
print(" ERROR: " + response.text)
sys.exit(response.status_code)

print("Change Request creation successful")
print(" Change Request creation successful")
data=response.json() # json.loads(response.text)
CR_NUMBER=data["result"]["number"]
CR_SYSID=data["result"]["sys_id"]
FULL_JSON=json.dumps(data, indent=2)
print(f"Change Request Number: {CR_NUMBER}")
print(f"Change Request sys_id: {CR_SYSID}")
print("Change Request full answer:\n" + FULL_JSON)

print(f" Change Request Number: {CR_NUMBER}")
print(f" Change Request sys_id: {CR_SYSID}")
if DEBUG:
print( " Change Request full answer:\n" + FULL_JSON)

if os.path.exists(env_file_path):
env_file = open(env_file_path, "a")
env_file.write(f"CR_NUMBER={CR_NUMBER}\n")
env_file.write(f"CR_SYS_ID={CR_SYSID}\n")
env_file.write(f"CR_SYSID={CR_SYSID}\n")
env_file.write("CR_FULL_JSON=/codefresh/volume/servicenow-cr.json\n")
env_file.close()

Expand All @@ -55,35 +56,107 @@ def processChangeRequestResponse(response):

#
# Call SNow REST API to create a new Change Request
# Fields required are past in the data
def createChangeRequest(user, password, baseUrl, title, data, description):
# Fields required are pasted in the data
def createChangeRequest(user, password, baseUrl, data):

if DEBUG:
print("Entering createChangeRequest:")
print("Body: " + data)

if (bool(data)):
crBody=json.loads(data)
if DEBUG:
print("Data: " + data)
else:
crBody= {}

if DEBUG:
print(" Data: None")
crBody["cf_build_id"] = os.getenv('CF_BUILD_ID')


url="%s/now/table/change_request" % (baseUrl)

if DEBUG:
print(f"Entering createChangeRequest:")
print(f"URL: {url}")
print(f"User: {user}")
print(f"Body: {crBody}")
print(f" URL: {url}")
print(f" User: {user}")
print(f" Body: {crBody}")

resp=requests.post(url,
json = crBody,
headers = {"content-type":"application/json"},
auth=(user, password))
processChangeRequestResponse(response=resp)
processCreateChangeRequestResponse(response=resp)

def processModifyChangeRequestResponse(response, action):

if DEBUG:
print("Processing answer from CR %s REST call" %(action))
print(" %s Change Request returned code %s" % (action,response.status_code))
if (response.status_code != 200 and response.status_code != 201):
print(" %s Change Request creation failed with code %s" % (action, response.status_code))
print(" ERROR: " + response.text)
sys.exit(response.status_code)

print(" %s Change Request successful" %(action))
data=response.json() # json.loads(response.text)
FULL_JSON=json.dumps(data, indent=2)

if (action == "close" ):
jsonVar="CR_CLOSE_FULL_JSON"
jsonFileName="/codefresh/volume/servicenow-cr-close.json"
elif (action == "update" ):
jsonVar="CR_UPDATE_FULL_JSON"
jsonFileName="/codefresh/volume/servicenow-cr-update.json"
else:
print("ERROR: action unknown. Should not be here. Error should have been caught earlier")
if os.path.exists(env_file_path):
env_file = open(env_file_path, "a")
env_file.write(f"{jsonVar}=/codefresh/volume/servicenow-cr-close.json\n")
env_file.close()

json_file=open("/codefresh/volume/servicenow-cr-close.json", "w")
json_file.write(FULL_JSON)
json_file.close()

# Call SNow REST API to close a CR
# Fields required are pasted in the data
def closeChangeRequest(user, password, baseUrl, sysid, code, notes, data):
if DEBUG:
print("Entering closeChangeRequest:")
print(f"DATA: {data}")
if (bool(data)):
crBody=json.loads(data)
else:
crBody= {}
crBody["state"] = 3
crBody["close_code"] = code
crBody["close_notes"] = notes
url="%s/now/table/change_request/%s" % (baseUrl, sysid)
resp=requests.patch(url,
json = crBody,
headers = {"content-type":"application/json"},
auth=(user, password))
processModifyChangeRequestResponse(response=resp, action="close")

# Call SNow REST API to update a CR
# Fields required are pasted in the data
def updateChangeRequest(user, password, baseUrl, sysid, data):
if DEBUG:
print("Entering updateChangeRequest:")
print(f"DATA: {data}")
if (bool(data)):
crBody=json.loads(data)
else:
crBody= {}
print("WARNING: CR_DATA is empty. What are you updating exactly?")

url="%s/now/table/change_request/%s" % (baseUrl, sysid)
if DEBUG:
print(f" update CR URL: {url}")
resp=requests.patch(url,
json = crBody,
headers = {"content-type":"application/json"},
auth=(user, password))
processModifyChangeRequestResponse(response=resp, action="update")
# Use rest API to call scripted REST API to start a flow that will wait for CR
# to be approved or rejected, then callback Codefreh to approve/deny pipeline
#
Expand Down Expand Up @@ -112,26 +185,38 @@ def callback(user, password, baseUrl, number, cf_build_id, token):
auth=(user, password))
processCallbackResponse(response=resp)

def checkSysid(sysid):
if DEBUG:
print("Entering checkSysid: ")
print(" CR_SYSID: %s" % (sysid))

if ( sysid == None ):
print("FATAL: CR_SYSID is not defined.")
sys.exit(1)


def main():
global DEBUG

ACTION = os.getenv('action', 'createCR').lower()
ACTION = os.getenv('ACTION').lower()
USER = os.getenv('SN_USER')
PASSWORD = os.getenv('SN_PASSWORD')
INSTANCE = os.getenv('SN_INSTANCE')
DATA = os.getenv('data')
DATA = os.getenv('CR_DATA')
DEBUG = True if os.getenv('DEBUG', "false").lower() == "true" else False

#DEBUG = True if os.getenv('debug', "false").lower == "true" else False
TITLE = os.getenv('title', 'Change Request created by Codefresh')
DESCRIPTION = os.getenv('description', '')
if DEBUG:
print("Starting ServiceNow plugin for Codefresh")
print(f" ACTION: {ACTION}")
print(f" DATA: {DATA}")
print(" SYSID: %s" % (os.getenv('CR_SYSID')))
print("---")

if ACTION == "createcr":
createChangeRequest(user=USER,
password=PASSWORD,
baseUrl=getBaseUrl(instance=INSTANCE),
title=TITLE,
data=DATA,
description=DESCRIPTION)
data=DATA)
elif ACTION == "callback":
callback(user=USER,
password=PASSWORD,
Expand All @@ -140,9 +225,35 @@ def main():
token=os.getenv('TOKEN'),
cf_build_id=os.getenv('CF_BUILD_ID')
)
elif ACTION == "closecr":
CR_SYSID= os.getenv('CR_SYSID')
CODE=os.getenv('CR_CLOSE_CODE')
NOTES=os.getenv('CR_CLOSE_NOTES')
checkSysid(CR_SYSID)

closeChangeRequest(
user=USER,
password=PASSWORD,
baseUrl=getBaseUrl(instance=INSTANCE),
sysid=os.getenv('CR_SYSID'),
code=CODE,
notes=NOTES,
data=DATA
)
elif ACTION == "updatecr":
CR_SYSID= os.getenv('CR_SYSID')
checkSysid(CR_SYSID)

updateChangeRequest(
user=USER,
password=PASSWORD,
baseUrl=getBaseUrl(instance=INSTANCE),
sysid=CR_SYSID,
data=DATA
)
else:
sys.exit(f"Unknown action: {ACTION}")
printf("FATAL: Unknown action: {ACTION}. Allowed values are createCR, closeCR or updateCR.")
sys.exit(1)


if __name__ == "__main__":
Expand Down
Loading

0 comments on commit c1769f0

Please sign in to comment.