Debian Codegraph @

azure-kusto-data/azure/kusto/data/env_utils.py

raw
1 import os
2 from dataclasses import dataclass, astuple
3 from typing import Optional
4
5
6 def get_env(*args, optional=False, default=None):
7 """Return the first environment variable that is defined."""
8 for arg in args:
9 if arg in os.environ:
10 return os.environ[arg]
11 if optional or default:
12 return default
13 raise ValueError("No environment variables found: {}".format(args))
14
15
16 def set_env(key, value):
17 """Set the environment variable."""
18 os.environ[key] = value
19
20
21 def get_app_id(optional=False):
22 """Return the app id."""
23 result = get_env("APP_ID", "AZURE_CLIENT_ID", optional=optional)
24 if result:
25 set_env("AZURE_CLIENT_ID", result)
26 return result
27
28
29 def get_auth_id(optional=False):
30 """Return the auth id."""
31 result = get_env("AUTH_ID", "APP_AUTH_ID", "AZURE_TENANT_ID", optional=optional)
32 if result:
33 set_env("AZURE_TENANT_ID", result)
34 return result
35
36
37 def get_app_key(optional=False):
38 """Return the app key."""
39 result = get_env("APP_KEY", "AZURE_CLIENT_SECRET", optional=optional)
40 if result:
41 set_env("AZURE_CLIENT_SECRET", result)
42 return result
43
44
45 @dataclass(frozen=True)
46 class AppKeyAuth:
47 app_id: str
48 app_key: str
49 auth_id: str
50
51 def __iter__(self):
52 return iter(astuple(self))
53
54
55 def prepare_app_key_auth(optional=False) -> Optional[AppKeyAuth]:
56 """Gets app key auth information from the env, sets the correct values for azidentity, and returns the AppKeyAuth object."""
57 app_id = get_app_id(optional=optional)
58 app_key = get_app_key(optional=optional)
59 auth_id = get_auth_id(optional=optional)
60 if app_id and app_key and auth_id:
61 return AppKeyAuth(app_id, app_key, auth_id)
62 return None