| 41 | |
| 42 | |
| 43 | class UserSecretsClient(): |
| 44 | GET_USER_SECRET_ENDPOINT = '/requests/GetUserSecretRequest' |
| 45 | GET_USER_SECRET_BY_LABEL_ENDPOINT = '/requests/GetUserSecretByLabelRequest' |
| 46 | |
| 47 | def __init__(self): |
| 48 | self.web_client = KaggleWebClient() |
| 49 | |
| 50 | def get_secret(self, label) -> str: |
| 51 | """Retrieves a user secret value by its label. |
| 52 | |
| 53 | This returns the value of the secret with the given label, |
| 54 | if it attached to the current kernel. |
| 55 | Example usage: |
| 56 | client = UserSecretsClient() |
| 57 | secret = client.get_secret('my_db_password') |
| 58 | """ |
| 59 | if label is None or len(label) == 0: |
| 60 | raise ValidationError("Label must be non-empty.") |
| 61 | request_body = { |
| 62 | 'Label': label, |
| 63 | } |
| 64 | response_json = self.web_client.make_post_request(request_body, self.GET_USER_SECRET_BY_LABEL_ENDPOINT) |
| 65 | if 'secret' not in response_json: |
| 66 | raise BackendError( |
| 67 | f'Unexpected response from the service. Response: {response_json}') |
| 68 | return response_json['secret'] |
| 69 | |
| 70 | def get_gcloud_credential(self) -> str: |
| 71 | """Retrieves the Google Cloud SDK credential attached to the current |
| 72 | kernel. |
| 73 | Example usage: |
| 74 | client = UserSecretsClient() |
| 75 | credential_json = client.get_gcloud_credential() |
| 76 | """ |
| 77 | try: |
| 78 | return self.get_secret("__gcloud_sdk_auth__") |
| 79 | except BackendError as backend_error: |
| 80 | message = str(backend_error.args) |
| 81 | if message.find('No user secrets exist') != -1: |
| 82 | raise NotFoundError('Google Cloud SDK credential not found.') |
| 83 | else: |
| 84 | raise |
| 85 | |
| 86 | def set_gcloud_credentials(self, project=None, account=None): |
| 87 | """Set user credentials attached to the current kernel and optionally the project & account name to the `gcloud` CLI. |
| 88 | |
| 89 | Example usage: |
| 90 | client = UserSecretsClient() |
| 91 | client.set_gcloud_credentials(project="my-gcp-project", account="me@my-org.com") |
| 92 | |
| 93 | !gcloud ai-platform jobs list |
| 94 | """ |
| 95 | creds = self.get_gcloud_credential() |
| 96 | creds_path = self._write_credentials_file(creds) |
| 97 | |
| 98 | subprocess.run(['gcloud', 'config', 'set', 'auth/credential_file_override', creds_path]) |
| 99 | |
| 100 | if project: |
no outgoing calls