yc2terraform 0.0.2__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.
@@ -0,0 +1,6 @@
1
+ from importlib import metadata as _metadata
2
+
3
+ try:
4
+ __version__ = _metadata.version('yc2terraform')
5
+ except _metadata.PackageNotFoundError: # pragma: no cover
6
+ __version__ = '0.0.0'
@@ -0,0 +1,3 @@
1
+ from _typeshed import Incomplete
2
+
3
+ __version__: Incomplete
@@ -0,0 +1,3 @@
1
+ from yc2terraform.cli import main
2
+
3
+ main()
@@ -0,0 +1 @@
1
+ from yc2terraform.cli import main as main
yc2terraform/api.py ADDED
@@ -0,0 +1,112 @@
1
+ """Minimal async Yandex Cloud REST client (read-only)."""
2
+
3
+ import asyncio
4
+ import logging
5
+ import os
6
+ import shutil
7
+ import subprocess
8
+ from typing import Any
9
+
10
+ import httpx
11
+
12
+ from yc2terraform.registry import API
13
+
14
+ log = logging.getLogger(__name__)
15
+
16
+ ENDPOINTS_URL = 'https://api.cloud.yandex.net/endpoints'
17
+ IAM_TOKENS_URL = 'https://iam.api.cloud.yandex.net/iam/v1/tokens'
18
+ RETRY_STATUS = {429, 500, 502, 503, 504}
19
+
20
+
21
+ class ApiError(RuntimeError):
22
+ pass
23
+
24
+
25
+ def _is_oauth(token: str) -> bool:
26
+ return token.startswith(('y0_', 'y1_', 'y2_', 'y3_', 'AQAA'))
27
+
28
+
29
+ def resolve_token() -> str | None:
30
+ """IAM/OAuth token from $YC_TOKEN, or a fresh IAM token from the `yc` CLI."""
31
+ if token := os.environ.get('YC_TOKEN'):
32
+ return token
33
+ if shutil.which('yc'):
34
+ result = subprocess.run(['yc', 'iam', 'create-token'], capture_output=True, text=True, check=False)
35
+ if result.returncode == 0 and result.stdout.strip():
36
+ log.debug('Using IAM token from `yc iam create-token`')
37
+ return result.stdout.strip()
38
+ return None
39
+
40
+
41
+ class YandexCloud:
42
+ def __init__(self, token: str, client: httpx.AsyncClient | None = None):
43
+ self._token = token
44
+ self._client = client or httpx.AsyncClient(timeout=30, transport=httpx.AsyncHTTPTransport(retries=3))
45
+ self._endpoints: dict[str, str] | None = None
46
+ self._lock = asyncio.Lock()
47
+
48
+ async def __aenter__(self) -> 'YandexCloud':
49
+ if _is_oauth(self._token):
50
+ resp = await self._client.post(IAM_TOKENS_URL, json={'yandexPassportOauthToken': self._token})
51
+ resp.raise_for_status()
52
+ self._token = resp.json()['iamToken']
53
+ return self
54
+
55
+ async def __aexit__(self, *exc: object) -> None:
56
+ await self._client.aclose()
57
+
58
+ @property
59
+ def iam_token(self) -> str:
60
+ return self._token
61
+
62
+ async def _request(self, url: str, params: dict[str, Any] | None = None, auth: bool = True) -> dict[str, Any]:
63
+ headers = {'Authorization': f'Bearer {self._token}'} if auth else {}
64
+ for attempt in range(4):
65
+ resp = await self._client.get(url, params=params, headers=headers)
66
+ if resp.status_code not in RETRY_STATUS or attempt == 3:
67
+ break
68
+ await asyncio.sleep(2**attempt)
69
+ log.debug('GET %s %s -> %s', url, params or '', resp.status_code)
70
+ if resp.status_code != 200:
71
+ raise ApiError(f'GET {resp.url} failed: {resp.status_code} {resp.text[:300]}')
72
+ return resp.json()
73
+
74
+ async def _endpoint(self, endpoint_id: str) -> str:
75
+ async with self._lock:
76
+ if self._endpoints is None:
77
+ data = await self._request(ENDPOINTS_URL, auth=False)
78
+ self._endpoints = {e['id']: e['address'] for e in data['endpoints']}
79
+ return self._endpoints[endpoint_id]
80
+
81
+ async def _base(self, tf_type: str) -> str:
82
+ api = API.get(tf_type)
83
+ if api is None:
84
+ raise ApiError(f'{tf_type}: API discovery is not supported for this type')
85
+ return f'https://{await self._endpoint(api.endpoint)}/{api.path}'
86
+
87
+ async def get(self, tf_type: str, resource_id: str) -> dict[str, Any]:
88
+ return await self._request(f'{await self._base(tf_type)}/{resource_id}')
89
+
90
+ async def list_items(
91
+ self, tf_type: str, *, folder_id: str | None = None, parent_id: str | None = None, sub: str | None = None
92
+ ) -> list[dict[str, Any]]:
93
+ """List a collection by folder, or a sub-collection of a parent (`clusters/{id}/users`)."""
94
+ url = await self._base(tf_type)
95
+ if parent_id:
96
+ url = f'{url}/{parent_id}/{sub}'
97
+ return await self._paginate(url, {'folderId': folder_id} if folder_id else {})
98
+
99
+ async def folders(self, cloud_id: str) -> list[dict[str, Any]]:
100
+ url = f'https://{await self._endpoint("resource-manager")}/resource-manager/v1/folders'
101
+ return await self._paginate(url, {'cloudId': cloud_id})
102
+
103
+ async def _paginate(self, url: str, params: dict[str, Any]) -> list[dict[str, Any]]:
104
+ params = {'pageSize': 1000, **params}
105
+ items: list[dict[str, Any]] = []
106
+ while True:
107
+ data = await self._request(url, params)
108
+ # A list response has exactly one list field (instances, clusters, dnsZones, ...).
109
+ items += next((v for v in data.values() if isinstance(v, list)), [])
110
+ if not (token := data.get('nextPageToken')):
111
+ return items
112
+ params['pageToken'] = token
yc2terraform/api.pyi ADDED
@@ -0,0 +1,23 @@
1
+ import httpx
2
+ from _typeshed import Incomplete
3
+ from typing import Any
4
+ from yc2terraform.registry import API as API
5
+
6
+ log: Incomplete
7
+ ENDPOINTS_URL: str
8
+ IAM_TOKENS_URL: str
9
+ RETRY_STATUS: Incomplete
10
+
11
+ class ApiError(RuntimeError): ...
12
+
13
+ def resolve_token() -> str | None: ...
14
+
15
+ class YandexCloud:
16
+ def __init__(self, token: str, client: httpx.AsyncClient | None = None) -> None: ...
17
+ async def __aenter__(self) -> YandexCloud: ...
18
+ async def __aexit__(self, *exc: object) -> None: ...
19
+ @property
20
+ def iam_token(self) -> str: ...
21
+ async def get(self, tf_type: str, resource_id: str) -> dict[str, Any]: ...
22
+ async def list_items(self, tf_type: str, *, folder_id: str | None = None, parent_id: str | None = None, sub: str | None = None) -> list[dict[str, Any]]: ...
23
+ async def folders(self, cloud_id: str) -> list[dict[str, Any]]: ...
yc2terraform/cli.py ADDED
@@ -0,0 +1,258 @@
1
+ """Command line interface."""
2
+
3
+ import asyncio
4
+ import logging
5
+ import os
6
+ from pathlib import Path
7
+ from typing import Annotated
8
+
9
+ import httpx
10
+ import typer
11
+ from rich.console import Console
12
+ from rich.logging import RichHandler
13
+ from rich.table import Table
14
+
15
+ from yc2terraform import __version__, yc
16
+ from yc2terraform.api import ApiError, YandexCloud, resolve_token
17
+ from yc2terraform.discovery import EXPANDERS, Child, Resource, folder_inventory
18
+ from yc2terraform.export import Options, Result, export
19
+ from yc2terraform.registry import API, FOLDER_KINDS, IMPORT_BY_NAME, parse_kind, tf_type
20
+ from yc2terraform.terraform import Terraform, TerraformError
21
+
22
+ app = typer.Typer(
23
+ help='Generate Terraform manifests (HCL) for existing Yandex Cloud resources.',
24
+ no_args_is_help=True,
25
+ rich_markup_mode='rich',
26
+ )
27
+ console = Console(stderr=True)
28
+
29
+ Output = Annotated[Path, typer.Option('--output', '-o', help='Directory for generated files.')]
30
+ Recursive = Annotated[
31
+ bool, typer.Option('--recursive', '-r', help='Also export linked resources (disks, users, subnets, ...).')
32
+ ]
33
+ ImportMetadata = Annotated[
34
+ bool, typer.Option('--import-metadata', help='Keep instance `metadata` (cloud-init, SSH keys).')
35
+ ]
36
+ ImportIds = Annotated[bool, typer.Option('--import-ids', help='Keep literal IDs instead of moving them to variables.')]
37
+ WithState = Annotated[
38
+ bool, typer.Option('--with-state', help='Also `terraform import` into the output directory state.')
39
+ ]
40
+ ImportBlocks = Annotated[
41
+ bool, typer.Option('--import-blocks', help='Add `import {}` blocks (Terraform >= 1.5) to manifests.')
42
+ ]
43
+ Parallel = Annotated[int, typer.Option('--parallel', '-p', min=1, help='Concurrent `terraform import` processes.')]
44
+ TerraformBin = Annotated[str, typer.Option('--terraform', help='Terraform binary (e.g. `tofu`).')]
45
+ Debug = Annotated[bool, typer.Option('--debug', help='Verbose logging.')]
46
+
47
+
48
+ def _setup(debug: bool) -> None:
49
+ logging.basicConfig(
50
+ level=logging.DEBUG if debug else logging.INFO,
51
+ format='%(message)s',
52
+ handlers=[RichHandler(console=console, show_path=False, show_time=debug)],
53
+ )
54
+ logging.getLogger('httpx').setLevel(logging.WARNING)
55
+
56
+
57
+ def _report(results: list[Result]) -> None:
58
+ table = Table('Address', 'File / error', title='yc2terraform')
59
+ for r in results:
60
+ table.add_row(r.address, f'[red]{r.error}[/]' if r.error else str(r.file))
61
+ console.print(table)
62
+ failed = sum(1 for r in results if r.error)
63
+ if failed:
64
+ console.print(f'[red]{failed} of {len(results)} failed[/]')
65
+ raise typer.Exit(1)
66
+ console.print('Done. Review the files, then run `terraform plan`: it should show no changes.')
67
+
68
+
69
+ async def _run(collect, opts: Options, binary: str, need_api: bool) -> list[Result]: # noqa: ANN001
70
+ token = resolve_token()
71
+ if need_api and not token:
72
+ raise TerraformError('YC_TOKEN is not set and `yc iam create-token` failed: the YC API is needed here.')
73
+ if not token:
74
+ return await collect(None, Terraform(binary), opts)
75
+ async with YandexCloud(token) as api:
76
+ # Hand the token to the provider unless it already has its own credentials.
77
+ own_auth = any(os.environ.get(k) for k in ('YC_TOKEN', 'YC_SERVICE_ACCOUNT_KEY_FILE'))
78
+ return await collect(api, Terraform(binary, env=None if own_auth else {'YC_TOKEN': api.iam_token}), opts)
79
+
80
+
81
+ def _main(coro) -> list[Result]: # noqa: ANN001
82
+ try:
83
+ return asyncio.run(coro)
84
+ except (TerraformError, ApiError, httpx.HTTPError) as e:
85
+ console.print(f'[red]{e}[/]')
86
+ raise typer.Exit(2) from e
87
+
88
+
89
+ @app.command('import')
90
+ def import_(
91
+ service: Annotated[
92
+ str, typer.Argument(help='Service as in `yc`: compute, vpc, managed-postgresql, ... (or a yandex_* type).')
93
+ ],
94
+ subitem_type: Annotated[str, typer.Argument(help='Resource type as in `yc`: instance, cluster, node-group, ...')],
95
+ name: Annotated[str, typer.Argument(help='Name for the Terraform resource (use the cloud name).')],
96
+ id: Annotated[
97
+ str | None, typer.Argument(help='Cloud ID. Omit it to look the ID up by NAME with `yc ... get --name`.')
98
+ ] = None,
99
+ folder_id: Annotated[
100
+ str | None, typer.Option('--folder-id', help='Folder for the name lookup (default: yc profile folder).')
101
+ ] = None,
102
+ output: Output = Path('.'),
103
+ recursive: Recursive = False,
104
+ import_metadata: ImportMetadata = False,
105
+ import_ids: ImportIds = False,
106
+ with_state: WithState = False,
107
+ import_blocks: ImportBlocks = False,
108
+ parallel: Parallel = 4,
109
+ terraform: TerraformBin = 'terraform',
110
+ debug: Debug = False,
111
+ ) -> None:
112
+ """Export one resource (and with -r everything it depends on).
113
+
114
+ [dim]yc2terraform import -r managed-postgresql cluster pg-prod c9q8...[/]
115
+ """
116
+ _setup(debug)
117
+ kind = tf_type(service, subitem_type)
118
+ resource_id = id or (name if kind in IMPORT_BY_NAME else _lookup_id(service, subitem_type, name, folder_id))
119
+ root: Child = (Resource(kind, resource_id, name), None)
120
+ opts = Options(output, recursive, import_metadata, import_ids, with_state, import_blocks, parallel)
121
+
122
+ async def collect(api, tf, opts): # noqa: ANN001, ANN202
123
+ return await export([root], opts, tf, api)
124
+
125
+ _report(_main(_run(collect, opts, terraform, need_api=recursive and kind in EXPANDERS)))
126
+
127
+
128
+ def _lookup_id(service: str, subitem_type: str, name: str, folder_id: str | None) -> str:
129
+ if not yc.available():
130
+ raise typer.BadParameter('ID is required (or install the `yc` CLI to look it up by name)', param_hint='ID')
131
+ try:
132
+ return asyncio.run(yc.get_by_name(service, subitem_type, name, folder_id))['id']
133
+ except yc.YcError as e:
134
+ raise typer.BadParameter(f'cannot find {service} {subitem_type} {name!r}: {e}', param_hint='NAME') from e
135
+
136
+
137
+ def _kinds(only: list[str] | None, skip: list[str] | None) -> list[tuple[str, str]]:
138
+ try:
139
+ kinds = [parse_kind(k) for k in only] if only else list(FOLDER_KINDS)
140
+ drop = {parse_kind(k) for k in skip or []}
141
+ except ValueError as e:
142
+ raise typer.BadParameter(str(e)) from e
143
+ return [k for k in kinds if k not in drop]
144
+
145
+
146
+ def _folder_id(value: str | None) -> str:
147
+ if folder := value or yc.default_folder():
148
+ return folder
149
+ raise typer.BadParameter('pass FOLDER_ID, set $YC_FOLDER_ID or configure `yc config set folder-id`')
150
+
151
+
152
+ def _need_api(recursive: bool) -> bool:
153
+ return recursive or not yc.available()
154
+
155
+
156
+ Only = Annotated[
157
+ list[str] | None,
158
+ typer.Option(
159
+ '--only', help='Export only these types: compute.instance, "compute instance" or a yandex_* type. Repeatable.'
160
+ ),
161
+ ]
162
+ Skip = Annotated[list[str] | None, typer.Option('--skip', help='Skip these types. Repeatable.')]
163
+ NoRecursive = Annotated[bool, typer.Option('--no-recursive', help='Do not follow links (disks, subnets, users, ...).')]
164
+
165
+
166
+ @app.command()
167
+ def folder(
168
+ folder_id: Annotated[
169
+ str | None, typer.Argument(help='Folder ID (default: $YC_FOLDER_ID, then the yc profile folder).')
170
+ ] = None,
171
+ only: Only = None,
172
+ skip: Skip = None,
173
+ output: Output = Path('.'),
174
+ no_recursive: NoRecursive = False,
175
+ import_metadata: ImportMetadata = False,
176
+ import_ids: ImportIds = False,
177
+ with_state: WithState = False,
178
+ import_blocks: ImportBlocks = False,
179
+ parallel: Parallel = 4,
180
+ terraform: TerraformBin = 'terraform',
181
+ debug: Debug = False,
182
+ ) -> None:
183
+ """Dump a whole folder to Terraform: every type from `yc2terraform types`, plus linked resources.
184
+
185
+ [dim]yc2terraform folder --with-state --import-ids --import-metadata[/]
186
+ """
187
+ _setup(debug)
188
+ kinds = _kinds(only, skip)
189
+ folder_id = _folder_id(folder_id)
190
+ opts = Options(output, not no_recursive, import_metadata, import_ids, with_state, import_blocks, parallel)
191
+
192
+ async def collect(api, tf, opts): # noqa: ANN001, ANN202
193
+ return await export(await folder_inventory(api, folder_id, kinds), opts, tf, api)
194
+
195
+ _report(_main(_run(collect, opts, terraform, need_api=_need_api(opts.recursive))))
196
+
197
+
198
+ @app.command()
199
+ def cloud(
200
+ cloud_id: Annotated[str, typer.Argument(help='Cloud ID.')],
201
+ only: Only = None,
202
+ skip: Skip = None,
203
+ output: Output = Path('.'),
204
+ no_recursive: NoRecursive = False,
205
+ import_metadata: ImportMetadata = False,
206
+ import_ids: ImportIds = False,
207
+ with_state: WithState = False,
208
+ import_blocks: ImportBlocks = False,
209
+ parallel: Parallel = 4,
210
+ terraform: TerraformBin = 'terraform',
211
+ debug: Debug = False,
212
+ ) -> None:
213
+ """Export every folder of a cloud, one sub-directory per folder."""
214
+ _setup(debug)
215
+ kinds = _kinds(only, skip)
216
+ opts = Options(output, not no_recursive, import_metadata, import_ids, with_state, import_blocks, parallel)
217
+
218
+ async def collect(api, tf, opts): # noqa: ANN001, ANN202
219
+ results = []
220
+ for f in await api.folders(cloud_id):
221
+ logging.getLogger(__name__).info('Folder %s (%s)', f['name'], f['id'])
222
+ roots = await folder_inventory(api, f['id'], kinds)
223
+ if roots:
224
+ folder_opts = Options(**{**opts.__dict__, 'output': opts.output / f['name']})
225
+ results += await export(roots, folder_opts, tf, api)
226
+ return results
227
+
228
+ _report(_main(_run(collect, opts, terraform, need_api=True)))
229
+
230
+
231
+ @app.command()
232
+ def types() -> None:
233
+ """Show the types exported by `folder` / `cloud` and how they are discovered."""
234
+ table = Table('yc service / type', 'Terraform type', 'Listed via', 'Recursive children')
235
+ for service, resource in FOLDER_KINDS:
236
+ kind = tf_type(service, resource)
237
+ table.add_row(
238
+ f'{service} {resource}', kind, 'yc, REST' if kind in API else 'yc', 'yes' if kind in EXPANDERS else ''
239
+ )
240
+ Console().print(table)
241
+ console.print('`import` accepts any other yandex_* type too (without discovery).')
242
+
243
+
244
+ def _version(value: bool) -> None:
245
+ if value:
246
+ print(__version__)
247
+ raise typer.Exit
248
+
249
+
250
+ @app.callback()
251
+ def _root(
252
+ version: Annotated[bool, typer.Option('--version', callback=_version, is_eager=True, help='Show version.')] = False,
253
+ ) -> None:
254
+ pass
255
+
256
+
257
+ def main() -> None:
258
+ app()
yc2terraform/cli.pyi ADDED
@@ -0,0 +1,31 @@
1
+ from _typeshed import Incomplete
2
+ from typing import Annotated
3
+ from yc2terraform import __version__ as __version__, yc as yc
4
+ from yc2terraform.api import ApiError as ApiError, YandexCloud as YandexCloud, resolve_token as resolve_token
5
+ from yc2terraform.discovery import Child as Child, EXPANDERS as EXPANDERS, Resource as Resource, folder_inventory as folder_inventory
6
+ from yc2terraform.export import Options as Options, Result as Result, export as export
7
+ from yc2terraform.registry import API as API, FOLDER_KINDS as FOLDER_KINDS, IMPORT_BY_NAME as IMPORT_BY_NAME, parse_kind as parse_kind, tf_type as tf_type
8
+ from yc2terraform.terraform import Terraform as Terraform, TerraformError as TerraformError
9
+
10
+ app: Incomplete
11
+ console: Incomplete
12
+ Output: Incomplete
13
+ Recursive: Incomplete
14
+ ImportMetadata: Incomplete
15
+ ImportIds: Incomplete
16
+ WithState: Incomplete
17
+ ImportBlocks: Incomplete
18
+ Parallel: Incomplete
19
+ TerraformBin: Incomplete
20
+ Debug: Incomplete
21
+
22
+ def import_(service: Annotated[str, None], subitem_type: Annotated[str, None], name: Annotated[str, None], id: Annotated[str | None, None] = None, folder_id: Annotated[str | None, None] = None, output: Output = ..., recursive: Recursive = False, import_metadata: ImportMetadata = False, import_ids: ImportIds = False, with_state: WithState = False, import_blocks: ImportBlocks = False, parallel: Parallel = 4, terraform: TerraformBin = 'terraform', debug: Debug = False) -> None: ...
23
+
24
+ Only: Incomplete
25
+ Skip: Incomplete
26
+ NoRecursive: Incomplete
27
+
28
+ def folder(folder_id: Annotated[str | None, None] = None, only: Only = None, skip: Skip = None, output: Output = ..., no_recursive: NoRecursive = False, import_metadata: ImportMetadata = False, import_ids: ImportIds = False, with_state: WithState = False, import_blocks: ImportBlocks = False, parallel: Parallel = 4, terraform: TerraformBin = 'terraform', debug: Debug = False) -> None: ...
29
+ def cloud(cloud_id: Annotated[str, None], only: Only = None, skip: Skip = None, output: Output = ..., no_recursive: NoRecursive = False, import_metadata: ImportMetadata = False, import_ids: ImportIds = False, with_state: WithState = False, import_blocks: ImportBlocks = False, parallel: Parallel = 4, terraform: TerraformBin = 'terraform', debug: Debug = False) -> None: ...
30
+ def types() -> None: ...
31
+ def main() -> None: ...