|
1 | 1 | import google.auth
|
2 | 2 | import google.auth.transport
|
3 | 3 | import google.auth.transport.requests
|
| 4 | + |
| 5 | +import kubernetes |
| 6 | +from kubernetes import client as k8s_client |
| 7 | +from kubernetes import config as k8s_config |
| 8 | +from kubernetes.config import kube_config |
| 9 | +from kubernetes.client import ApiClient, ConfigurationObject, configuration |
4 | 10 | import os
|
5 |
| -print(os.getenv("GOOGLE_APPLICATION_CREDENTIALS", "")) |
6 |
| -#credentials, project_id = google.auth.default(scopes=["https://www.googleapis.com/auth/userinfo.email"]) |
7 |
| -credentials, project_id = google.auth.default() |
8 |
| -request = google.auth.transport.requests.Request() |
9 |
| -credentials.refresh(request) |
| 11 | +import yaml |
| 12 | +from py import util |
| 13 | + |
| 14 | +def load_kube_config(config_file=None, context=None, |
| 15 | + client_configuration=configuration, |
| 16 | + persist_config=True, **kwargs): |
| 17 | + """Loads authentication and cluster information from kube-config file |
| 18 | + and stores them in kubernetes.client.configuration. |
| 19 | +
|
| 20 | + :param config_file: Name of the kube-config file. |
| 21 | + :param context: set the active context. If is set to None, current_context |
| 22 | + from config file will be used. |
| 23 | + :param client_configuration: The kubernetes.client.ConfigurationObject to |
| 24 | + set configs to. |
| 25 | + :param persist_config: If True, config file will be updated when changed |
| 26 | + (e.g GCP token refresh). |
| 27 | + """ |
| 28 | + |
| 29 | + if config_file is None: |
| 30 | + config_file = os.path.expanduser(kube_config.KUBE_CONFIG_DEFAULT_LOCATION) |
| 31 | + |
| 32 | + config_persister = None |
| 33 | + if persist_config: |
| 34 | + def _save_kube_config(config_map): |
| 35 | + with open(config_file, 'w') as f: |
| 36 | + yaml.safe_dump(config_map, f, default_flow_style=False) |
| 37 | + config_persister = _save_kube_config |
| 38 | + |
| 39 | + kube_config._get_kube_config_loader_for_yaml_file( |
| 40 | + config_file, active_context=context, |
| 41 | + client_configuration=client_configuration, |
| 42 | + config_persister=config_persister, **kwargs).load_and_set() |
| 43 | + |
| 44 | +def refresh_credentials(): |
| 45 | + #credentials, project_id = google.auth.default(scopes=["https://www.googleapis.com/auth/cloud-platform"]) |
| 46 | + credentials, project_id = google.auth.default(scopes=["https://www.googleapis.com/auth/userinfo.email"]) |
| 47 | + request = google.auth.transport.requests.Request() |
| 48 | + credentials.refresh(request) |
| 49 | + return credentials |
10 | 50 |
|
| 51 | +refresh_credentials() |
| 52 | +load_kube_config(get_google_credentials=refresh_credentials) |
| 53 | +# Create an API client object to talk to the K8s master. |
| 54 | +api_client = k8s_client.ApiClient() |
0 commit comments