Skip to content

Instantly share code, notes, and snippets.

@data-henrik
Created April 7, 2020 18:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save data-henrik/601e612442524c1ba32dc1c4fda88b99 to your computer and use it in GitHub Desktop.
Save data-henrik/601e612442524c1ba32dc1c4fda88b99 to your computer and use it in GitHub Desktop.
IBM Cloud Function / Openwhisk action to retrieve credentials
# IBM Cloud Functions / OpenWhisk action to
# 1) obtain an IAM Bearer token based on API key from env
# 2) fetch credentials in JSON object from Key Protect key
# 3) return the arguments, credentials and token
import json,sys,os
import requests,base64
# obtain IAM access token
def getAuthToken(api_key):
url = os.environ.get('__OW_IAM_API_URL')
headers = { "Content-Type" : "application/x-www-form-urlencoded" }
data = "apikey=" + api_key + "&grant_type=urn:ibm:params:oauth:grant-type:apikey"
response = requests.post( url, headers=headers, data=data ).json()
# only access token needed
return response["access_token"]
# retrieve key (by Id) from Key Protect instance (by Id)
def getKeyFromKeyProtect(access_token, kpInstId, kpKeyId):
# replace REGION with, e.g., us-south
url="https://REGION.kms.cloud.ibm.com/api/v2/keys/%s" % kpKeyId
headers = { "accept" : "application/vnd.ibm.kms.key+json", "bluemix-instance": kpInstId,
"Authorization": "Bearer " + access_token}
response = requests.get( url, headers=headers).json()
# credentials are in payload
kpPayload=response["resources"][0]["payload"]
return json.loads(base64.b64decode(kpPayload).decode())
def main(args):
# use IAM key of service Id
iamKey = os.environ.get('__OW_IAM_NAMESPACE_API_KEY')
authToken = getAuthToken(iamKey)
# Id for Key Protect instance and the key are passed in
kpKeyId = args.get("kpKeyId")
kpInstId = args.get("kpInstId")
credentials=getKeyFromKeyProtect(authToken, kpInstId, kpKeyId)
return { **args, **credentials, "access_token": authThoken}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment