netherframe.backends.remote 0.2.0__tar.gz
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.
- netherframe_backends_remote-0.2.0/LICENSE +21 -0
- netherframe_backends_remote-0.2.0/PKG-INFO +58 -0
- netherframe_backends_remote-0.2.0/README.md +36 -0
- netherframe_backends_remote-0.2.0/netherframe/backends/remote/__init__.py +5 -0
- netherframe_backends_remote-0.2.0/netherframe/backends/remote/py.typed +0 -0
- netherframe_backends_remote-0.2.0/netherframe/backends/remote/remote.py +515 -0
- netherframe_backends_remote-0.2.0/nf/backends/remote/__init__.py +4 -0
- netherframe_backends_remote-0.2.0/nf/backends/remote/py.typed +0 -0
- netherframe_backends_remote-0.2.0/nf/backends/remote/remote.py +4 -0
- netherframe_backends_remote-0.2.0/pyproject.toml +47 -0
- netherframe_backends_remote-0.2.0/pyproject.toml.orig +46 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Netherframe
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: netherframe.backends.remote
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Terraform Cloud/Enterprise backend implementations for Netherframe
|
|
5
|
+
Author: Sourabh Cheedella
|
|
6
|
+
Author-email: Sourabh Cheedella <cheedella.sourabh@gmail.com>
|
|
7
|
+
License-Expression: MIT
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Classifier: Development Status :: 4 - Beta
|
|
10
|
+
Classifier: Intended Audience :: Developers
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
12
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
13
|
+
Classifier: Topic :: System :: Systems Administration
|
|
14
|
+
Requires-Dist: netherframe-core>=0.9.0
|
|
15
|
+
Requires-Dist: requests>=2.34.2
|
|
16
|
+
Requires-Dist: pytest>=9.2.0 ; extra == 'dev'
|
|
17
|
+
Requires-Python: >=3.14
|
|
18
|
+
Project-URL: Homepage, https://netherframe.arsenal.sh
|
|
19
|
+
Project-URL: Repository, https://github.com/arsenal-sh/netherframe
|
|
20
|
+
Provides-Extra: dev
|
|
21
|
+
Description-Content-Type: text/markdown
|
|
22
|
+
|
|
23
|
+
# nf.backends.remote
|
|
24
|
+
|
|
25
|
+
Terraform Cloud/Enterprise backend implementations for Netherframe Infrastructure as Code framework.
|
|
26
|
+
|
|
27
|
+
## Installation
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
pip install netherframe.backends.remote
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
## Usage
|
|
34
|
+
|
|
35
|
+
```python
|
|
36
|
+
from nf.backends.remote import RemoteBackend, RemoteStateBackend
|
|
37
|
+
|
|
38
|
+
# For Terraform synthesis mode
|
|
39
|
+
backend = RemoteBackend(nf_scope=stack, organization="my-org", workspaces={"name": "my-app-prod"})
|
|
40
|
+
|
|
41
|
+
# For native execution mode
|
|
42
|
+
state_backend = RemoteStateBackend(hostname="app.terraform.io", organization="my-org", workspaces={"name": "my-app-prod"}, token="your-api-token")
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
## Features
|
|
46
|
+
|
|
47
|
+
- Terraform Cloud/Enterprise integration
|
|
48
|
+
- Compatible with Terraform's remote backend
|
|
49
|
+
- API-based state management: state is stored as workspace state versions and
|
|
50
|
+
locked with the workspace lock
|
|
51
|
+
- Workspaces are selected by `name`, or by `prefix` plus `TF_WORKSPACE`
|
|
52
|
+
- Conditional writes: a state version is uploaded only while the workspace's state is the one the run read
|
|
53
|
+
- Force-unlock of the workspace (its lock ID is the workspace ID); pre-apply checkpoints are state versions, which HCP Terraform keeps
|
|
54
|
+
|
|
55
|
+
`RemoteStateBackend` keeps Netherframe's state under a `netherframe` key of an
|
|
56
|
+
otherwise empty Terraform state document, so Terraform itself does not see the
|
|
57
|
+
resources in that workspace. Loading a workspace whose state was written by
|
|
58
|
+
Terraform raises an error instead of silently returning empty state.
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
# nf.backends.remote
|
|
2
|
+
|
|
3
|
+
Terraform Cloud/Enterprise backend implementations for Netherframe Infrastructure as Code framework.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pip install netherframe.backends.remote
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Usage
|
|
12
|
+
|
|
13
|
+
```python
|
|
14
|
+
from nf.backends.remote import RemoteBackend, RemoteStateBackend
|
|
15
|
+
|
|
16
|
+
# For Terraform synthesis mode
|
|
17
|
+
backend = RemoteBackend(nf_scope=stack, organization="my-org", workspaces={"name": "my-app-prod"})
|
|
18
|
+
|
|
19
|
+
# For native execution mode
|
|
20
|
+
state_backend = RemoteStateBackend(hostname="app.terraform.io", organization="my-org", workspaces={"name": "my-app-prod"}, token="your-api-token")
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
## Features
|
|
24
|
+
|
|
25
|
+
- Terraform Cloud/Enterprise integration
|
|
26
|
+
- Compatible with Terraform's remote backend
|
|
27
|
+
- API-based state management: state is stored as workspace state versions and
|
|
28
|
+
locked with the workspace lock
|
|
29
|
+
- Workspaces are selected by `name`, or by `prefix` plus `TF_WORKSPACE`
|
|
30
|
+
- Conditional writes: a state version is uploaded only while the workspace's state is the one the run read
|
|
31
|
+
- Force-unlock of the workspace (its lock ID is the workspace ID); pre-apply checkpoints are state versions, which HCP Terraform keeps
|
|
32
|
+
|
|
33
|
+
`RemoteStateBackend` keeps Netherframe's state under a `netherframe` key of an
|
|
34
|
+
otherwise empty Terraform state document, so Terraform itself does not see the
|
|
35
|
+
resources in that workspace. Loading a workspace whose state was written by
|
|
36
|
+
Terraform raises an error instead of silently returning empty state.
|
|
File without changes
|
|
@@ -0,0 +1,515 @@
|
|
|
1
|
+
"""Terraform Cloud/Enterprise backend implementation."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import base64
|
|
6
|
+
import hashlib
|
|
7
|
+
import os
|
|
8
|
+
import subprocess
|
|
9
|
+
import uuid
|
|
10
|
+
from typing import TYPE_CHECKING, Any
|
|
11
|
+
|
|
12
|
+
from netherframe.core.backends.state_backend import state_conflict
|
|
13
|
+
from netherframe.core.backends.state_engine import State, StateBackend
|
|
14
|
+
from netherframe.core.backends.state_models import StateVersion
|
|
15
|
+
from netherframe.core.constructs.app_stack import App, Stack
|
|
16
|
+
from netherframe.core.constructs.backend_base import Backend
|
|
17
|
+
from netherframe.core.exceptions import StateLockError
|
|
18
|
+
from netherframe.core.logging import get_logger
|
|
19
|
+
from netherframe.core.serialization import orjson_compat as json
|
|
20
|
+
|
|
21
|
+
if TYPE_CHECKING:
|
|
22
|
+
from netherframe.core.constructs.framework_settings import BackendSettings
|
|
23
|
+
|
|
24
|
+
logger = get_logger(__name__)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class RemoteBackend(Backend):
|
|
28
|
+
"""Terraform Cloud/Enterprise remote backend."""
|
|
29
|
+
|
|
30
|
+
@property
|
|
31
|
+
def backend_type(self) -> str:
|
|
32
|
+
"""Get the backend type name."""
|
|
33
|
+
return "remote"
|
|
34
|
+
|
|
35
|
+
def __init__(
|
|
36
|
+
self,
|
|
37
|
+
nf_scope: Stack,
|
|
38
|
+
*,
|
|
39
|
+
organization: str,
|
|
40
|
+
workspaces: dict[str, str],
|
|
41
|
+
nf_backend_settings: BackendSettings | None = None,
|
|
42
|
+
**kwargs: Any,
|
|
43
|
+
) -> None:
|
|
44
|
+
"""Initialize remote backend.
|
|
45
|
+
|
|
46
|
+
Args:
|
|
47
|
+
nf_scope: Parent stack
|
|
48
|
+
organization: Terraform Cloud organization
|
|
49
|
+
workspaces: Workspace configuration
|
|
50
|
+
**kwargs: Additional backend configuration
|
|
51
|
+
|
|
52
|
+
"""
|
|
53
|
+
super().__init__(
|
|
54
|
+
nf_scope=nf_scope,
|
|
55
|
+
nf_id="backend",
|
|
56
|
+
nf_backend_settings=nf_backend_settings,
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
self.organization = organization
|
|
60
|
+
self.workspaces = workspaces
|
|
61
|
+
self.additional_config = kwargs
|
|
62
|
+
|
|
63
|
+
def _build_config(self) -> dict[str, Any]:
|
|
64
|
+
"""Build Terraform remote backend configuration."""
|
|
65
|
+
config: dict[str, Any] = {
|
|
66
|
+
"organization": self.organization,
|
|
67
|
+
"workspaces": self.workspaces,
|
|
68
|
+
}
|
|
69
|
+
config.update(self.additional_config)
|
|
70
|
+
return config
|
|
71
|
+
|
|
72
|
+
def to_hcl(self) -> dict[str, Any]:
|
|
73
|
+
"""Convert backend configuration to HCL format."""
|
|
74
|
+
return self._build_config()
|
|
75
|
+
|
|
76
|
+
def _to_config(self) -> dict[str, Any]:
|
|
77
|
+
"""Convert to Terraform backend configuration."""
|
|
78
|
+
return {"remote": self.to_hcl()}
|
|
79
|
+
|
|
80
|
+
def get_state_resources(self) -> list[dict[str, Any]] | None:
|
|
81
|
+
"""Get resources from Terraform Cloud state.
|
|
82
|
+
|
|
83
|
+
This would require Terraform Cloud API access or terraform state pull.
|
|
84
|
+
"""
|
|
85
|
+
# For Terraform Cloud, we'd typically use the API or terraform state pull
|
|
86
|
+
# This is a simplified implementation
|
|
87
|
+
stack = self.nf_scope
|
|
88
|
+
if not isinstance(stack, Stack) or not isinstance(stack.nf_scope, App):
|
|
89
|
+
return None
|
|
90
|
+
app = stack.nf_scope
|
|
91
|
+
|
|
92
|
+
try:
|
|
93
|
+
working_dir = f"{app.outdir}/{app.nf_id}/{stack.nf_id}"
|
|
94
|
+
result = subprocess.run(
|
|
95
|
+
["terraform", "state", "pull"],
|
|
96
|
+
cwd=working_dir,
|
|
97
|
+
capture_output=True,
|
|
98
|
+
text=True,
|
|
99
|
+
check=True,
|
|
100
|
+
)
|
|
101
|
+
state = json.loads(result.stdout)
|
|
102
|
+
return state.get("resources", [])
|
|
103
|
+
|
|
104
|
+
except subprocess.CalledProcessError, json.JSONDecodeError, FileNotFoundError:
|
|
105
|
+
pass
|
|
106
|
+
|
|
107
|
+
return None
|
|
108
|
+
|
|
109
|
+
def resource_exists_at_address(self, address: str) -> bool | None:
|
|
110
|
+
"""Check if a resource exists at the given Terraform address.
|
|
111
|
+
|
|
112
|
+
Args:
|
|
113
|
+
address: Terraform resource address (e.g., "aws_s3_bucket.test")
|
|
114
|
+
|
|
115
|
+
Returns:
|
|
116
|
+
True if resource exists, False if not, None if unable to check
|
|
117
|
+
|
|
118
|
+
"""
|
|
119
|
+
resources = self.get_state_resources()
|
|
120
|
+
if resources is None:
|
|
121
|
+
return None
|
|
122
|
+
|
|
123
|
+
parsed_address = self._parse_resource_address(address)
|
|
124
|
+
if parsed_address is None:
|
|
125
|
+
return False
|
|
126
|
+
module_path, resource_type, resource_name = parsed_address
|
|
127
|
+
|
|
128
|
+
# Check each resource
|
|
129
|
+
for resource in resources:
|
|
130
|
+
# Match type and name
|
|
131
|
+
if resource.get("type") == resource_type and resource.get("name") == resource_name:
|
|
132
|
+
# Check module path if specified
|
|
133
|
+
if module_path:
|
|
134
|
+
resource_module = resource.get("module", "")
|
|
135
|
+
# Extract module path from resource
|
|
136
|
+
if resource_module:
|
|
137
|
+
# Format: "module.network" -> ["network"]
|
|
138
|
+
resource_module_parts = []
|
|
139
|
+
module_parts = resource_module.split(".")
|
|
140
|
+
for j in range(1, len(module_parts), 2):
|
|
141
|
+
resource_module_parts.append(module_parts[j])
|
|
142
|
+
|
|
143
|
+
# Compare module paths
|
|
144
|
+
if resource_module_parts == module_path:
|
|
145
|
+
return True
|
|
146
|
+
else:
|
|
147
|
+
# Resource is not in a module but address expects module
|
|
148
|
+
continue
|
|
149
|
+
# No module path in address, resource should not be in a module
|
|
150
|
+
elif not resource.get("module"):
|
|
151
|
+
return True
|
|
152
|
+
|
|
153
|
+
return False
|
|
154
|
+
|
|
155
|
+
def bootstrap_ready(self) -> tuple[bool, str]:
|
|
156
|
+
"""Remote backend does not support bootstrapping."""
|
|
157
|
+
return False, "Terraform Cloud/Enterprise backend cannot be bootstrapped"
|
|
158
|
+
|
|
159
|
+
@staticmethod
|
|
160
|
+
def _parse_resource_address(address: str) -> tuple[list[str], str, str] | None:
|
|
161
|
+
"""Parse a Terraform resource address into module path, type, and name."""
|
|
162
|
+
parts = address.split(".")
|
|
163
|
+
if len(parts) < 2:
|
|
164
|
+
return None
|
|
165
|
+
|
|
166
|
+
module_path = []
|
|
167
|
+
i = 0
|
|
168
|
+
while i < len(parts) - 2 and parts[i] == "module":
|
|
169
|
+
module_path.append(parts[i + 1])
|
|
170
|
+
i += 2
|
|
171
|
+
|
|
172
|
+
if i + 1 >= len(parts):
|
|
173
|
+
return None
|
|
174
|
+
return module_path, parts[i], parts[i + 1]
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
class RemoteStateBackend(StateBackend):
|
|
178
|
+
"""Terraform Cloud/Enterprise remote backend.
|
|
179
|
+
|
|
180
|
+
Stores state as workspace state versions through the HCP Terraform API and locks
|
|
181
|
+
state with the workspace lock. The Netherframe state is kept under a
|
|
182
|
+
``netherframe`` key of an otherwise empty Terraform v4 state document, so the
|
|
183
|
+
workspace accepts it without Terraform having to understand Netherframe's model.
|
|
184
|
+
|
|
185
|
+
Only the holder of the workspace lock can create a state version, so a conditional
|
|
186
|
+
write compares the stored serial and lineage with the expected ones and uploads
|
|
187
|
+
while holding it: no other run can write in between.
|
|
188
|
+
"""
|
|
189
|
+
|
|
190
|
+
conditional_writes = True
|
|
191
|
+
|
|
192
|
+
REQUEST_TIMEOUT_SECONDS = 30
|
|
193
|
+
STATE_KEY = "netherframe"
|
|
194
|
+
|
|
195
|
+
def __init__(
|
|
196
|
+
self,
|
|
197
|
+
hostname: str,
|
|
198
|
+
organization: str,
|
|
199
|
+
workspaces: dict[str, str],
|
|
200
|
+
token: str | None = None,
|
|
201
|
+
) -> None:
|
|
202
|
+
"""Initialize remote state backend.
|
|
203
|
+
|
|
204
|
+
Args:
|
|
205
|
+
hostname: Terraform Cloud/Enterprise hostname
|
|
206
|
+
organization: Organization name
|
|
207
|
+
workspaces: Workspace configuration
|
|
208
|
+
token: API token
|
|
209
|
+
|
|
210
|
+
"""
|
|
211
|
+
self.hostname = hostname
|
|
212
|
+
self.organization = organization
|
|
213
|
+
self.workspaces = workspaces
|
|
214
|
+
self.token = token
|
|
215
|
+
self._workspace_id: str | None = None
|
|
216
|
+
self._locked = False
|
|
217
|
+
|
|
218
|
+
# Set up headers
|
|
219
|
+
self.headers = {
|
|
220
|
+
"Content-Type": "application/vnd.api+json",
|
|
221
|
+
}
|
|
222
|
+
if token:
|
|
223
|
+
self.headers["Authorization"] = f"Bearer {token}"
|
|
224
|
+
|
|
225
|
+
# Import requests
|
|
226
|
+
try:
|
|
227
|
+
import requests
|
|
228
|
+
|
|
229
|
+
# Any: tests and callers may substitute another requests-compatible client
|
|
230
|
+
self.requests: Any = requests
|
|
231
|
+
except ImportError as e:
|
|
232
|
+
raise RuntimeError("requests is required for remote backend") from e
|
|
233
|
+
|
|
234
|
+
def get_backend_type(self) -> str:
|
|
235
|
+
"""Get the backend type identifier.
|
|
236
|
+
|
|
237
|
+
Returns:
|
|
238
|
+
"remote" for Terraform Cloud/Enterprise backend
|
|
239
|
+
|
|
240
|
+
"""
|
|
241
|
+
return "remote"
|
|
242
|
+
|
|
243
|
+
def get_config(self) -> dict[str, Any]:
|
|
244
|
+
"""Get the backend configuration.
|
|
245
|
+
|
|
246
|
+
Returns:
|
|
247
|
+
Configuration dictionary with all parameters needed to recreate this backend
|
|
248
|
+
|
|
249
|
+
"""
|
|
250
|
+
config = {
|
|
251
|
+
"hostname": self.hostname,
|
|
252
|
+
"organization": self.organization,
|
|
253
|
+
"workspaces": self.workspaces,
|
|
254
|
+
}
|
|
255
|
+
# Only include token in config if it was provided
|
|
256
|
+
if self.token:
|
|
257
|
+
config["token"] = self.token
|
|
258
|
+
return config
|
|
259
|
+
|
|
260
|
+
# -- API helpers -------------------------------------------------------------
|
|
261
|
+
|
|
262
|
+
def _api_url(self, path: str) -> str:
|
|
263
|
+
return f"https://{self.hostname}/api/v2{path}"
|
|
264
|
+
|
|
265
|
+
def _workspace_name(self) -> str:
|
|
266
|
+
"""Return the workspace to use, like Terraform's remote backend selects it."""
|
|
267
|
+
name = self.workspaces.get("name")
|
|
268
|
+
if name:
|
|
269
|
+
return name
|
|
270
|
+
prefix = self.workspaces.get("prefix")
|
|
271
|
+
selected = os.environ.get("TF_WORKSPACE")
|
|
272
|
+
if prefix and selected:
|
|
273
|
+
return f"{prefix}{selected}"
|
|
274
|
+
raise ValueError(
|
|
275
|
+
"RemoteStateBackend needs workspaces={'name': ...}, or a 'prefix' together with TF_WORKSPACE",
|
|
276
|
+
)
|
|
277
|
+
|
|
278
|
+
def state_identity(self) -> dict[str, Any]:
|
|
279
|
+
return {"backend": "remote", "hostname": self.hostname, "organization": self.organization, "workspace_id": self._get_workspace_id()}
|
|
280
|
+
|
|
281
|
+
def _request(self, method: str, url: str, *, expected: tuple[int, ...], **kwargs: Any) -> Any:
|
|
282
|
+
"""Send an API request and return the response if its status is expected."""
|
|
283
|
+
response = self.requests.request(
|
|
284
|
+
method,
|
|
285
|
+
url,
|
|
286
|
+
headers=self.headers,
|
|
287
|
+
timeout=self.REQUEST_TIMEOUT_SECONDS,
|
|
288
|
+
**kwargs,
|
|
289
|
+
)
|
|
290
|
+
if response.status_code not in expected:
|
|
291
|
+
raise RuntimeError(
|
|
292
|
+
f"Terraform Cloud API {method} {url} failed with HTTP {response.status_code}: {response.text}",
|
|
293
|
+
)
|
|
294
|
+
return response
|
|
295
|
+
|
|
296
|
+
def _get_workspace_id(self) -> str:
|
|
297
|
+
if self._workspace_id is None:
|
|
298
|
+
name = self._workspace_name()
|
|
299
|
+
response = self._request(
|
|
300
|
+
"GET",
|
|
301
|
+
self._api_url(f"/organizations/{self.organization}/workspaces/{name}"),
|
|
302
|
+
expected=(200,),
|
|
303
|
+
)
|
|
304
|
+
self._workspace_id = response.json()["data"]["id"]
|
|
305
|
+
return self._workspace_id
|
|
306
|
+
|
|
307
|
+
def _download_current_state(self) -> dict[str, Any] | None:
|
|
308
|
+
"""Return the workspace's current state document, or None if it has none."""
|
|
309
|
+
workspace_id = self._get_workspace_id()
|
|
310
|
+
response = self._request(
|
|
311
|
+
"GET",
|
|
312
|
+
self._api_url(f"/workspaces/{workspace_id}/current-state-version"),
|
|
313
|
+
expected=(200, 404),
|
|
314
|
+
)
|
|
315
|
+
if response.status_code == 404:
|
|
316
|
+
return None
|
|
317
|
+
attributes = response.json()["data"]["attributes"]
|
|
318
|
+
download_url = attributes.get("hosted-state-download-url")
|
|
319
|
+
if not download_url:
|
|
320
|
+
raise RuntimeError(f"Current state version of workspace {workspace_id} has no download URL")
|
|
321
|
+
return json.loads(self._request("GET", download_url, expected=(200,)).content)
|
|
322
|
+
|
|
323
|
+
def _state_from_document(self, document: dict[str, Any]) -> State:
|
|
324
|
+
if self.STATE_KEY in document:
|
|
325
|
+
return State.from_dict(document[self.STATE_KEY])
|
|
326
|
+
if isinstance(document.get("resources", []), dict):
|
|
327
|
+
return State.from_dict(document)
|
|
328
|
+
raise ValueError(
|
|
329
|
+
f"Workspace {self._workspace_name()} holds Terraform state that was not written by Netherframe",
|
|
330
|
+
)
|
|
331
|
+
|
|
332
|
+
# -- StateBackend --------------------------------------------------------------
|
|
333
|
+
|
|
334
|
+
def load(self) -> State:
|
|
335
|
+
"""Load state from the workspace's current state version.
|
|
336
|
+
|
|
337
|
+
Returns:
|
|
338
|
+
State object containing the loaded state
|
|
339
|
+
|
|
340
|
+
"""
|
|
341
|
+
try:
|
|
342
|
+
document = self._download_current_state()
|
|
343
|
+
if document is None:
|
|
344
|
+
logger.info(f"No state in workspace {self._workspace_name()}, will create new state")
|
|
345
|
+
return State()
|
|
346
|
+
logger.info(f"Loaded state from workspace {self._workspace_name()}")
|
|
347
|
+
return self._state_from_document(document)
|
|
348
|
+
except Exception as e:
|
|
349
|
+
logger.error("Failed to load state from Terraform Cloud: %s", e)
|
|
350
|
+
raise
|
|
351
|
+
|
|
352
|
+
def save(self, state: State) -> None:
|
|
353
|
+
"""Save state as a new state version of the workspace.
|
|
354
|
+
|
|
355
|
+
Terraform Cloud only accepts state versions from the holder of the workspace
|
|
356
|
+
lock, so the workspace is locked for the upload unless we already hold it.
|
|
357
|
+
|
|
358
|
+
Args:
|
|
359
|
+
state: State object to save
|
|
360
|
+
|
|
361
|
+
"""
|
|
362
|
+
self._save(state, None)
|
|
363
|
+
|
|
364
|
+
def save_if_unchanged(self, state: State, expected: StateVersion) -> None:
|
|
365
|
+
"""Save state as a new state version, only while the workspace's state is still ``expected``."""
|
|
366
|
+
self._save(state, expected)
|
|
367
|
+
|
|
368
|
+
def _save(self, state: State, expected: StateVersion | None) -> None:
|
|
369
|
+
lock_for_save = not self._locked
|
|
370
|
+
if lock_for_save and not self.lock({"operation": "save"}):
|
|
371
|
+
raise StateLockError(f"Cannot save state: workspace {self._workspace_name()} is locked")
|
|
372
|
+
try:
|
|
373
|
+
current = self._download_current_state() or {}
|
|
374
|
+
if expected is not None:
|
|
375
|
+
stored = StateVersion.of(self._state_from_document(current)) if current else StateVersion()
|
|
376
|
+
if stored != expected:
|
|
377
|
+
raise state_conflict(f"workspace {self._workspace_name()}", stored, expected)
|
|
378
|
+
# The Terraform document's serial only ever increases; its lineage is the workspace's
|
|
379
|
+
serial = int(current.get("serial", 0)) + 1
|
|
380
|
+
lineage = current.get("lineage") or state.lineage or str(uuid.uuid4())
|
|
381
|
+
document = {
|
|
382
|
+
"version": 4,
|
|
383
|
+
"terraform_version": "1.0.0",
|
|
384
|
+
"serial": serial,
|
|
385
|
+
"lineage": lineage,
|
|
386
|
+
"outputs": {},
|
|
387
|
+
"resources": [],
|
|
388
|
+
self.STATE_KEY: state.to_dict(),
|
|
389
|
+
}
|
|
390
|
+
raw = json.dumps(document).encode("utf-8")
|
|
391
|
+
body = {
|
|
392
|
+
"data": {
|
|
393
|
+
"type": "state-versions",
|
|
394
|
+
"attributes": {
|
|
395
|
+
"serial": serial,
|
|
396
|
+
"md5": hashlib.md5(raw, usedforsecurity=False).hexdigest(),
|
|
397
|
+
"lineage": lineage,
|
|
398
|
+
"state": base64.b64encode(raw).decode("ascii"),
|
|
399
|
+
},
|
|
400
|
+
},
|
|
401
|
+
}
|
|
402
|
+
self._request(
|
|
403
|
+
"POST",
|
|
404
|
+
self._api_url(f"/workspaces/{self._get_workspace_id()}/state-versions"),
|
|
405
|
+
expected=(200, 201),
|
|
406
|
+
data=json.dumps(body),
|
|
407
|
+
)
|
|
408
|
+
logger.info(f"State saved to workspace {self._workspace_name()} (serial {serial})")
|
|
409
|
+
except Exception as e:
|
|
410
|
+
logger.error("Failed to save state to Terraform Cloud: %s", e)
|
|
411
|
+
raise
|
|
412
|
+
finally:
|
|
413
|
+
if lock_for_save:
|
|
414
|
+
self.unlock()
|
|
415
|
+
|
|
416
|
+
def lock(self, info: dict[str, Any]) -> bool:
|
|
417
|
+
"""Acquire state lock by locking the workspace.
|
|
418
|
+
|
|
419
|
+
Args:
|
|
420
|
+
info: Lock information (e.g., who is locking, operation ID)
|
|
421
|
+
|
|
422
|
+
Returns:
|
|
423
|
+
True if lock was acquired, False otherwise
|
|
424
|
+
|
|
425
|
+
"""
|
|
426
|
+
if self._locked:
|
|
427
|
+
logger.error("State lock is already held by this backend")
|
|
428
|
+
return False
|
|
429
|
+
try:
|
|
430
|
+
operation = info.get("operation") or info.get("Operation") or "apply"
|
|
431
|
+
response = self._request(
|
|
432
|
+
"POST",
|
|
433
|
+
self._api_url(f"/workspaces/{self._get_workspace_id()}/actions/lock"),
|
|
434
|
+
expected=(200, 409),
|
|
435
|
+
data=json.dumps({"reason": f"Locked by Netherframe ({operation})"}),
|
|
436
|
+
)
|
|
437
|
+
except Exception as e:
|
|
438
|
+
logger.error("Failed to acquire lock: %s", e)
|
|
439
|
+
return False
|
|
440
|
+
if response.status_code == 409:
|
|
441
|
+
logger.error(f"State is locked: workspace {self._workspace_name()} is already locked")
|
|
442
|
+
return False
|
|
443
|
+
self._locked = True
|
|
444
|
+
logger.info(f"State lock acquired (workspace {self._workspace_name()})")
|
|
445
|
+
return True
|
|
446
|
+
|
|
447
|
+
def unlock(self) -> None:
|
|
448
|
+
"""Release state lock, if this backend holds it."""
|
|
449
|
+
if not self._locked:
|
|
450
|
+
return
|
|
451
|
+
try:
|
|
452
|
+
self._request(
|
|
453
|
+
"POST",
|
|
454
|
+
self._api_url(f"/workspaces/{self._get_workspace_id()}/actions/unlock"),
|
|
455
|
+
expected=(200,),
|
|
456
|
+
)
|
|
457
|
+
logger.info(f"State lock released (workspace {self._workspace_name()})")
|
|
458
|
+
except Exception as e:
|
|
459
|
+
logger.error("Failed to release lock: %s", e)
|
|
460
|
+
finally:
|
|
461
|
+
self._locked = False
|
|
462
|
+
|
|
463
|
+
def save_checkpoint(self, name: str, *, keep: int) -> str | None:
|
|
464
|
+
"""The workspace's current state version: HCP Terraform keeps every one, so nothing is copied.
|
|
465
|
+
|
|
466
|
+
None when the workspace has no state yet.
|
|
467
|
+
"""
|
|
468
|
+
response = self._request(
|
|
469
|
+
"GET",
|
|
470
|
+
self._api_url(f"/workspaces/{self._get_workspace_id()}/current-state-version"),
|
|
471
|
+
expected=(200, 404),
|
|
472
|
+
)
|
|
473
|
+
if response.status_code == 404:
|
|
474
|
+
return None
|
|
475
|
+
location = self._api_url(f"/state-versions/{response.json()['data']['id']}")
|
|
476
|
+
logger.info(f"State before this run is state version {location} of workspace {self._workspace_name()}")
|
|
477
|
+
return location
|
|
478
|
+
|
|
479
|
+
def load_checkpoint(self, location: str) -> State | None:
|
|
480
|
+
"""The state of the workspace's state version at ``location``."""
|
|
481
|
+
if not location.startswith(self._api_url("/state-versions/")):
|
|
482
|
+
return None
|
|
483
|
+
attributes = self._request("GET", location, expected=(200,)).json()["data"]["attributes"]
|
|
484
|
+
download_url = attributes.get("hosted-state-download-url")
|
|
485
|
+
if not download_url:
|
|
486
|
+
raise RuntimeError(f"State version {location} has no download URL")
|
|
487
|
+
return self._state_from_document(json.loads(self._request("GET", download_url, expected=(200,)).content))
|
|
488
|
+
|
|
489
|
+
can_force_unlock = True
|
|
490
|
+
|
|
491
|
+
def current_lock(self) -> dict[str, Any] | None:
|
|
492
|
+
"""The workspace's lock, whose ID is the workspace's, or None when the workspace is not locked."""
|
|
493
|
+
response = self._request(
|
|
494
|
+
"GET",
|
|
495
|
+
self._api_url(f"/organizations/{self.organization}/workspaces/{self._workspace_name()}"),
|
|
496
|
+
expected=(200,),
|
|
497
|
+
)
|
|
498
|
+
workspace = response.json()["data"]
|
|
499
|
+
if not workspace.get("attributes", {}).get("locked"):
|
|
500
|
+
return None
|
|
501
|
+
return {"ID": workspace["id"], "Who": f"the holder of workspace {self._workspace_name()}'s lock", "Path": self._workspace_name()}
|
|
502
|
+
|
|
503
|
+
def force_unlock(self, lock_id: str) -> None:
|
|
504
|
+
"""Force-unlock the workspace (its ID is the lock's), whoever locked it; needs the workspace's admin permission."""
|
|
505
|
+
workspace_id = self._get_workspace_id()
|
|
506
|
+
if lock_id != workspace_id:
|
|
507
|
+
raise StateLockError(f"The lock of workspace {self._workspace_name()} is {workspace_id}, not {lock_id}")
|
|
508
|
+
response = self._request(
|
|
509
|
+
"POST",
|
|
510
|
+
self._api_url(f"/workspaces/{workspace_id}/actions/force-unlock"),
|
|
511
|
+
expected=(200, 409),
|
|
512
|
+
)
|
|
513
|
+
if response.status_code == 409:
|
|
514
|
+
raise StateLockError(f"Workspace {self._workspace_name()} is not locked")
|
|
515
|
+
logger.warning(f"Force-unlocked workspace {self._workspace_name()}")
|
|
File without changes
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "netherframe.backends.remote"
|
|
3
|
+
version = "0.2.0"
|
|
4
|
+
description = "Terraform Cloud/Enterprise backend implementations for Netherframe"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
requires-python = ">=3.14"
|
|
7
|
+
license = "MIT"
|
|
8
|
+
license-files = ["LICENSE"]
|
|
9
|
+
classifiers = [
|
|
10
|
+
"Development Status :: 4 - Beta",
|
|
11
|
+
"Intended Audience :: Developers",
|
|
12
|
+
"Programming Language :: Python :: 3.14",
|
|
13
|
+
"Topic :: Software Development :: Libraries :: Python Modules",
|
|
14
|
+
"Topic :: System :: Systems Administration",
|
|
15
|
+
]
|
|
16
|
+
dependencies = [
|
|
17
|
+
"netherframe.core>=0.9.0",
|
|
18
|
+
"requests>=2.34.2",
|
|
19
|
+
]
|
|
20
|
+
|
|
21
|
+
[[project.authors]]
|
|
22
|
+
name = "Sourabh Cheedella"
|
|
23
|
+
email = "cheedella.sourabh@gmail.com"
|
|
24
|
+
|
|
25
|
+
[project.optional-dependencies]
|
|
26
|
+
dev = ["pytest>=9.2.0"]
|
|
27
|
+
|
|
28
|
+
[project.urls]
|
|
29
|
+
Homepage = "https://netherframe.arsenal.sh"
|
|
30
|
+
Repository = "https://github.com/arsenal-sh/netherframe"
|
|
31
|
+
|
|
32
|
+
[build-system]
|
|
33
|
+
requires = ["uv_build>=0.13.9,<0.14.0"]
|
|
34
|
+
build-backend = "uv_build"
|
|
35
|
+
|
|
36
|
+
[tool.uv]
|
|
37
|
+
package = true
|
|
38
|
+
|
|
39
|
+
[tool.uv.build-backend]
|
|
40
|
+
module-name = [
|
|
41
|
+
"netherframe.backends.remote",
|
|
42
|
+
"nf.backends.remote",
|
|
43
|
+
]
|
|
44
|
+
module-root = ""
|
|
45
|
+
|
|
46
|
+
[tool.uv.sources."netherframe.core"]
|
|
47
|
+
workspace = true
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "netherframe.backends.remote"
|
|
3
|
+
version = "0.2.0"
|
|
4
|
+
description = "Terraform Cloud/Enterprise backend implementations for Netherframe"
|
|
5
|
+
authors = [
|
|
6
|
+
{name = "Sourabh Cheedella", email = "cheedella.sourabh@gmail.com"},
|
|
7
|
+
]
|
|
8
|
+
readme = "README.md"
|
|
9
|
+
requires-python = ">=3.14"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
license-files = ["LICENSE"]
|
|
12
|
+
classifiers = [
|
|
13
|
+
"Development Status :: 4 - Beta",
|
|
14
|
+
"Intended Audience :: Developers",
|
|
15
|
+
"Programming Language :: Python :: 3.14",
|
|
16
|
+
"Topic :: Software Development :: Libraries :: Python Modules",
|
|
17
|
+
"Topic :: System :: Systems Administration",
|
|
18
|
+
]
|
|
19
|
+
|
|
20
|
+
dependencies = [
|
|
21
|
+
"netherframe.core>=0.9.0",
|
|
22
|
+
"requests>=2.34.2",
|
|
23
|
+
]
|
|
24
|
+
|
|
25
|
+
[project.optional-dependencies]
|
|
26
|
+
dev = [
|
|
27
|
+
"pytest>=9.2.0",
|
|
28
|
+
]
|
|
29
|
+
|
|
30
|
+
[project.urls]
|
|
31
|
+
Homepage = "https://netherframe.arsenal.sh"
|
|
32
|
+
Repository = "https://github.com/arsenal-sh/netherframe"
|
|
33
|
+
|
|
34
|
+
[build-system]
|
|
35
|
+
requires = ["uv_build>=0.13.9,<0.14.0"]
|
|
36
|
+
build-backend = "uv_build"
|
|
37
|
+
|
|
38
|
+
[tool.uv]
|
|
39
|
+
package = true
|
|
40
|
+
|
|
41
|
+
[tool.uv.build-backend]
|
|
42
|
+
module-name = ["netherframe.backends.remote", "nf.backends.remote"]
|
|
43
|
+
module-root = ""
|
|
44
|
+
|
|
45
|
+
[tool.uv.sources]
|
|
46
|
+
"netherframe.core" = { workspace = true }
|