Skip to content

Instantly share code, notes, and snippets.

@ndamulelonemakh
Last active October 5, 2021 11:36
Show Gist options
  • Select an option

  • Save ndamulelonemakh/ceba31c7cbefaaddabed66102b326b31 to your computer and use it in GitHub Desktop.

Select an option

Save ndamulelonemakh/ceba31c7cbefaaddabed66102b326b31 to your computer and use it in GitHub Desktop.
Using Google Service Account in Azure App Service
'''
Simple method to dynamically create the google service account file in Azure App service
Steps
----------------------
i. Add the service account file contents to Azure App Service configuration
ii. The json contents will be available to your app at runtime as an environment variable, e.g. GOOGLE_CREDENTIALS
iii. When you app starts, save the contents of the environment variable to a file that you specified as your GOOGLE_APPLICATION_CREDENTIALS
'''
import os
import json
import logging
logging.basicConfig(level=logging.DEBUG)
log = logging.getLogger(__name__)
def prepare_gcp_service_account_file():
log.debug('Preparing gcp service account file')
gcp_service_account_filepath = os.getenv('GOOGLE_APPLICATION_CREDENTIALS')
gcp_service_account_json_txt = os.getenv('GOOGLE_CREDENTIALS', default='')
if gcp_service_account_json_txt != '':
gcp_service_account_json_txt = gcp_service_account_json_txt.encode('unicode_escape').decode('UTF-8')
jsondata = json.loads(gcp_service_account_json_txt)
# This step is very important, else google wont recognise the private key
jsondata["private_key"] = jsondata["private_key"].replace('\\n', '\n')
with open(gcp_service_account_filepath, 'w') as f:
json.dump(jsondata, f, indent=4)
log.debug(f'Preparing gcp service account done.')
return
log.warning(f'Credentials not found. $GOOGLE_CREDENTIALS is empty')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment