-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathproject.py
More file actions
387 lines (338 loc) · 13.4 KB
/
Copy pathproject.py
File metadata and controls
387 lines (338 loc) · 13.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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
237
238
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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
# Copyright IBM Corp. 2025, 2026
# SPDX-License-Identifier: MPL-2.0
from __future__ import annotations
import argparse
import os
import uuid
from pytfe import TFEClient, TFEConfig
from pytfe.models import (
ProjectAddTagBindingsOptions,
ProjectCreateOptions,
ProjectListOptions,
ProjectSettingOverwrites,
ProjectUpdateOptions,
TagBinding,
WorkspaceCreateOptions,
)
def _print_header(title: str) -> None:
print("\n" + "=" * 80)
print(title)
print("=" * 80)
def _org_display(project) -> str:
"""Render organization safely for both string and object representations."""
org = getattr(project, "organization", None)
if org is None:
return ""
if isinstance(org, str):
return org
return getattr(org, "id", str(org))
def _parse_tag_pairs(tag_pairs: list[str] | None) -> list[TagBinding]:
"""Convert --tag key=value args into TagBinding models."""
if not tag_pairs:
return []
tags: list[TagBinding] = []
for pair in tag_pairs:
if "=" in pair:
key, value = pair.split("=", 1)
key = key.strip()
value = value.strip()
if not key:
raise ValueError(f"Invalid tag format '{pair}'. Key is empty.")
tags.append(TagBinding(key=key, value=value))
else:
key = pair.strip()
if not key:
raise ValueError(f"Invalid tag format '{pair}'.")
tags.append(TagBinding(key=key, value=None))
return tags
def main() -> None:
parser = argparse.ArgumentParser(description="Projects demo for python-tfe SDK")
parser.add_argument(
"--address",
default=os.getenv("TFE_ADDRESS", "https://app.terraform.io"),
help="TFE/TFC address",
)
parser.add_argument(
"--token",
default=os.getenv("TFE_TOKEN", ""),
help="TFE/TFC API token",
)
parser.add_argument(
"--organization",
default=os.getenv("TFE_ORG", ""),
help="Organization name",
)
parser.add_argument(
"--page-size",
type=int,
default=20,
help="Page size for project listing",
)
parser.add_argument("--list", action="store_true", help="List projects")
parser.add_argument("--create", action="store_true", help="Create a project")
parser.add_argument("--read", action="store_true", help="Read a project")
parser.add_argument("--update", action="store_true", help="Update a project")
parser.add_argument("--delete", action="store_true", help="Delete a project")
parser.add_argument(
"--list-tag-bindings",
action="store_true",
help="List project tag bindings",
)
parser.add_argument(
"--list-effective-tag-bindings",
action="store_true",
help="List project effective tag bindings",
)
parser.add_argument(
"--add-tag-bindings",
action="store_true",
help="Add/replace tag bindings on project",
)
parser.add_argument(
"--delete-tag-bindings",
action="store_true",
help="Delete all tag bindings from project",
)
parser.add_argument(
"--project-id",
help="Project ID for read/update/delete/tag operations",
)
parser.add_argument("--name", help="Project name for create/update")
parser.add_argument("--description", help="Project description for create/update")
parser.add_argument(
"--tag",
action="append",
default=[],
help="Tag binding in key=value format (repeatable)",
)
parser.add_argument(
"--create-random",
action="store_true",
help="Append a short random suffix to --name for create",
)
parser.add_argument(
"--move-workspace-id",
action="append",
default=[],
help="Workspace id to move into --project-id (repeatable). Requires "
"--project-id.",
)
parser.add_argument(
"--demo-move",
action="store_true",
help="End-to-end demo: create scratch projects + workspace, move the "
"workspace between projects, clean up.",
)
args = parser.parse_args()
if not args.token:
raise SystemExit("Error: --token or TFE_TOKEN is required")
cfg = TFEConfig(address=args.address, token=args.token)
client = TFEClient(cfg)
has_org_op = args.list or args.create
has_project_op = (
args.read
or args.update
or args.delete
or args.list_tag_bindings
or args.list_effective_tag_bindings
or args.add_tag_bindings
or args.delete_tag_bindings
)
if has_org_op and not args.organization:
raise SystemExit("Error: --organization or TFE_ORG is required")
if has_project_op and not args.project_id:
raise SystemExit("Error: --project-id is required for selected operation")
# 1) List projects
if args.list:
_print_header(f"Listing projects for organization: {args.organization}")
list_options = ProjectListOptions(page_size=args.page_size)
count = 0
for project in client.projects.list(args.organization, list_options):
count += 1
print(f"- {project.name} (ID: {project.id})")
print(f" Description: {project.description}")
print(f" Workspaces: {project.workspace_count}")
print(f" Default execution mode: {project.default_execution_mode}")
print(
f" Auto destroy activity duration: {project.auto_destroy_activity_duration}"
)
print(f" Created at: {project.created_at}")
print(f" Updated at: {project.updated_at}")
print(f" Setting overwrites: {project.setting_overwrites}")
print(f" Default agent pool: {project.default_agent_pool}")
print(f" Organization: {_org_display(project)}")
print()
if count == 0:
print("No projects found.")
else:
print(f"Total: {count} projects")
# 2) Create project
if args.create:
if not args.name:
raise SystemExit("Error: --name is required for create")
name = args.name
if args.create_random:
name = f"{name}-{uuid.uuid4().hex[:8]}"
_print_header(f"Creating project: {name}")
tags = _parse_tag_pairs(args.tag)
create_options = ProjectCreateOptions(
name=name,
description=args.description,
auto_destroy_activity_duration="14d",
default_execution_mode="remote",
default_agent_pool_id=None,
setting_overwrites=ProjectSettingOverwrites(
execution_mode=False,
agent_pool=False,
),
tag_bindings=tags,
)
project = client.projects.create(args.organization, create_options)
print(f"Created project: {project.id}")
print(f"Name: {project.name}")
print(f"Description: {project.description}")
print(f"Workspaces: {project.workspace_count}")
print(f"Default execution mode: {project.default_execution_mode}")
print(
f"Auto destroy activity duration: {project.auto_destroy_activity_duration}"
)
print(f"Created at: {project.created_at}")
print(f"Updated at: {project.updated_at}")
print(f"Setting overwrites: {project.setting_overwrites}")
print(f"Default agent pool: {project.default_agent_pool}")
print(f"Organization: {_org_display(project)}")
# 3) Read project
if args.read:
_print_header(f"Reading project: {args.project_id}")
project = client.projects.read(args.project_id)
print(f"ID: {project.id}")
print(f"Name: {project.name}")
print(f"Description: {project.description}")
print(f"Organization: {_org_display(project)}")
print(f"Created at: {project.created_at}")
print(f"Updated at: {project.updated_at}")
print(f"Workspace count: {project.workspace_count}")
print(f"Default execution mode: {project.default_execution_mode}")
print(
f"Auto destroy activity duration: {project.auto_destroy_activity_duration}"
)
# 4) Update project
if args.update:
if args.name is None and args.description is None and not args.tag:
raise SystemExit(
"Error: provide at least one of --name, --description or --tag for update"
)
_print_header(f"Updating project: {args.project_id}")
tags = _parse_tag_pairs(args.tag)
update_options = ProjectUpdateOptions(
name=args.name,
description=args.description,
tag_bindings=tags if tags else None,
)
updated = client.projects.update(args.project_id, update_options)
print("Project updated successfully")
print(f"ID: {updated.id}")
print(f"Name: {updated.name}")
print(f"Description: {updated.description}")
# 5) Delete project
if args.delete:
_print_header(f"Deleting project: {args.project_id}")
client.projects.delete(args.project_id)
print("Project deleted successfully")
# 6) List tag bindings
if args.list_tag_bindings:
_print_header(f"Listing tag bindings for project: {args.project_id}")
bindings = client.projects.list_tag_bindings(args.project_id)
if not bindings:
print("No tag bindings found.")
else:
for tag in bindings:
print(f"- {tag.key}={tag.value}")
print(f"Total: {len(bindings)} tag bindings")
# 7) List effective tag bindings
if args.list_effective_tag_bindings:
_print_header(f"Listing effective tag bindings for project: {args.project_id}")
bindings = list(client.projects.list_effective_tag_bindings(args.project_id))
if not bindings:
print("No effective tag bindings found.")
else:
for tag in bindings:
print(f"- {tag.key}={tag.value}")
print(f"Total: {len(bindings)} effective tag bindings")
# 8) Add tag bindings
if args.add_tag_bindings:
tags = _parse_tag_pairs(args.tag)
if not tags:
raise SystemExit(
"Error: at least one --tag key=value is required for --add-tag-bindings"
)
_print_header(f"Adding tag bindings to project: {args.project_id}")
options = ProjectAddTagBindingsOptions(tag_bindings=tags)
updated_tags = client.projects.add_tag_bindings(args.project_id, options)
for tag in updated_tags:
print(f"- {tag.key}={tag.value}")
print(f"Total returned: {len(updated_tags)} tag bindings")
# 9) Delete tag bindings
if args.delete_tag_bindings:
_print_header(f"Deleting all tag bindings from project: {args.project_id}")
client.projects.delete_tag_bindings(args.project_id)
print("Deleted all project tag bindings")
# 10) Move workspaces into the given project (additive, not destructive)
if args.move_workspace_id:
if not args.project_id:
raise SystemExit("--project-id is required for --move-workspace-id")
_print_header(
f"Moving {len(args.move_workspace_id)} workspace(s) into "
f"project {args.project_id}"
)
client.projects.move_workspaces(args.project_id, args.move_workspace_id)
print("done")
# 11) End-to-end demo: create scratch resources, move, cleanup
if args.demo_move:
import time
_print_header("project.move_workspaces end-to-end demo (scratch resources)")
stamp = int(time.time())
created: dict[str, str] = {}
try:
src = client.projects.create(
args.organization,
ProjectCreateOptions(name=f"pytfe-move-src-{stamp}"),
)
created["src_project"] = src.id
print(f"created source project: {src.id} ({src.name})")
dst = client.projects.create(
args.organization,
ProjectCreateOptions(name=f"pytfe-move-dst-{stamp}"),
)
created["dst_project"] = dst.id
print(f"created target project: {dst.id} ({dst.name})")
ws = client.workspaces.create(
args.organization,
WorkspaceCreateOptions(
name=f"pytfe-move-ws-{stamp}", project={"id": src.id}
),
)
created["workspace"] = ws.id
print(f"created workspace: {ws.id} in {src.id}")
client.projects.move_workspaces(dst.id, [ws.id])
ws2 = client.workspaces.read_by_id(ws.id)
moved = ws2.project.id if ws2.project else "?"
print(f"workspace now belongs to: {moved}")
assert moved == dst.id
print("OK")
finally:
if "workspace" in created:
try:
client.workspaces.delete_by_id(created["workspace"])
print(f"cleaned up workspace {created['workspace']}")
except Exception as e:
print(f"WARN: workspace cleanup failed: {e}")
for key in ("dst_project", "src_project"):
if key in created:
try:
client.projects.delete(created[key])
print(f"cleaned up project {created[key]}")
except Exception as e:
print(f"WARN: project {key} cleanup failed: {e}")
if __name__ == "__main__":
main()