Skip to content

Instantly share code, notes, and snippets.

@konverner
Last active December 22, 2024 09:42
Show Gist options
  • Save konverner/607e3e22632b123f9c0b6fd18b09e353 to your computer and use it in GitHub Desktop.
Save konverner/607e3e22632b123f9c0b6fd18b09e353 to your computer and use it in GitHub Desktop.
a function allows to generate json key file used by google api from environment variables
"""
A function allows to generate json key file used by google api from environment variables. Example of `.env` file:
```
TYPE="my_service_account"
PROJECT_ID="my_project_id"
PRIVATE_KEY_ID="my_private_key_id"
PRIVATE_KEY="-----BEGIN PRIVATE KEY-----
my_private_key_content
-----END PRIVATE KEY-----
"
CLIENT_EMAIL="my_client_email"
CLIENT_ID="my_client_id"
AUTH_URI="https://accounts.google.com/o/oauth2/auth"
TOKEN_URI="https://oauth2.googleapis.com/token"
AUTH_PROVIDER_X509_CERT_URL="https://www.googleapis.com/oauth2/v1/certs"
CLIENT_X509_CERT_URL="my_client_x509_cert_url"
UNIVERSE_DOMAIN="googleapis.com"
```
"""
import os
def create_keyfile_dict() -> dict[str, str]:
""" Create a dictionary with keys for the Google API from environment variables
Returns:
Dictionary with keys for the Google API
Raises:
ValueError: If any of the environment variables is not set
"""
variables_keys = {
"type": os.getenv("TYPE"),
"project_id": os.getenv("PROJECT_ID"),
"private_key_id": os.getenv("PRIVATE_KEY_ID"),
"private_key": os.getenv("PRIVATE_KEY").replace('\\n', '\n'),
"client_email": os.getenv("CLIENT_EMAIL"),
"client_id": os.getenv("CLIENT_ID"),
"auth_uri": os.getenv("AUTH_URI"),
"token_uri": os.getenv("TOKEN_URI"),
"auth_provider_x509_cert_url": os.getenv("AUTH_PROVIDER_X509_CERT_URL"),
"client_x509_cert_url": os.getenv("CLIENT_X509_CERT_URL")
}
for key, _ in variables_keys.items():
if variables_keys[key] is None:
raise ValueError(f"Environment variable {key} is not set")
return variables_keys
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment