Skip to content

Entity and methods

Secret

Bases: Entity

A class representing a secret.

Source code in digitalhub_core/entities/secrets/entity.py
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
class Secret(Entity):
    """
    A class representing a secret.
    """

    ENTITY_TYPE = EntityTypes.SECRETS.value

    def __init__(
        self,
        project: str,
        name: str,
        uuid: str,
        kind: str,
        metadata: Metadata,
        spec: SecretSpec,
        status: SecretStatus,
        user: str | None = None,
    ) -> None:
        """
        Constructor.

        Parameters
        ----------
        project : str
            Project name.
        name : str
            Name of the object.
        uuid : str
            Version of the object.
        kind : str
            Kind the object.
        metadata : Metadata
            Metadata of the object.
        spec : SecretSpec
            Specification of the object.
        status : SecretStatus
            Status of the object.
        user : str
            Owner of the object.
        """
        super().__init__()
        self.project = project
        self.name = name
        self.id = uuid
        self.kind = kind
        self.key = f"store://{project}/{self.ENTITY_TYPE}/{kind}/{name}:{uuid}"
        self.metadata = metadata
        self.spec = spec
        self.status = status
        self.user = user

        # Add attributes to be used in the to_dict method
        self._obj_attr.extend(["project", "name", "id", "key"])

    #############################
    #  Save / Refresh / Export
    #############################

    def save(self, update: bool = False) -> Secret:
        """
        Save entity into backend.

        Parameters
        ----------
        update : bool
            Flag to indicate update.

        Returns
        -------
        Secret
            Entity saved.
        """
        obj = self.to_dict()

        if not update:
            new_obj = create_entity_api_ctx(self.project, self.ENTITY_TYPE, obj)
            self._update_attributes(new_obj)
            return self

        self.metadata.updated = obj["metadata"]["updated"] = get_timestamp()
        new_obj = update_entity_api_ctx(self.project, self.ENTITY_TYPE, self.id, obj)
        self._update_attributes(new_obj)
        return self

    def refresh(self) -> Secret:
        """
        Refresh object from backend.

        Returns
        -------
        Secret
            Entity refreshed.
        """
        new_obj = read_entity_api_ctx(self.key)
        self._update_attributes(new_obj)
        return self

    def export(self, filename: str | None = None) -> None:
        """
        Export object as a YAML file.

        Parameters
        ----------
        filename : str
            Name of the export YAML file. If not specified, the default value is used.

        Returns
        -------
        None
        """
        obj = self.to_dict()
        if filename is None:
            filename = f"{self.kind}_{self.name}_{self.id}.yml"
        pth = self._context().root / filename
        pth.parent.mkdir(parents=True, exist_ok=True)
        write_yaml(pth, obj)

    #############################
    #  Context
    #############################

    def _context(self) -> Context:
        """
        Get context.

        Returns
        -------
        Context
            Context.
        """
        return get_context(self.project)

    #############################
    #  Secret methods
    #############################

    def set_secret_value(self, value: str) -> None:
        """
        Set a secret.

        Parameters
        ----------
        value : str
            Value of the secret.

        Returns
        -------
        None
        """
        if self._context().local:
            raise NotImplementedError("set_secret() is not implemented for local projects.")

        obj = {self.name: value}
        set_data_api(self.project, self.ENTITY_TYPE, obj)

    def read_secret_value(self) -> dict:
        """
        Read a secret from backend.

        Returns
        -------
        str
            Value of the secret.
        """
        if self._context().local:
            raise NotImplementedError("read_secret() is not implemented for local projects.")

        params = {"keys": self.name}
        return get_data_api(self.project, self.ENTITY_TYPE, params=params)

    #############################
    #  Static interface methods
    #############################

    @staticmethod
    def _parse_dict(obj: dict, validate: bool = True) -> dict:
        """
        Get dictionary and parse it to a valid entity dictionary.

        Parameters
        ----------
        obj : dict
            Dictionary to parse.

        Returns
        -------
        dict
            A dictionary containing the attributes of the entity instance.
        """
        project = obj.get("project")
        name = build_name(obj.get("name"))
        kind = obj.get("kind")
        uuid = build_uuid(obj.get("id"))
        metadata = build_metadata(kind, **obj.get("metadata", {}))
        spec = build_spec(kind, validate=validate, **obj.get("spec", {}))
        status = build_status(kind, **obj.get("status", {}))
        user = obj.get("user")
        return {
            "project": project,
            "name": name,
            "uuid": uuid,
            "kind": kind,
            "metadata": metadata,
            "spec": spec,
            "status": status,
            "user": user,
        }

