cloud-metadata 1.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- cloud_metadata/__init__.py +176 -0
- cloud_metadata/_http.py +103 -0
- cloud_metadata/cli.py +192 -0
- cloud_metadata/detect.py +187 -0
- cloud_metadata/engine.py +333 -0
- cloud_metadata/errors.py +65 -0
- cloud_metadata/functions.py +211 -0
- cloud_metadata/providers/__init__.py +20 -0
- cloud_metadata/providers/_loader.py +260 -0
- cloud_metadata/providers/_spec.py +194 -0
- cloud_metadata/providers/data/alibaba.json +113 -0
- cloud_metadata/providers/data/amazon.json +97 -0
- cloud_metadata/providers/data/google.json +78 -0
- cloud_metadata/providers/data/index.json +9 -0
- cloud_metadata/providers/data/microsoft.json +77 -0
- cloud_metadata/providers/data/oracle.json +73 -0
- cloud_metadata/py.typed +0 -0
- cloud_metadata/registry.py +125 -0
- cloud_metadata-1.1.0.dist-info/METADATA +379 -0
- cloud_metadata-1.1.0.dist-info/RECORD +23 -0
- cloud_metadata-1.1.0.dist-info/WHEEL +4 -0
- cloud_metadata-1.1.0.dist-info/entry_points.txt +3 -0
- cloud_metadata-1.1.0.dist-info/licenses/LICENSE +618 -0
cloud_metadata/engine.py
ADDED
|
@@ -0,0 +1,333 @@
|
|
|
1
|
+
# Copyright (c) 2026 SUSE LLC. All rights reserved.
|
|
2
|
+
#
|
|
3
|
+
# This file is part of cloud-metadata. cloud-metadata provides one command
|
|
4
|
+
# and one Python API that return the same standard instance metadata on every
|
|
5
|
+
# supported public cloud.
|
|
6
|
+
#
|
|
7
|
+
# This program is free software: you can redistribute it and/or modify
|
|
8
|
+
# it under the terms of the GNU General Public License as published by
|
|
9
|
+
# the Free Software Foundation, either version 3 of the License, or
|
|
10
|
+
# (at your option) any later version.
|
|
11
|
+
#
|
|
12
|
+
# This program is distributed in the hope that it will be useful,
|
|
13
|
+
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
14
|
+
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
15
|
+
# GNU General Public License for more details.
|
|
16
|
+
#
|
|
17
|
+
# You should have received a copy of the GNU General Public License
|
|
18
|
+
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
|
19
|
+
|
|
20
|
+
"""Fetch metadata documents and resolve standard keys for a provider."""
|
|
21
|
+
|
|
22
|
+
import json
|
|
23
|
+
import logging
|
|
24
|
+
import urllib.error
|
|
25
|
+
from collections.abc import Mapping
|
|
26
|
+
from urllib.parse import quote
|
|
27
|
+
|
|
28
|
+
from cloud_metadata import _http, functions, registry
|
|
29
|
+
from cloud_metadata.errors import (
|
|
30
|
+
DocumentNotFound,
|
|
31
|
+
InvalidExpression,
|
|
32
|
+
KeyNotAvailable,
|
|
33
|
+
MetadataUnavailable,
|
|
34
|
+
)
|
|
35
|
+
from cloud_metadata.providers._spec import Auth, Document, ProviderSpec
|
|
36
|
+
|
|
37
|
+
logger = logging.getLogger(__name__)
|
|
38
|
+
|
|
39
|
+
HTTP_UNAUTHORIZED = 401
|
|
40
|
+
HTTP_NOT_FOUND = 404
|
|
41
|
+
HOP_LIMIT_STATUSES = (401, 403)
|
|
42
|
+
|
|
43
|
+
# Per provider name: the base URL that answered last, tried first next time.
|
|
44
|
+
_working_base_url: dict[str, str] = {}
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
# Per provider name: the session token, or None if the token flow failed and
|
|
48
|
+
# plain requests are used instead.
|
|
49
|
+
_tokens: dict[str, str | None] = {}
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
# Per (provider name, document name): the parsed document.
|
|
53
|
+
_documents: dict[tuple[str, str], object] = {}
|
|
54
|
+
|
|
55
|
+
# Per provider name: why the token flow failed, if it did.
|
|
56
|
+
_token_errors: dict[str, MetadataUnavailable] = {}
|
|
57
|
+
|
|
58
|
+
HOP_LIMIT_HINT = (
|
|
59
|
+
"the token request timed out and the plain request was rejected; if this "
|
|
60
|
+
"runs in a container on AWS, the IMDS hop limit (HttpPutResponseHopLimit) "
|
|
61
|
+
"may be too low, so raise it to 2 or allow IMDSv1"
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def clear_cache() -> None:
|
|
66
|
+
"""Forget everything learned about providers in this process."""
|
|
67
|
+
_working_base_url.clear()
|
|
68
|
+
_tokens.clear()
|
|
69
|
+
_token_errors.clear()
|
|
70
|
+
_documents.clear()
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _is_timeout(err: BaseException | None) -> bool:
|
|
74
|
+
while err is not None:
|
|
75
|
+
if isinstance(err, TimeoutError):
|
|
76
|
+
return True
|
|
77
|
+
if isinstance(err, urllib.error.URLError) and isinstance(
|
|
78
|
+
err.reason, TimeoutError
|
|
79
|
+
):
|
|
80
|
+
return True
|
|
81
|
+
err = err.__cause__
|
|
82
|
+
return False
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _ordered_base_urls(spec: ProviderSpec) -> list[str]:
|
|
86
|
+
urls = list(spec.base_urls)
|
|
87
|
+
last = _working_base_url.get(spec.name)
|
|
88
|
+
if last in urls:
|
|
89
|
+
urls.remove(last)
|
|
90
|
+
urls.insert(0, last)
|
|
91
|
+
return urls
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _send(
|
|
95
|
+
spec: ProviderSpec,
|
|
96
|
+
method: str,
|
|
97
|
+
path: str,
|
|
98
|
+
headers: Mapping[str, str],
|
|
99
|
+
timeout: float,
|
|
100
|
+
) -> _http.Response:
|
|
101
|
+
"""Send a request to the first base URL that answers.
|
|
102
|
+
|
|
103
|
+
Only connection-level failures move on to the next base URL. If a service
|
|
104
|
+
answers with an HTTP error, that error is raised straight away, because
|
|
105
|
+
the other base URLs lead to the same service.
|
|
106
|
+
"""
|
|
107
|
+
urls = _ordered_base_urls(spec)
|
|
108
|
+
if not urls:
|
|
109
|
+
msg = f"{spec.name}: no base_urls to query"
|
|
110
|
+
raise MetadataUnavailable(msg)
|
|
111
|
+
last_error: MetadataUnavailable | None = None
|
|
112
|
+
for base_url in urls:
|
|
113
|
+
try:
|
|
114
|
+
response = _http.request(
|
|
115
|
+
method, _http.join_url(base_url, path), headers, timeout
|
|
116
|
+
)
|
|
117
|
+
except MetadataUnavailable as err:
|
|
118
|
+
if err.status is not None:
|
|
119
|
+
raise
|
|
120
|
+
last_error = err
|
|
121
|
+
continue
|
|
122
|
+
_working_base_url[spec.name] = base_url
|
|
123
|
+
return response
|
|
124
|
+
msg = f"{spec.name}: no metadata service reachable ({last_error})"
|
|
125
|
+
raise MetadataUnavailable(msg) from last_error
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _fetch_token(spec: ProviderSpec, auth: Auth, timeout: float) -> str | None:
|
|
129
|
+
"""Run the token flow. Returns None if no token could be obtained."""
|
|
130
|
+
headers = {**spec.request_headers, **auth.request_headers}
|
|
131
|
+
try:
|
|
132
|
+
response = _send(spec, auth.method, auth.path, headers, timeout)
|
|
133
|
+
except MetadataUnavailable as err:
|
|
134
|
+
logger.warning("%s: token request failed (%s)", spec.name, err)
|
|
135
|
+
_token_errors[spec.name] = err
|
|
136
|
+
return None
|
|
137
|
+
return response.body.strip() or None
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def _session_token(spec: ProviderSpec, timeout: float) -> str | None:
|
|
141
|
+
if spec.auth is None:
|
|
142
|
+
return None
|
|
143
|
+
if spec.name not in _tokens:
|
|
144
|
+
_tokens[spec.name] = _fetch_token(spec, spec.auth, timeout)
|
|
145
|
+
return _tokens[spec.name]
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _send_without_token(
|
|
149
|
+
spec: ProviderSpec,
|
|
150
|
+
method: str,
|
|
151
|
+
path: str,
|
|
152
|
+
headers: Mapping[str, str],
|
|
153
|
+
timeout: float,
|
|
154
|
+
) -> _http.Response:
|
|
155
|
+
"""Send a plain request, explaining a likely AWS hop-limit failure."""
|
|
156
|
+
try:
|
|
157
|
+
return _send(spec, method, path, headers, timeout)
|
|
158
|
+
except MetadataUnavailable as err:
|
|
159
|
+
token_error = _token_errors.get(spec.name)
|
|
160
|
+
if err.status in HOP_LIMIT_STATUSES and _is_timeout(token_error):
|
|
161
|
+
msg = f"{spec.name}: {err}; {HOP_LIMIT_HINT}"
|
|
162
|
+
raise MetadataUnavailable(msg, status=err.status) from err
|
|
163
|
+
raise
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def request(
|
|
167
|
+
spec: ProviderSpec,
|
|
168
|
+
path: str,
|
|
169
|
+
*,
|
|
170
|
+
method: str = "GET",
|
|
171
|
+
timeout: float = _http.DEFAULT_TIMEOUT,
|
|
172
|
+
) -> _http.Response:
|
|
173
|
+
"""Send one request to the provider, applying its headers and token flow.
|
|
174
|
+
|
|
175
|
+
If the provider has an ``auth`` flow, a token is requested first and sent
|
|
176
|
+
in ``apply_header``. A token that the service rejects with ``401`` is
|
|
177
|
+
replaced once. If no token can be obtained, the request is sent without
|
|
178
|
+
one (for example AWS IMDSv1).
|
|
179
|
+
|
|
180
|
+
Raises:
|
|
181
|
+
MetadataUnavailable: If no base URL answers or the service returns an
|
|
182
|
+
HTTP error.
|
|
183
|
+
"""
|
|
184
|
+
token = _session_token(spec, timeout)
|
|
185
|
+
headers = dict(spec.request_headers)
|
|
186
|
+
if token is None or spec.auth is None:
|
|
187
|
+
return _send_without_token(spec, method, path, headers, timeout)
|
|
188
|
+
headers[spec.auth.apply_header] = token
|
|
189
|
+
try:
|
|
190
|
+
return _send(spec, method, path, headers, timeout)
|
|
191
|
+
except MetadataUnavailable as err:
|
|
192
|
+
if err.status != HTTP_UNAUTHORIZED:
|
|
193
|
+
raise
|
|
194
|
+
# The token expired or was revoked: get a new one and try once more.
|
|
195
|
+
_tokens.pop(spec.name, None)
|
|
196
|
+
token = _session_token(spec, timeout)
|
|
197
|
+
if token is None:
|
|
198
|
+
return _send_without_token(
|
|
199
|
+
spec, method, path, dict(spec.request_headers), timeout
|
|
200
|
+
)
|
|
201
|
+
headers[spec.auth.apply_header] = token
|
|
202
|
+
return _send(spec, method, path, headers, timeout)
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def fetch_document(
|
|
206
|
+
spec: ProviderSpec, name: str, *, timeout: float = _http.DEFAULT_TIMEOUT
|
|
207
|
+
) -> object:
|
|
208
|
+
"""Fetch one named document, trying the provider's base URLs in order.
|
|
209
|
+
|
|
210
|
+
Returns the parsed body for a ``json`` document and the stripped body for a
|
|
211
|
+
``text`` document.
|
|
212
|
+
|
|
213
|
+
Raises:
|
|
214
|
+
DocumentNotFound: If the spec has no document called ``name``.
|
|
215
|
+
MetadataUnavailable: If no base URL answers, the service returns an
|
|
216
|
+
HTTP error or a JSON body is invalid.
|
|
217
|
+
"""
|
|
218
|
+
document = spec.documents.get(name)
|
|
219
|
+
if document is None:
|
|
220
|
+
msg = f"unknown document {name!r}"
|
|
221
|
+
raise DocumentNotFound(msg)
|
|
222
|
+
path = _resolve_path(spec, document, timeout)
|
|
223
|
+
response = request(spec, path, timeout=timeout)
|
|
224
|
+
return _parse(spec, name, document, response.body)
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def _resolve_path(spec: ProviderSpec, document: Document, timeout: float) -> str:
|
|
228
|
+
"""Fill the placeholders of a document path from other documents."""
|
|
229
|
+
# A value from the service must not be able to change the path, so it is
|
|
230
|
+
# quoted.
|
|
231
|
+
values = {
|
|
232
|
+
param: quote(str(get_document(spec, target, timeout=timeout)), safe=":")
|
|
233
|
+
for param, target in document.params.items()
|
|
234
|
+
}
|
|
235
|
+
return document.path.format(**values)
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def _parse(spec: ProviderSpec, name: str, document: Document, body: str) -> object:
|
|
239
|
+
if document.format == "text":
|
|
240
|
+
return body.strip()
|
|
241
|
+
try:
|
|
242
|
+
return json.loads(body)
|
|
243
|
+
except json.JSONDecodeError as err:
|
|
244
|
+
msg = f"{spec.name}: document {name!r} is not valid JSON: {err}"
|
|
245
|
+
raise MetadataUnavailable(msg) from err
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def primary_document(spec: ProviderSpec) -> str:
|
|
249
|
+
"""Return the name of the spec's primary (first) document."""
|
|
250
|
+
if not spec.documents:
|
|
251
|
+
msg = f"{spec.name}: the provider defines no documents"
|
|
252
|
+
raise ValueError(msg)
|
|
253
|
+
return next(iter(spec.documents))
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def get_document(
|
|
257
|
+
spec: ProviderSpec, name: str, *, timeout: float = _http.DEFAULT_TIMEOUT
|
|
258
|
+
) -> object:
|
|
259
|
+
"""Return a document, fetching it only the first time in this process."""
|
|
260
|
+
cache_key = (spec.name, name)
|
|
261
|
+
if cache_key not in _documents:
|
|
262
|
+
_documents[cache_key] = fetch_document(spec, name, timeout=timeout)
|
|
263
|
+
return _documents[cache_key]
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def evaluate(
|
|
267
|
+
spec: ProviderSpec,
|
|
268
|
+
expression: str | None,
|
|
269
|
+
document: str | None = None,
|
|
270
|
+
*,
|
|
271
|
+
timeout: float = _http.DEFAULT_TIMEOUT,
|
|
272
|
+
) -> object:
|
|
273
|
+
"""Evaluate a JMESPath expression against a document.
|
|
274
|
+
|
|
275
|
+
``document`` defaults to the primary document. An expression of ``None``
|
|
276
|
+
returns the whole document. ``jmespath`` is imported only when an
|
|
277
|
+
expression is evaluated.
|
|
278
|
+
|
|
279
|
+
Raises:
|
|
280
|
+
DocumentNotFound: If the spec has no document called ``document``.
|
|
281
|
+
InvalidExpression: If the expression is not valid JMESPath.
|
|
282
|
+
MetadataUnavailable: If the document cannot be fetched.
|
|
283
|
+
"""
|
|
284
|
+
if document is None:
|
|
285
|
+
document = primary_document(spec)
|
|
286
|
+
data = get_document(spec, document, timeout=timeout)
|
|
287
|
+
if expression is None:
|
|
288
|
+
return data
|
|
289
|
+
import jmespath # noqa: PLC0415 - lazy, see DESIGN.md section 1
|
|
290
|
+
import jmespath.exceptions # noqa: PLC0415
|
|
291
|
+
|
|
292
|
+
try:
|
|
293
|
+
return jmespath.search(expression, data, options=functions.get_options())
|
|
294
|
+
except jmespath.exceptions.JMESPathError as err:
|
|
295
|
+
msg = f"invalid expression {expression!r}: {err}"
|
|
296
|
+
raise InvalidExpression(msg) from err
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
def resolve(
|
|
300
|
+
spec: ProviderSpec, key: str, *, timeout: float = _http.DEFAULT_TIMEOUT
|
|
301
|
+
) -> str:
|
|
302
|
+
"""Return the value of a standard key as a string.
|
|
303
|
+
|
|
304
|
+
Strings are returned as they are and other values as compact JSON.
|
|
305
|
+
|
|
306
|
+
Raises:
|
|
307
|
+
KeyNotAvailable: If the provider does not map the key, the value is
|
|
308
|
+
empty, or the service has no such document (HTTP 404).
|
|
309
|
+
MetadataUnavailable: If the service cannot be reached or fails.
|
|
310
|
+
"""
|
|
311
|
+
if key not in spec.keys:
|
|
312
|
+
msg = f"{spec.name}: key {key!r} is not available"
|
|
313
|
+
raise KeyNotAvailable(msg)
|
|
314
|
+
document, expression = spec.keys[key]
|
|
315
|
+
try:
|
|
316
|
+
value = evaluate(spec, expression, document, timeout=timeout)
|
|
317
|
+
except MetadataUnavailable as err:
|
|
318
|
+
if err.status == HTTP_NOT_FOUND:
|
|
319
|
+
msg = f"{spec.name}: key {key!r} has no value on this instance"
|
|
320
|
+
raise KeyNotAvailable(msg) from err
|
|
321
|
+
raise
|
|
322
|
+
if isinstance(value, str):
|
|
323
|
+
value = value.strip()
|
|
324
|
+
if value is None or value in ("", [], {}):
|
|
325
|
+
msg = f"{spec.name}: key {key!r} has no value on this instance"
|
|
326
|
+
raise KeyNotAvailable(msg)
|
|
327
|
+
if isinstance(value, str):
|
|
328
|
+
return value
|
|
329
|
+
return json.dumps(value, separators=(",", ":"))
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
# A provider change can alter every cached value.
|
|
333
|
+
registry.add_change_callback(clear_cache)
|
cloud_metadata/errors.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
# Copyright (c) 2026 SUSE LLC. All rights reserved.
|
|
2
|
+
#
|
|
3
|
+
# This file is part of cloud-metadata. cloud-metadata provides one command
|
|
4
|
+
# and one Python API that return the same standard instance metadata on every
|
|
5
|
+
# supported public cloud.
|
|
6
|
+
#
|
|
7
|
+
# This program is free software: you can redistribute it and/or modify
|
|
8
|
+
# it under the terms of the GNU General Public License as published by
|
|
9
|
+
# the Free Software Foundation, either version 3 of the License, or
|
|
10
|
+
# (at your option) any later version.
|
|
11
|
+
#
|
|
12
|
+
# This program is distributed in the hope that it will be useful,
|
|
13
|
+
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
14
|
+
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
15
|
+
# GNU General Public License for more details.
|
|
16
|
+
#
|
|
17
|
+
# You should have received a copy of the GNU General Public License
|
|
18
|
+
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
|
19
|
+
|
|
20
|
+
"""Exceptions raised by cloud-metadata."""
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class CloudMetadataError(Exception):
|
|
24
|
+
"""Base class for all cloud-metadata errors."""
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class ProviderNotDetected(CloudMetadataError):
|
|
28
|
+
"""No registered provider matches the current host, or the name is unknown."""
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class KeyNotAvailable(CloudMetadataError):
|
|
32
|
+
"""The key is unmapped for the provider or has no value on this instance."""
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class DocumentNotFound(CloudMetadataError, KeyError):
|
|
36
|
+
"""The provider has no document with that name.
|
|
37
|
+
|
|
38
|
+
It is also a ``KeyError``, so code that catches ``KeyError`` keeps working.
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
def __str__(self) -> str:
|
|
42
|
+
"""Return the message without the quotes that ``KeyError`` adds."""
|
|
43
|
+
return str(self.args[0]) if self.args else ""
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class InvalidExpression(CloudMetadataError, ValueError):
|
|
47
|
+
"""The JMESPath expression is not valid.
|
|
48
|
+
|
|
49
|
+
It is also a ``ValueError``, so code that catches ``ValueError`` keeps
|
|
50
|
+
working.
|
|
51
|
+
"""
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class MetadataUnavailable(CloudMetadataError):
|
|
55
|
+
"""The metadata service is unreachable, timed out or returned an error.
|
|
56
|
+
|
|
57
|
+
Attributes:
|
|
58
|
+
status: The HTTP status code if the service answered with one, else
|
|
59
|
+
``None`` (unreachable or timed out).
|
|
60
|
+
"""
|
|
61
|
+
|
|
62
|
+
def __init__(self, message: str = "", *, status: int | None = None) -> None:
|
|
63
|
+
"""Store the message and the optional HTTP status."""
|
|
64
|
+
super().__init__(message)
|
|
65
|
+
self.status = status
|
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
# Copyright (c) 2026 SUSE LLC. All rights reserved.
|
|
2
|
+
#
|
|
3
|
+
# This file is part of cloud-metadata. cloud-metadata provides one command
|
|
4
|
+
# and one Python API that return the same standard instance metadata on every
|
|
5
|
+
# supported public cloud.
|
|
6
|
+
#
|
|
7
|
+
# This program is free software: you can redistribute it and/or modify
|
|
8
|
+
# it under the terms of the GNU General Public License as published by
|
|
9
|
+
# the Free Software Foundation, either version 3 of the License, or
|
|
10
|
+
# (at your option) any later version.
|
|
11
|
+
#
|
|
12
|
+
# This program is distributed in the hope that it will be useful,
|
|
13
|
+
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
14
|
+
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
15
|
+
# GNU General Public License for more details.
|
|
16
|
+
#
|
|
17
|
+
# You should have received a copy of the GNU General Public License
|
|
18
|
+
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
|
19
|
+
|
|
20
|
+
"""Custom JMESPath functions.
|
|
21
|
+
|
|
22
|
+
JMESPath has no string splitting, so a few cloud responses (for example Google
|
|
23
|
+
machine types and zones, which are full resource paths) need small helpers.
|
|
24
|
+
Google also reports one IPv6 list for both internal and external addresses, so
|
|
25
|
+
there are helpers that pick the private or the public one. Alibaba does not say
|
|
26
|
+
which kind its IPv6 addresses are, so ``first_ipv6`` takes the first of any kind.
|
|
27
|
+
Azure has no single ID for a Marketplace image, so ``image_urn`` builds the
|
|
28
|
+
``publisher:offer:sku:version`` URN from the image reference.
|
|
29
|
+
These are the only non-data extension point for provider expressions.
|
|
30
|
+
|
|
31
|
+
``jmespath`` is imported only when :func:`get_options` is first called, so
|
|
32
|
+
importing this module is cheap.
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
import ipaddress
|
|
36
|
+
import re
|
|
37
|
+
from functools import cache
|
|
38
|
+
from typing import TYPE_CHECKING, NotRequired, TypedDict
|
|
39
|
+
|
|
40
|
+
if TYPE_CHECKING:
|
|
41
|
+
import jmespath
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class _Signature(TypedDict):
|
|
45
|
+
"""An argument signature, as ``jmespath.functions.signature`` takes it."""
|
|
46
|
+
|
|
47
|
+
types: list[str]
|
|
48
|
+
variadic: NotRequired[bool]
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
_ZONE_SUFFIX = re.compile(r"-[a-z]$")
|
|
52
|
+
|
|
53
|
+
# Unique local addresses (private) and global unicast addresses (public).
|
|
54
|
+
_IPV6_PRIVATE = ipaddress.IPv6Network("fc00::/7")
|
|
55
|
+
_IPV6_PUBLIC = ipaddress.IPv6Network("2000::/3")
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def basename(path: str | None) -> str | None:
|
|
59
|
+
"""Return the last ``/`` separated segment of ``path``.
|
|
60
|
+
|
|
61
|
+
A trailing ``/`` is ignored. ``None`` stays ``None``.
|
|
62
|
+
"""
|
|
63
|
+
if path is None:
|
|
64
|
+
return None
|
|
65
|
+
return path.rstrip("/").rsplit("/", 1)[-1]
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def strip_zone_suffix(zone: str | None) -> str | None:
|
|
69
|
+
"""Remove the trailing zone letter, for example ``us-central1-a``.
|
|
70
|
+
|
|
71
|
+
Returns ``us-central1``. A value without a zone letter is returned
|
|
72
|
+
unchanged. ``None`` stays ``None``.
|
|
73
|
+
"""
|
|
74
|
+
if zone is None:
|
|
75
|
+
return None
|
|
76
|
+
return _ZONE_SUFFIX.sub("", zone)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
_SEPARATORS = re.compile(r"""[\s,\[\]"']+""")
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _ipv6_addresses(value: object) -> list[str]:
|
|
83
|
+
"""Return every IPv6 address in ``value``, without prefix lengths.
|
|
84
|
+
|
|
85
|
+
``value`` is an address, a range such as ``fd20:1::/96``, a list of those, or
|
|
86
|
+
text that holds them with brackets, quotes or commas around them, for
|
|
87
|
+
example ``["2408::1", "2408::2"]``. Anything that is not an IPv6 address is
|
|
88
|
+
skipped.
|
|
89
|
+
"""
|
|
90
|
+
if isinstance(value, list):
|
|
91
|
+
return [address for entry in value for address in _ipv6_addresses(entry)]
|
|
92
|
+
if not isinstance(value, str):
|
|
93
|
+
return []
|
|
94
|
+
addresses = []
|
|
95
|
+
for token in _SEPARATORS.split(value):
|
|
96
|
+
if not token:
|
|
97
|
+
continue
|
|
98
|
+
text = token.split("/", 1)[0]
|
|
99
|
+
try:
|
|
100
|
+
ipaddress.IPv6Address(text)
|
|
101
|
+
except ValueError:
|
|
102
|
+
continue
|
|
103
|
+
addresses.append(text)
|
|
104
|
+
return addresses
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _first_ipv6_in(value: object, network: ipaddress.IPv6Network) -> str | None:
|
|
108
|
+
for text in _ipv6_addresses(value):
|
|
109
|
+
if ipaddress.IPv6Address(text) in network:
|
|
110
|
+
return text
|
|
111
|
+
return None
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def first_ipv6(value: str | list[object] | None) -> str | None:
|
|
115
|
+
"""Return the first IPv6 address in ``value``, whatever its scope.
|
|
116
|
+
|
|
117
|
+
Brackets, quotes, commas and prefix lengths are ignored, so this reads a
|
|
118
|
+
bare ``[2408::1]`` as well as a JSON list. Returns ``None`` if there is no
|
|
119
|
+
IPv6 address.
|
|
120
|
+
"""
|
|
121
|
+
addresses = _ipv6_addresses(value)
|
|
122
|
+
return addresses[0] if addresses else None
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def ipv6_private(value: str | list[object] | None) -> str | None:
|
|
126
|
+
"""Return the first private (unique local, ``fc00::/7``) IPv6 address.
|
|
127
|
+
|
|
128
|
+
``value`` is an address or range, or a list of them. A prefix length is
|
|
129
|
+
dropped. Returns ``None`` if there is no such address.
|
|
130
|
+
"""
|
|
131
|
+
return _first_ipv6_in(value, _IPV6_PRIVATE)
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def ipv6_public(value: str | list[object] | None) -> str | None:
|
|
135
|
+
"""Return the first public (global unicast, ``2000::/3``) IPv6 address.
|
|
136
|
+
|
|
137
|
+
``value`` is an address or range, or a list of them. A prefix length is
|
|
138
|
+
dropped. Returns ``None`` if there is no such address.
|
|
139
|
+
"""
|
|
140
|
+
return _first_ipv6_in(value, _IPV6_PUBLIC)
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def image_urn(reference: dict[str, object] | None) -> str | None:
|
|
144
|
+
"""Return the ``publisher:offer:sku:version`` URN of a Marketplace image.
|
|
145
|
+
|
|
146
|
+
``reference`` is the ``imageReference`` object of an Azure instance. The
|
|
147
|
+
version is ``exactVersion`` when that is set, otherwise ``version``, which
|
|
148
|
+
may be ``latest``. The values are used as they are, apart from stripping
|
|
149
|
+
white space. Returns ``None`` if the reference is missing or any part is
|
|
150
|
+
absent, empty or not a string, so a custom image does not get a URN like
|
|
151
|
+
``:::``.
|
|
152
|
+
"""
|
|
153
|
+
if reference is None:
|
|
154
|
+
return None
|
|
155
|
+
parts = []
|
|
156
|
+
for fields in (
|
|
157
|
+
("publisher",),
|
|
158
|
+
("offer",),
|
|
159
|
+
("sku",),
|
|
160
|
+
("exactVersion", "version"),
|
|
161
|
+
):
|
|
162
|
+
text = next(
|
|
163
|
+
(
|
|
164
|
+
value.strip()
|
|
165
|
+
for field in fields
|
|
166
|
+
if isinstance(value := reference.get(field), str) and value.strip()
|
|
167
|
+
),
|
|
168
|
+
None,
|
|
169
|
+
)
|
|
170
|
+
if text is None:
|
|
171
|
+
return None
|
|
172
|
+
parts.append(text)
|
|
173
|
+
return ":".join(parts)
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
@cache
|
|
177
|
+
def get_options() -> "jmespath.Options":
|
|
178
|
+
"""Return JMESPath options with the custom functions registered."""
|
|
179
|
+
import jmespath # noqa: PLC0415 - lazy, see module docstring
|
|
180
|
+
import jmespath.functions # noqa: PLC0415
|
|
181
|
+
|
|
182
|
+
string_or_null: _Signature = {"types": ["string", "null"]}
|
|
183
|
+
address_list: _Signature = {"types": ["array", "string", "null"]}
|
|
184
|
+
object_or_null: _Signature = {"types": ["object", "null"]}
|
|
185
|
+
|
|
186
|
+
class CloudMetadataFunctions(jmespath.functions.Functions):
|
|
187
|
+
@jmespath.functions.signature(string_or_null)
|
|
188
|
+
def _func_basename(self, path: str | None) -> str | None:
|
|
189
|
+
return basename(path)
|
|
190
|
+
|
|
191
|
+
@jmespath.functions.signature(string_or_null)
|
|
192
|
+
def _func_strip_zone_suffix(self, zone: str | None) -> str | None:
|
|
193
|
+
return strip_zone_suffix(zone)
|
|
194
|
+
|
|
195
|
+
@jmespath.functions.signature(address_list)
|
|
196
|
+
def _func_first_ipv6(self, value: str | list[object] | None) -> str | None:
|
|
197
|
+
return first_ipv6(value)
|
|
198
|
+
|
|
199
|
+
@jmespath.functions.signature(address_list)
|
|
200
|
+
def _func_ipv6_private(self, value: str | list[object] | None) -> str | None:
|
|
201
|
+
return ipv6_private(value)
|
|
202
|
+
|
|
203
|
+
@jmespath.functions.signature(address_list)
|
|
204
|
+
def _func_ipv6_public(self, value: str | list[object] | None) -> str | None:
|
|
205
|
+
return ipv6_public(value)
|
|
206
|
+
|
|
207
|
+
@jmespath.functions.signature(object_or_null)
|
|
208
|
+
def _func_image_urn(self, reference: dict[str, object] | None) -> str | None:
|
|
209
|
+
return image_urn(reference)
|
|
210
|
+
|
|
211
|
+
return jmespath.Options(custom_functions=CloudMetadataFunctions())
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
# Copyright (c) 2026 SUSE LLC. All rights reserved.
|
|
2
|
+
#
|
|
3
|
+
# This file is part of cloud-metadata. cloud-metadata provides one command
|
|
4
|
+
# and one Python API that return the same standard instance metadata on every
|
|
5
|
+
# supported public cloud.
|
|
6
|
+
#
|
|
7
|
+
# This program is free software: you can redistribute it and/or modify
|
|
8
|
+
# it under the terms of the GNU General Public License as published by
|
|
9
|
+
# the Free Software Foundation, either version 3 of the License, or
|
|
10
|
+
# (at your option) any later version.
|
|
11
|
+
#
|
|
12
|
+
# This program is distributed in the hope that it will be useful,
|
|
13
|
+
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
14
|
+
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
15
|
+
# GNU General Public License for more details.
|
|
16
|
+
#
|
|
17
|
+
# You should have received a copy of the GNU General Public License
|
|
18
|
+
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
|
19
|
+
|
|
20
|
+
"""Built-in and runtime-registered cloud providers."""
|