Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Snow issue402 #404

Merged
merged 38 commits into from
Oct 14, 2021
Merged
Show file tree
Hide file tree
Changes from 36 commits
Commits
Show all changes
38 commits
Select commit Hold shift + click to select a range
c81de76
bumping version to force rebuild
lrochette Sep 17, 2021
08a449b
Change to private account
lrochette Oct 6, 2021
22ee7b4
#402: Adding logic for action
lrochette Oct 6, 2021
43c196a
#402: fix step.yaml syntax
lrochette Oct 7, 2021
2c1bc1e
#402: smaller SVG icon
lrochette Oct 7, 2021
962e26b
402: new smaller logo in svg format
lrochette Oct 7, 2021
e52613a
#402: adding code for closing CR
lrochette Oct 7, 2021
36d4e2e
: use all CAPS for parameters to get consistency
lrochette Oct 7, 2021
ba7283d
#402: Fixing python script
lrochette Oct 11, 2021
4be688e
#402: test for empty CR_DATA
lrochette Oct 11, 2021
d38a408
#402: test for empty CR_DATA
lrochette Oct 11, 2021
6ee91cd
#402: test for empty CR_DATA
lrochette Oct 11, 2021
ba322bd
#402: test for empty CR_DATA
lrochette Oct 11, 2021
46052e9
#402: step.yaml syntax?
lrochette Oct 11, 2021
21c4cee
#402: remvoing blank lines
lrochette Oct 11, 2021
f771571
#402: fix go template syntax with eq instead of ==
lrochette Oct 12, 2021
76745a0
#402: fix conflict between CR_ACTION to the step and ACTION to the sc…
lrochette Oct 12, 2021
cf4ef11
more debug info
lrochette Oct 12, 2021
51f83dd
#402: more debug info
lrochette Oct 12, 2021
10087b3
#402: push overwrite of env variable to the end of the block
lrochette Oct 12, 2021
3b8f642
#402: minor debug info fixes
lrochette Oct 12, 2021
bf26d37
#402: change DEBUG to boolean
lrochette Oct 12, 2021
ce6ce30
#402: change DEBUG to boolean
lrochette Oct 12, 2021
6afd91b
#402: debug info on action
lrochette Oct 12, 2021
78cce4e
#402: debug info on action
lrochette Oct 12, 2021
e4593af
#402: debug info on action
lrochette Oct 12, 2021
99827b2
#402: debug info on action
lrochette Oct 12, 2021
2208a02
#402: debug info
lrochette Oct 12, 2021
a8466a4
: exit with non-zero on error
lrochette Oct 12, 2021
887cf6f
: exit with non-zero on error
lrochette Oct 12, 2021
7b1ac3d
#402: fixed DEBUG var issue
lrochette Oct 13, 2021
7137272
#402: fixed DEBUG var issue
lrochette Oct 13, 2021
51f3598
Fixing URL in annotation
lrochette Oct 13, 2021
5fffb6e
#402: link to CR from the step fixed
lrochette Oct 13, 2021
efe8d5d
#402: reverto to Codefresh official setup - vs. my own private
lrochette Oct 13, 2021
4d25bc5
Merge branch 'master' into snow-issue402
lrochette Oct 13, 2021
5ffc72a
#402: Ted notes
lrochette Oct 14, 2021
d552461
Ted notes
lrochette Oct 14, 2021
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file modified 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