__init__(project, name, uuid, kind, metadata, spec, status, user=None)

Constructor.

Parameters:

Name Type Description Default
project str

Project name.

required
name str

Name of the object.

required
uuid str

Version of the object.

required
kind str

Kind the object.

required
metadata Metadata

Metadata of the object.

required
spec SecretSpec

Specification of the object.

required
status SecretStatus

Status of the object.

required
user str

Owner of the object.

None
Source code in digitalhub_core/entities/secrets/entity.py
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
def __init__(
    self,
    project: str,
    name: str,
    uuid: str,
    kind: str,
    metadata: Metadata,
    spec: SecretSpec,
    status: SecretStatus,
    user: str | None = None,
) -> None:
    """
    Constructor.

    Parameters
    ----------
    project : str
        Project name.
    name : str
        Name of the object.
    uuid : str
        Version of the object.
    kind : str
        Kind the object.
    metadata : Metadata
        Metadata of the object.
    spec : SecretSpec
        Specification of the object.
    status : SecretStatus
        Status of the object.
    user : str
        Owner of the object.
    """
    super().__init__()
    self.project = project
    self.name = name
    self.id = uuid
    self.kind = kind
    self.key = f"store://{project}/{self.ENTITY_TYPE}/{kind}/{name}:{uuid}"
    self.metadata = metadata
    self.spec = spec
    self.status = status
    self.user = user

    # Add attributes to be used in the to_dict method
    self._obj_attr.extend(["project", "name", "id", "key"])

export(filename=None)

Export object as a YAML file.

Parameters:

Name Type Description Default
filename str

Name of the export YAML file. If not specified, the default value is used.

None

Returns:

Type Description
None
Source code in digitalhub_core/entities/secrets/entity.py
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
def export(self, filename: str | None = None) -> None:
    """
    Export object as a YAML file.

    Parameters
    ----------
    filename : str
        Name of the export YAML file. If not specified, the default value is used.

    Returns
    -------
    None
    """
    obj = self.to_dict()
    if filename is None:
        filename = f"{self.kind}_{self.name}_{self.id}.yml"
    pth = self._context().root / filename
    pth.parent.mkdir(parents=True, exist_ok=True)
    write_yaml(pth, obj)

read_secret_value()

Read a secret from backend.

Returns:

Type Description
str

Value of the secret.

Source code in digitalhub_core/entities/secrets/entity.py
185
186
187
188
189
190
191
192
193
194
195
196
197
198
def read_secret_value(self) -> dict:
    """
    Read a secret from backend.

    Returns
    -------
    str
        Value of the secret.
    """
    if self._context().local:
        raise NotImplementedError("read_secret() is not implemented for local projects.")

    params = {"keys": self.name}
    return get_data_api(self.project, self.ENTITY_TYPE, params=params)

refresh()

Refresh object from backend.

Returns:

Type Description
Secret

Entity refreshed.

Source code in digitalhub_core/entities/secrets/entity.py
114
115
116
117
118
119
120
121
122
123
124
125
def refresh(self) -> Secret:
    """
    Refresh object from backend.

    Returns
    -------
    Secret
        Entity refreshed.
    """
    new_obj = read_entity_api_ctx(self.key)
    self._update_attributes(new_obj)
    return self

save(update=False)

Save entity into backend.

Parameters:

Name Type Description Default
update bool

Flag to indicate update.

False

Returns:

Type Description
Secret

Entity saved.

Source code in digitalhub_core/entities/secrets/entity.py
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
def save(self, update: bool = False) -> Secret:
    """
    Save entity into backend.

    Parameters
    ----------
    update : bool
        Flag to indicate update.

    Returns
    -------
    Secret
        Entity saved.
    """
    obj = self.to_dict()

    if not update:
        new_obj = create_entity_api_ctx(self.project, self.ENTITY_TYPE, obj)
        self._update_attributes(new_obj)
        return self

    self.metadata.updated = obj["metadata"]["updated"] = get_timestamp()
    new_obj = update_entity_api_ctx(self.project, self.ENTITY_TYPE, self.id, obj)
    self._update_attributes(new_obj)
    return self

set_secret_value(value)

Set a secret.

Parameters:

Name Type Description Default
value str

Value of the secret.

required

Returns:

Type Description
None
Source code in digitalhub_core/entities/secrets/entity.py
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
def set_secret_value(self, value: str) -> None:
    """
    Set a secret.

    Parameters
    ----------
    value : str
        Value of the secret.

    Returns
    -------
    None
    """
    if self._context().local:
        raise NotImplementedError("set_secret() is not implemented for local projects.")

    obj = {self.name: value}
    set_data_api(self.project, self.ENTITY_TYPE, obj)

secret_from_dict(obj)

Create Secret instance from a dictionary.

Parameters:

Name Type Description Default
obj dict

Dictionary to create object from.

required

Returns:

Type Description
Secret

Secret instance.

Source code in digitalhub_core/entities/secrets/entity.py
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
def secret_from_dict(obj: dict) -> Secret:
    """
    Create Secret instance from a dictionary.

    Parameters
    ----------
    obj : dict
        Dictionary to create object from.

    Returns
    -------
    Secret
        Secret instance.
    """
    return Secret.from_dict(obj)

secret_from_parameters(project, name, kind, uuid=None, description=None, git_source=None, labels=None, embedded=True, **kwargs)

Create a new Secret instance with the specified parameters.

Parameters:

Name Type Description Default
project str

Project name.

required
name str

Object name.

required
kind str

Kind the object.

required
uuid str

ID of the object (UUID4).

None
git_source str

Remote git source for object.

None
labels list[str]

List of labels.

None
description str

Description of the object (human readable).

None
embedded bool

Flag to determine if object must be embedded in project.

True
**kwargs dict

Spec keyword arguments.

{}

Returns:

Type Description
Secret

An instance of the created secret.

Source code in digitalhub_core/entities/secrets/entity.py
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
def secret_from_parameters(
    project: str,
    name: str,
    kind: str,
    uuid: str | None = None,
    description: str | None = None,
    git_source: str | None = None,
    labels: list[str] | None = None,
    embedded: bool = True,
    **kwargs,
) -> Secret:
    """
    Create a new Secret instance with the specified parameters.

    Parameters
    ----------
    project : str
        Project name.
    name : str
        Object name.
    kind : str
        Kind the object.
    uuid : str
        ID of the object (UUID4).
    git_source : str
        Remote git source for object.
    labels : list[str]
        List of labels.
    description : str
        Description of the object (human readable).
    embedded : bool
        Flag to determine if object must be embedded in project.
    **kwargs : dict
        Spec keyword arguments.

    Returns
    -------
    Secret
        An instance of the created secret.
    """
    name = build_name(name)
    uuid = build_uuid(uuid)
    metadata = build_metadata(
        kind,
        project=project,
        name=name,
        version=uuid,
        description=description,
        source=git_source,
        labels=labels,
        embedded=embedded,
    )
    path = f"kubernetes://dhcore-proj-secrets-{project}/{name}"
    provider = "kubernetes"
    spec = build_spec(
        kind,
        path=path,
        provider=provider,
        **kwargs,
    )
    status = build_status(kind)
    return Secret(
        project=project,
        name=name,
        uuid=uuid,
        kind=kind,
        metadata=metadata,
        spec=spec,
        status=status,
    )