Skip to content

Instantly share code, notes, and snippets.

@greyhoundforty
Created May 9, 2024 20:36
Show Gist options
  • Save greyhoundforty/ac826408cca4187353cae348433f6da1 to your computer and use it in GitHub Desktop.
Save greyhoundforty/ac826408cca4187353cae348433f6da1 to your computer and use it in GitHub Desktop.
IBM Cloud Code Engine python webhook function
import hmac
import os
import json
import hashlib
import httpx
def main(params):
"""Main parameter for function."""
ibmcloud_api_key = os.environ.get('IBMCLOUD_API_KEY')
if not ibmcloud_api_key:
raise ValueError("IBMCLOUD_API_KEY environment variable not found")
hdrs = { 'Accept' : 'application/json', 'Content-Type' : 'application/x-www-form-urlencoded' }
iam_params = { 'grant_type' : 'urn:ibm:params:oauth:grant-type:apikey', 'apikey' : ibmcloud_api_key }
resp = httpx.post('https://iam.cloud.ibm.com/identity/token', data = iam_params, headers = hdrs)
image_tag = params.get('workflow_run', {}).get('head_sha', None)
resp.raise_for_status()
json_payload = resp.json()
iam_token = json_payload['access_token']
code_engine_app = os.environ.get('CE_APP')
code_engine_region = os.environ.get('CE_REGION')
project_id = os.environ.get('CE_PROJECT_ID')
app_endpoint = f"https://api.{code_engine_region}.codeengine.cloud.ibm.com/v2/projects/{project_id}/apps/{code_engine_app}"
try:
app_get = httpx.get(app_endpoint, headers = { 'Authorization' : iam_token })
results = app_get.json()
etag = results['entity_tag']
update_headers = { "Authorization" : iam_token, "Content-Type" : "application/merge-patch+json", "If-Match" : etag }
app_patch_model = { "image_reference": "private.us.icr.io/rtiffany/dts-ce-py-app:" + image_tag }
app_update = httpx.patch(app_endpoint, headers = update_headers, json = app_patch_model)
app_update.raise_for_status()
app_json_payload = app_update.json()
return {
"headers": {"Content-Type": "application/json"},
"statusCode": 200,
"body": app_json_payload
}
except Exception as e:
# Define results here to avoid the error
results = {"error": str(e)}
return {
"headers": {"Content-Type": "application/json"},
"statusCode": 500,
"body": json.dumps(results)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment