multicloud-cli 0.5.1__tar.gz → 0.6.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.
Files changed (40) hide show
  1. {multicloud_cli-0.5.1 → multicloud_cli-0.6.0}/PKG-INFO +1 -1
  2. multicloud_cli-0.6.0/multicloud_cli/__init__.py +1 -0
  3. {multicloud_cli-0.5.1 → multicloud_cli-0.6.0}/multicloud_cli/api.py +2 -1
  4. {multicloud_cli-0.5.1 → multicloud_cli-0.6.0}/multicloud_cli/cloud_account.py +75 -4
  5. {multicloud_cli-0.5.1 → multicloud_cli-0.6.0}/multicloud_cli/extend.py +11 -2
  6. {multicloud_cli-0.5.1 → multicloud_cli-0.6.0}/multicloud_cli/pool.py +32 -7
  7. {multicloud_cli-0.5.1 → multicloud_cli-0.6.0}/tests/test_account_extend.py +25 -0
  8. {multicloud_cli-0.5.1 → multicloud_cli-0.6.0}/tests/test_cloud_account.py +95 -1
  9. {multicloud_cli-0.5.1 → multicloud_cli-0.6.0}/tests/test_pool.py +48 -0
  10. multicloud_cli-0.5.1/multicloud_cli/__init__.py +0 -1
  11. {multicloud_cli-0.5.1 → multicloud_cli-0.6.0}/.gitignore +0 -0
  12. {multicloud_cli-0.5.1 → multicloud_cli-0.6.0}/LICENSE +0 -0
  13. {multicloud_cli-0.5.1 → multicloud_cli-0.6.0}/README.md +0 -0
  14. {multicloud_cli-0.5.1 → multicloud_cli-0.6.0}/multicloud_cli/account.py +0 -0
  15. {multicloud_cli-0.5.1 → multicloud_cli-0.6.0}/multicloud_cli/auth.py +0 -0
  16. {multicloud_cli-0.5.1 → multicloud_cli-0.6.0}/multicloud_cli/catalog.py +0 -0
  17. {multicloud_cli-0.5.1 → multicloud_cli-0.6.0}/multicloud_cli/config.py +0 -0
  18. {multicloud_cli-0.5.1 → multicloud_cli-0.6.0}/multicloud_cli/duration.py +0 -0
  19. {multicloud_cli-0.5.1 → multicloud_cli-0.6.0}/multicloud_cli/exitcodes.py +0 -0
  20. {multicloud_cli-0.5.1 → multicloud_cli-0.6.0}/multicloud_cli/main.py +0 -0
  21. {multicloud_cli-0.5.1 → multicloud_cli-0.6.0}/multicloud_cli/net.py +0 -0
  22. {multicloud_cli-0.5.1 → multicloud_cli-0.6.0}/multicloud_cli/node.py +0 -0
  23. {multicloud_cli-0.5.1 → multicloud_cli-0.6.0}/multicloud_cli/orgopt.py +0 -0
  24. {multicloud_cli-0.5.1 → multicloud_cli-0.6.0}/multicloud_cli/output.py +0 -0
  25. {multicloud_cli-0.5.1 → multicloud_cli-0.6.0}/multicloud_cli/ssh.py +0 -0
  26. {multicloud_cli-0.5.1 → multicloud_cli-0.6.0}/multicloud_cli/ssh_cert.py +0 -0
  27. {multicloud_cli-0.5.1 → multicloud_cli-0.6.0}/multicloud_cli/sso.py +0 -0
  28. {multicloud_cli-0.5.1 → multicloud_cli-0.6.0}/pyproject.toml +0 -0
  29. {multicloud_cli-0.5.1 → multicloud_cli-0.6.0}/tests/__init__.py +0 -0
  30. {multicloud_cli-0.5.1 → multicloud_cli-0.6.0}/tests/conftest.py +0 -0
  31. {multicloud_cli-0.5.1 → multicloud_cli-0.6.0}/tests/helpers.py +0 -0
  32. {multicloud_cli-0.5.1 → multicloud_cli-0.6.0}/tests/test_apply.py +0 -0
  33. {multicloud_cli-0.5.1 → multicloud_cli-0.6.0}/tests/test_auth.py +0 -0
  34. {multicloud_cli-0.5.1 → multicloud_cli-0.6.0}/tests/test_catalog.py +0 -0
  35. {multicloud_cli-0.5.1 → multicloud_cli-0.6.0}/tests/test_conventions.py +0 -0
  36. {multicloud_cli-0.5.1 → multicloud_cli-0.6.0}/tests/test_net.py +0 -0
  37. {multicloud_cli-0.5.1 → multicloud_cli-0.6.0}/tests/test_ssh.py +0 -0
  38. {multicloud_cli-0.5.1 → multicloud_cli-0.6.0}/tests/test_ssh_cert.py +0 -0
  39. {multicloud_cli-0.5.1 → multicloud_cli-0.6.0}/tests/test_sso.py +0 -0
  40. {multicloud_cli-0.5.1 → multicloud_cli-0.6.0}/tests/test_sso_session.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: multicloud-cli
3
- Version: 0.5.1
3
+ Version: 0.6.0
4
4
  Summary: mctl: the Multicloud command line: sign in, connect your cloud account, run pools
5
5
  Project-URL: Homepage, https://multicloud.io
6
6
  Author-email: Multicloud Team <info@multicloud.io>
@@ -0,0 +1 @@
1
+ __version__ = "0.6.0"
@@ -15,7 +15,8 @@ from . import auth, config, exitcodes, net, sso
15
15
 
16
16
  TIMEOUT_S = 30
17
17
  # The name of each scope in the console key form (multicloud.io, Account, API keys).
18
- CONSOLE_SCOPE_NAMES = {"org:read": "Pools: Read", "org:write": "Pools: Manage", "org:admin": "Pools: Full"}
18
+ CONSOLE_SCOPE_NAMES = {"org:read": "Pools: Read", "org:write": "Pools: Manage", "org:admin": "Pools: Full",
19
+ "infra": "Infrastructure"}
19
20
 
20
21
 
21
22
  class ApiError(Exception):
@@ -567,6 +567,70 @@ def accept_shared_account(ctx, account_id):
567
567
  sys.exit(exitcodes.ERROR)
568
568
 
569
569
 
570
+ IN_USE = "ACCOUNT_IN_USE"
571
+
572
+
573
+ def _disconnect(org, account_id: int, again: str = "disconnect") -> Dict[str, Any]:
574
+ """``DELETE /cloud-accounts/{id}`` with the sign-in. Returns the account; raises ``CloudAccountError`` with
575
+ calm text when a pool still uses it (nothing changed then)."""
576
+ try:
577
+ answer = api.call("DELETE", org, f"/cloud-accounts/{account_id}", pass_codes=(IN_USE,), prefer_sso=True)
578
+ except api.ApiError as ex:
579
+ raise CloudAccountError(str(ex), ex.exit_code)
580
+ status = answer.pop("_status", 200)
581
+ if status == 409:
582
+ detail = answer.get("detail") or {}
583
+ details = detail.get("details") or {}
584
+ lines = [f"Cloud account {account_id} is still in use, so it stays connected. Nothing changed."]
585
+ for name in details.get("pools") or []:
586
+ lines.append(f" Pool {name}: delete it with 'mctl pool delete {name}'.")
587
+ if details.get("other_organization_pools"):
588
+ lines.append(f" {details['other_organization_pools']} pool(s) of other organizations use it: "
589
+ "ask Multicloud support.")
590
+ if details.get("live_servers"):
591
+ lines.append(f" {details['live_servers']} server(s) still run in it. They stop a few minutes after "
592
+ "their pool is deleted.")
593
+ lines.append(f"Then run 'mctl cloud-account {again} {account_id}' again.")
594
+ raise CloudAccountError("\n".join(lines), exitcodes.ERROR)
595
+ return answer
596
+
597
+
598
+ @cloud_account.command()
599
+ @click.argument("account_id", type=int)
600
+ @click.option("-y", "--yes", is_flag=True, help="Disconnect without asking")
601
+ @click.pass_context
602
+ def disconnect(ctx, account_id, yes):
603
+ """Disconnect a cloud account from the organization (organization owners only).
604
+
605
+ Multicloud stops using the account at once. Nothing in the account is deleted: remove the Multicloud role
606
+ afterwards with 'tofu destroy' (or 'mctl cloud-account destroy' for an AWS account that mctl created). A pool
607
+ that uses the account must be deleted first. Needs a sign-in (mctl auth login), not an API key."""
608
+ # The sign-in from the start: the API refuses an API key here, so fail before the prompt.
609
+ data = _run(ctx, lambda org: call("GET", org, f"/{account_id}", prefer_sso=True))
610
+ data.pop("_status", None)
611
+ noun = noun_of(data.get("cloud"))
612
+ native = data.get("native_id") or data.get("expected_native_id")
613
+ which = f"{noun} {native}" if native else f"cloud account {account_id}"
614
+ if data.get("status") == "revoked":
615
+ click.echo(f"Cloud account {account_id} is already disconnected.")
616
+ return
617
+ if not yes:
618
+ if not _stdin_is_tty():
619
+ click.echo("Error: Refusing to disconnect without confirmation. Run again with --yes.", err=True)
620
+ sys.exit(exitcodes.ERROR)
621
+ click.echo(f"This disconnects {which} from your organization. Multicloud stops using it at once.")
622
+ click.echo(f"Nothing in the {noun} is deleted. You can connect it again later with mctl cloud-account create.")
623
+ if not click.confirm(f"Disconnect {which}?", default=False):
624
+ click.echo("Nothing changed.", err=True)
625
+ sys.exit(exitcodes.ERROR)
626
+ _run(ctx, lambda org: _disconnect(org, account_id))
627
+ click.echo(f"Disconnected: {which} is no longer connected to Multicloud.")
628
+ if not data.get("connected_on"):
629
+ return # Terraform never connected it: there is no Multicloud role to remove
630
+ click.echo("Next: remove the Multicloud role from the account. Run 'tofu destroy' (or 'terraform destroy') in "
631
+ f"the folder with {TF_FILE}, or 'mctl cloud-account destroy {account_id}' if mctl created the AWS account.")
632
+
633
+
570
634
  def _find_tool(requested: Optional[str]) -> str:
571
635
  if requested:
572
636
  if not shutil.which(requested):
@@ -631,10 +695,12 @@ def _aws_account_state(account_id: str) -> Optional[str]:
631
695
  @click.option("-y", "--yes", is_flag=True, help="Destroy without asking")
632
696
  @click.pass_context
633
697
  def destroy(ctx, account_id, directory, tool, yes):
634
- """Remove the Multicloud role and close the AWS account that multicloud.tf created.
698
+ """Disconnect the AWS account that multicloud.tf created, then close it.
635
699
 
636
- Only for a file made with 'create --new-account-email'. AWS keeps a closed account for 90 days, and its
637
- email cannot be used for a new AWS account again."""
700
+ Only for a file made with 'create --new-account-email'. The account is disconnected from your organization
701
+ first (organization owners only; needs mctl auth login), so a pool that still uses it stops the command before
702
+ anything is closed. AWS keeps a closed account for 90 days, and its email cannot be used for a new AWS
703
+ account again."""
638
704
  text = _check_file(account_id, directory)
639
705
  if not _PATH_A.search(text):
640
706
  click.echo(f"{TF_FILE} did not create an AWS account, so there is no account for mctl to close.")
@@ -656,11 +722,16 @@ def destroy(ctx, account_id, directory, tool, yes):
656
722
  if not _stdin_is_tty():
657
723
  click.echo("Error: Refusing to destroy without confirmation. Run again with --yes.", err=True)
658
724
  sys.exit(1)
659
- click.echo(f"This removes the Multicloud role and closes {which} that {TF_FILE} created.")
725
+ click.echo(f"This disconnects {which} from your organization, removes the Multicloud role and closes the "
726
+ f"account that {TF_FILE} created.")
660
727
  click.echo("AWS keeps a closed account for 90 days. Its email cannot be used again for a new AWS account.")
661
728
  if not click.confirm(f"Close {which}?", default=False):
662
729
  click.echo("Nothing destroyed.", err=True)
663
730
  sys.exit(exitcodes.ERROR)
731
+ # Disconnect first: a closed account must not stay connected, and a pool that still uses it stops us here,
732
+ # before anything is closed. An account that is already disconnected answers the same.
733
+ _run(ctx, lambda org: _disconnect(org, account_id, again="destroy"))
734
+ click.echo(f"Disconnected cloud account {account_id} from your organization.")
664
735
  # The account closes with everything in it. Deleting the Spot service-linked role can be blocked
665
736
  # for about 4 minutes after the last spot instance ends, so the destroy must not depend on it.
666
737
  code, out = _run(ctx, lambda org: _tool_capture(tool, ["state", "rm", "module.multicloud"], directory, base_env))
@@ -14,6 +14,7 @@ from urllib.parse import quote
14
14
  import click
15
15
 
16
16
  from . import api, exitcodes
17
+ from .cloud_account import quota_lines
17
18
  from .orgopt import org_group, org_option
18
19
  from .output import (collect as _collect, dump as _dump, echo as _echo, json_option, load_body, no_headers_option, quiet_option,
19
20
  run, table as _table)
@@ -70,6 +71,10 @@ def _run(ctx, key, fn):
70
71
 
71
72
  @extend.command(name="create")
72
73
  @click.argument("name", required=False)
74
+ @click.option("--cloud-account", "cloud_accounts", type=int, multiple=True, metavar="ID",
75
+ help="Run the pool on a connected cloud account (see: mctl cloud-account list). Repeat for more "
76
+ "(one per cloud). This command uses your SSO sign-in as owner; an API key that calls the "
77
+ "Extend API directly needs the Infrastructure (infra) scope")
73
78
  @click.option("--max-servers", type=int, default=None, help="Most servers the pool may hold (1-50)")
74
79
  @click.option("--max-cost-per-hour", type=float, default=None, help="Cost ceiling in USD per hour (up to 50)")
75
80
  @click.option("--from-file", "from_file", type=click.Path(dir_okay=False, allow_dash=True), default=None,
@@ -78,10 +83,12 @@ def _run(ctx, key, fn):
78
83
  help="Same key and body within 24 hours creates one pool (default: a new random key)")
79
84
  @json_option
80
85
  @click.pass_context
81
- def create_pool(ctx, name, max_servers, max_cost_per_hour, from_file, idempotency_key, as_json):
82
- """Create an Extend pool."""
86
+ def create_pool(ctx, name, cloud_accounts, max_servers, max_cost_per_hour, from_file, idempotency_key, as_json):
87
+ """Create an Extend pool, optionally on connected cloud accounts (--cloud-account)."""
83
88
  body = load_body(from_file)
84
89
  body.update(_collect(name=name, max_servers=max_servers, max_cost_per_hour=max_cost_per_hour))
90
+ if cloud_accounts:
91
+ body["cloud_accounts"] = [{"id": i} for i in cloud_accounts]
85
92
  if "name" not in body:
86
93
  raise click.UsageError("Missing: NAME")
87
94
  key = idempotency_key or str(uuid.uuid4())
@@ -98,6 +105,8 @@ def create_pool(ctx, name, max_servers, max_cost_per_hour, from_file, idempotenc
98
105
  if as_json:
99
106
  return _dump(made)
100
107
  click.echo(f"Pool {made.get('pool_id')} ({made.get('name')}) created. Status: {_status(made)}")
108
+ for line in quota_lines(made.get("quota")):
109
+ click.echo(line)
101
110
  click.echo(f"Next: mctl peering create {made.get('name')}")
102
111
 
103
112
 
@@ -16,6 +16,7 @@ from typing import Any, Callable, Dict, Optional, Tuple
16
16
  import click
17
17
 
18
18
  from . import api, exitcodes
19
+ from .cloud_account import quota_lines
19
20
  from .duration import duration_option, interval_option, parse_duration # noqa: F401 (parse_duration: tests)
20
21
  from .orgopt import org_group, org_option
21
22
  from .output import (collect as _collect, dump as _dump, echo as _echo, json_option, load_body, no_headers_option, plain as _plain,
@@ -221,10 +222,19 @@ def _classes_list(ctx, param, value):
221
222
  @click.argument("name", required=False)
222
223
  @click.option("--github-org", default=None, help="GitHub organization the runners serve")
223
224
  @click.option("--clouds", callback=_json_value, default=None,
224
- help="JSON list of clouds, or @file.json. Cloud keys belong in --from-file, not in a command line")
225
+ help="JSON list of clouds, or @file.json. Cloud keys belong in --from-file, not in a command line. "
226
+ "Not with --cloud-account")
227
+ @click.option("--cloud-account", "cloud_accounts", type=int, multiple=True, metavar="ID",
228
+ help="Run on a connected cloud account (see: mctl cloud-account list). Repeat for more "
229
+ "(one per cloud). Not with --clouds. The API key needs the Infrastructure (infra) scope")
225
230
  @click.option("--classes", "classes_", multiple=True, callback=_classes_list,
226
231
  help="Runner class; repeat or separate with commas (see: mctl pool classes)")
227
232
  @click.option("--max-cost-per-hour", type=float, default=None, help="Cost ceiling in USD per hour")
233
+ @click.option("--set", "sets", multiple=True, metavar="NAME=VALUE",
234
+ help="Set one setting, e.g. regions=us-east-1,us-west-2 with --cloud-account (a flat list; "
235
+ "without it, every region of the accounts). Repeat")
236
+ @click.option("--settings", "settings_json", callback=_json_value, default=None,
237
+ help="JSON object of settings, or @file.json")
228
238
  @click.option("--image-by-class", callback=_json_value, default=None, help="JSON object, or @file.json")
229
239
  @click.option("--egress-by-class", callback=_json_value, default=None, help="JSON object, or @file.json")
230
240
  @click.option("--class-headroom", callback=_json_value, default=None, help="JSON object, or @file.json")
@@ -237,15 +247,27 @@ def _classes_list(ctx, param, value):
237
247
  help="Same key and body within 24 hours creates one pool (default: a new random key)")
238
248
  @json_option
239
249
  @click.pass_context
240
- def create(ctx, name, github_org, clouds, classes_, max_cost_per_hour, image_by_class, egress_by_class,
241
- class_headroom, spot_policy, cpu_units_requests, from_file, idempotency_key, as_json):
242
- """Create a CI pool."""
250
+ def create(ctx, name, github_org, clouds, cloud_accounts, classes_, max_cost_per_hour, sets, settings_json,
251
+ image_by_class, egress_by_class, class_headroom, spot_policy, cpu_units_requests, from_file,
252
+ idempotency_key, as_json):
253
+ """Create a CI pool, on cloud keys (--clouds) or on connected cloud accounts (--cloud-account)."""
243
254
  body = load_body(from_file)
244
255
  body.update(_collect(name=name, github_org=github_org, clouds=clouds, classes=classes_,
245
256
  max_cost_per_hour=max_cost_per_hour, image_by_class=image_by_class,
246
257
  egress_by_class=egress_by_class, class_headroom=class_headroom,
247
258
  spot_policy=spot_policy, cpu_units_requests=cpu_units_requests))
248
- missing = [f for f in ("name", "github_org", "clouds", "classes", "max_cost_per_hour") if f not in body]
259
+ if cloud_accounts:
260
+ body["cloud_accounts"] = [{"id": i} for i in cloud_accounts]
261
+ settings = _settings_body(sets, (), settings_json)
262
+ if settings:
263
+ if not isinstance(body.get("settings", {}), dict):
264
+ raise click.UsageError("'settings' in --from-file must be a JSON object.")
265
+ body["settings"] = {**(body.get("settings") or {}), **settings}
266
+ if "clouds" in body and "cloud_accounts" in body:
267
+ raise click.UsageError("Use --cloud-account or --clouds, not both (also not both in --from-file).")
268
+ needed = ("name", "github_org", "classes", "max_cost_per_hour") if "cloud_accounts" in body else \
269
+ ("name", "github_org", "clouds", "classes", "max_cost_per_hour")
270
+ missing = [f for f in needed if f not in body]
249
271
  if missing:
250
272
  raise click.UsageError("Missing: " + ", ".join("--" + m.replace("_", "-") if m != "name" else "NAME"
251
273
  for m in missing))
@@ -253,7 +275,8 @@ def create(ctx, name, github_org, clouds, classes_, max_cost_per_hour, image_by_
253
275
 
254
276
  def go(org):
255
277
  try:
256
- return api.call("POST", org, "/pools", body=body, headers={"Idempotency-Key": key}, scope=WRITE)
278
+ return api.call("POST", org, "/pools", body=body, headers={"Idempotency-Key": key},
279
+ scope="infra" if "cloud_accounts" in body else WRITE)
257
280
  except api.ApiError as ex:
258
281
  if ex.status is None or ex.status >= 500:
259
282
  # The pool may exist already: the same key and body make the retry safe.
@@ -263,6 +286,8 @@ def create(ctx, name, github_org, clouds, classes_, max_cost_per_hour, image_by_
263
286
  if as_json:
264
287
  return _dump(made)
265
288
  click.echo(f"Pool {made.get('pool_id')} ({made.get('name')}) created. Status: {_status(made)}")
289
+ for line in quota_lines(made.get("quota")) if "cloud_accounts" in body else ():
290
+ click.echo(line)
266
291
  click.echo(f"Next: mctl pool show {made.get('pool_id')}")
267
292
 
268
293
 
@@ -279,7 +304,7 @@ def _put(settings: Dict[str, Any], name: str, value: Any) -> None:
279
304
 
280
305
 
281
306
  _LIST_SETTINGS = ("instance_types", "excluded_instance_types", "accelerator_names",
282
- "excluded_accelerator_names")
307
+ "excluded_accelerator_names", "regions")
283
308
 
284
309
 
285
310
  def _settings_body(sets, resets, settings_json) -> Dict[str, Any]:
@@ -125,6 +125,31 @@ def test_extend_create_flags(monkeypatch):
125
125
  assert "Next: mctl peering create edge" in r.stdout
126
126
 
127
127
 
128
+ def test_extend_create_pool_cloud_account_option(monkeypatch):
129
+ r, calls = run(["extend", "create", "edge", "--cloud-account", "7", "--cloud-account", "9",
130
+ "--max-servers", "5", "--idempotency-key", "k1"], [reply(202, POOL_MADE)], monkeypatch)
131
+ assert r.exit_code == 0, r.output
132
+ method, url, kw = calls[0]
133
+ assert (method, url) == ("POST", f"{BASE}/extend-pools")
134
+ assert kw["json"] == {"name": "edge", "max_servers": 5, "cloud_accounts": [{"id": 7}, {"id": 9}]}
135
+
136
+
137
+ def test_extend_create_pool_from_file_may_carry_cloud_accounts(monkeypatch, tmp_path):
138
+ f = tmp_path / "p.json"
139
+ f.write_text(json.dumps({"name": "edge", "cloud_accounts": [{"id": 7}]}))
140
+ r, calls = run(["extend", "create", "--from-file", str(f)], [reply(202, POOL_MADE)], monkeypatch)
141
+ assert r.exit_code == 0, r.output
142
+ assert calls[0][2]["json"] == {"name": "edge", "cloud_accounts": [{"id": 7}]}
143
+
144
+
145
+ def test_extend_create_pool_prints_quota_lines_only_when_the_answer_has_them(monkeypatch):
146
+ r, _ = run(["extend", "create", "edge", "--cloud-account", "7"],
147
+ [reply(202, {**POOL_MADE, "quota": {"notes": ["later"]}})], monkeypatch)
148
+ assert "quota NOTE" in r.stdout
149
+ r, _ = run(["extend", "create", "edge"], [reply(202, POOL_MADE)], monkeypatch)
150
+ assert "quota" not in r.stdout
151
+
152
+
128
153
  def test_extend_create_only_name_sends_only_name(monkeypatch):
129
154
  r, calls = run(["extend", "create", "edge"], [reply(202, POOL_MADE)], monkeypatch)
130
155
  assert calls[0][2]["json"] == {"name": "edge"}
@@ -685,10 +685,15 @@ class Tool:
685
685
  return [" ".join(a[:3]) for _, a, _ in self.calls]
686
686
 
687
687
 
688
- def _run_cmd(args, tool, tmp_path, monkeypatch, tty=False, tf=PATH_A_TF, answers=None, aws=True):
688
+ def _run_cmd(args, tool, tmp_path, monkeypatch, tty=False, tf=PATH_A_TF, answers=None, aws=True, sso=True):
689
689
  (tmp_path / "multicloud.tf").write_text(tf)
690
690
  monkeypatch.setenv("MULTICLOUD_API_KEY", "fake-key-0000")
691
691
  monkeypatch.setenv("MULTICLOUD_ORG", "acme")
692
+ # destroy disconnects with the sign-in (an owner route); apply keeps using the API key.
693
+ monkeypatch.setenv("MULTICLOUD_ISSUER", "https://auth.example.test/realms/multicloud")
694
+ monkeypatch.setattr(auth, "load_sso", lambda issuer: {"session": "x"} if sso else None)
695
+ monkeypatch.setattr(auth, "fresh_access_token", lambda issuer: "sso-token")
696
+ monkeypatch.setattr(cmds.api, "_sso_org", lambda slug, token, explicit=True: slug)
692
697
  monkeypatch.setenv("TF_LOG", "DEBUG")
693
698
  monkeypatch.setattr(cmds, "_stdin_is_tty", lambda: tty)
694
699
  monkeypatch.setattr(cmds, "_sleep", lambda s: None)
@@ -829,3 +834,92 @@ def test_destroy_for_another_cloud_account_is_refused(tmp_path, monkeypatch):
829
834
  tool = Tool()
830
835
  r, _ = _run_cmd(["destroy", "6", "--yes"], tool, tmp_path, monkeypatch)
831
836
  assert r.exit_code == 1 and not tool.calls
837
+
838
+
839
+ # --- disconnect ---------------------------------------------------------------------------------
840
+
841
+ VERIFIED_CONNECTED = {**VERIFIED, "connected_on": "2026-11-11T10:00:00Z"}
842
+ REVOKED = {**VERIFIED, "status": "revoked", "status_reason": "disconnected by an organization owner"}
843
+ IN_USE = {"detail": {"code": "ACCOUNT_IN_USE", "message": "This AWS account is still in use",
844
+ "details": {"pools": ["ci-runners"], "other_organization_pools": 0, "live_servers": 2}}}
845
+ DELETE_URL = "https://api.multicloud.io/api/v1/orgs/acme/cloud-accounts/5"
846
+
847
+
848
+ def test_disconnect_with_yes_uses_the_sign_in():
849
+ r, req = invoke_seq(["cloud-account", "disconnect", "5", "--yes"],
850
+ [reply(200, VERIFIED_CONNECTED), reply(200, REVOKED)])
851
+ assert r.exit_code == 0, r.output
852
+ assert [c.args[:2] for c in req.call_args_list] == [("GET", DELETE_URL), ("DELETE", DELETE_URL)]
853
+ for sent in req.call_args_list: # the sign-in, never the API key
854
+ assert sent.kwargs["headers"]["Authorization"] == "Bearer sso-token"
855
+ assert "X-API-Key" not in sent.kwargs["headers"]
856
+ assert f"Disconnected: AWS account {ACCT} is no longer connected to Multicloud." in r.stdout
857
+ assert "tofu destroy" in r.stdout and "mctl cloud-account destroy 5" in r.stdout
858
+
859
+
860
+ def test_disconnect_asks_first():
861
+ r, req = invoke_seq(["cloud-account", "disconnect", "5"], [reply(200, VERIFIED)], input="n\n")
862
+ assert r.exit_code == 1 and req.call_count == 1 and "Nothing changed." in r.stderr
863
+ assert f"This disconnects AWS account {ACCT} from your organization." in r.stdout
864
+ assert "Nothing in the AWS account is deleted." in r.stdout
865
+ r, req = invoke_seq(["cloud-account", "disconnect", "5"], [reply(200, VERIFIED), reply(200, REVOKED)],
866
+ input="y\n")
867
+ assert r.exit_code == 0 and req.call_args_list[1].args[0] == "DELETE"
868
+
869
+
870
+ def test_disconnect_without_a_terminal_needs_yes():
871
+ r, req = invoke_seq(["cloud-account", "disconnect", "5"], [reply(200, VERIFIED)], tty=False)
872
+ assert r.exit_code == 1 and req.call_count == 1 and "--yes" in r.stderr
873
+
874
+
875
+ def test_disconnect_without_a_sign_in_names_the_login():
876
+ r, req = invoke_seq(["cloud-account", "disconnect", "5", "--yes"], [reply(200, VERIFIED)], sso=False)
877
+ assert r.exit_code == 3 and not req.called and "mctl auth login" in r.stderr
878
+
879
+
880
+ def test_disconnect_in_use_lists_the_pools_and_changes_nothing():
881
+ r, req = invoke_seq(["cloud-account", "disconnect", "5", "--yes"], [reply(200, VERIFIED), reply(409, IN_USE)])
882
+ assert r.exit_code == 1
883
+ assert "Cloud account 5 is still in use, so it stays connected. Nothing changed." in r.stderr
884
+ assert "Pool ci-runners: delete it with 'mctl pool delete ci-runners'." in r.stderr
885
+ assert "2 server(s) still run in it." in r.stderr
886
+ assert "mctl cloud-account disconnect 5' again" in r.stderr
887
+ assert "Disconnected" not in r.stdout
888
+
889
+
890
+ def test_disconnect_an_already_disconnected_account_does_nothing():
891
+ r, req = invoke_seq(["cloud-account", "disconnect", "5", "--yes"], [reply(200, REVOKED)])
892
+ assert r.exit_code == 0 and req.call_count == 1 and "already disconnected" in r.stdout
893
+
894
+
895
+ def test_destroy_disconnects_before_it_closes(tmp_path, monkeypatch):
896
+ tool = Tool()
897
+ r, fake = _run_cmd(["destroy", "5", "--yes"], tool, tmp_path, monkeypatch, answers=[reply(200, REVOKED)])
898
+ assert r.exit_code == 0, r.output + r.stderr
899
+ assert fake.calls == [("DELETE", DELETE_URL)]
900
+ assert "Disconnected cloud account 5 from your organization." in r.stdout
901
+ # the order: Multicloud first, then the account closes
902
+ out = r.stdout
903
+ assert out.index("Disconnected cloud account 5") < out.index("Closing AWS account 999999999999")
904
+
905
+
906
+ def test_destroy_stops_before_closing_when_a_pool_uses_the_account(tmp_path, monkeypatch):
907
+ tool = Tool()
908
+ r, fake = _run_cmd(["destroy", "5", "--yes"], tool, tmp_path, monkeypatch, answers=[reply(409, IN_USE)])
909
+ assert r.exit_code == 1
910
+ assert "mctl cloud-account destroy 5' again" in r.stderr
911
+ assert tool.seq() == ["output -json"] # nothing removed, nothing closed
912
+
913
+
914
+ def test_destroy_without_a_sign_in_closes_nothing(tmp_path, monkeypatch):
915
+ tool = Tool()
916
+ r, fake = _run_cmd(["destroy", "5", "--yes"], tool, tmp_path, monkeypatch, sso=False)
917
+ assert r.exit_code == 3 and "mctl auth login" in r.stderr
918
+ assert not fake.calls and tool.seq() == ["output -json"]
919
+
920
+
921
+ def test_disconnect_a_never_connected_account_has_no_next_step():
922
+ pending = {"id": 5, "cloud": "AWS", "status": "pending", "expected_native_id": ACCT}
923
+ r, req = invoke_seq(["cloud-account", "disconnect", "5", "--yes"], [reply(200, pending), reply(200, REVOKED)])
924
+ assert r.exit_code == 0 and "Disconnected:" in r.stdout
925
+ assert "Next:" not in r.stdout
@@ -116,6 +116,54 @@ def test_create_body_equals_flags(monkeypatch):
116
116
  assert "Pool 7 (ci) created" in r.stdout
117
117
 
118
118
 
119
+ def test_pool_create_cloud_account_option_builds_body(monkeypatch):
120
+ quota = {"filed": [], "notes": ["spot quota is not checked or filed for pools on connected cloud accounts"]}
121
+ r, calls, _ = run(["create", "ci", "--github-org", "acme-gh", "--cloud-account", "7", "--cloud-account", "9",
122
+ "--classes", "cpu-4", "--max-cost-per-hour", "2.5", "--set", "regions=us-east-1,us-west-2",
123
+ "--idempotency-key", "k1"],
124
+ [reply(201, {**pool_view(), "quota": quota})], monkeypatch)
125
+ assert r.exit_code == 0, r.output
126
+ method, url, kw = calls[0]
127
+ assert (method, url) == ("POST", f"{BASE}/pools")
128
+ # CreatePoolRequest with cloud_accounts: no clouds key, regions in settings (H5)
129
+ assert kw["json"] == {"name": "ci", "github_org": "acme-gh", "cloud_accounts": [{"id": 7}, {"id": 9}],
130
+ "classes": ["cpu-4"], "max_cost_per_hour": 2.5,
131
+ "settings": {"regions": ["us-east-1", "us-west-2"]}}
132
+ assert "quota NOTE" in r.stdout and "quota FILED" not in r.stdout
133
+
134
+
135
+ def test_pool_create_cloud_account_and_clouds_are_exclusive(monkeypatch, tmp_path):
136
+ base = ["create", "ci", "--github-org", "g", "--classes", "cpu-4", "--max-cost-per-hour", "1"]
137
+ r, calls, _ = run(base + ["--cloud-account", "7", "--clouds", '[{"type":"AWS"}]'],
138
+ [reply(201, pool_view())], monkeypatch)
139
+ assert r.exit_code == 2 and not calls and "not both" in r.stderr
140
+ f = tmp_path / "p.json"
141
+ f.write_text(json.dumps({"clouds": [{"type": "AWS"}]}))
142
+ r, calls, _ = run(base + ["--cloud-account", "7", "--from-file", str(f)], [reply(201, pool_view())], monkeypatch)
143
+ assert r.exit_code == 2 and not calls
144
+
145
+
146
+ def test_pool_create_from_file_may_carry_cloud_accounts(monkeypatch, tmp_path):
147
+ body = {"name": "ci", "github_org": "g", "cloud_accounts": [{"id": 7}], "classes": ["cpu-4"],
148
+ "max_cost_per_hour": 1.0, "settings": {"regions": ["us-east-1"]}}
149
+ f = tmp_path / "pool.json"
150
+ f.write_text(json.dumps(body))
151
+ r, calls, _ = run(["create", "--from-file", str(f)], [reply(201, pool_view())], monkeypatch)
152
+ assert r.exit_code == 0, r.output
153
+ assert calls[0][2]["json"] == body
154
+
155
+
156
+ def test_pool_create_without_any_cloud_names_both_options(monkeypatch):
157
+ r, calls, _ = run(["create", "ci", "--github-org", "g", "--classes", "cpu-4", "--max-cost-per-hour", "1"],
158
+ [reply(201, pool_view())], monkeypatch)
159
+ assert r.exit_code == 2 and not calls and "--clouds" in r.stderr
160
+
161
+
162
+ def test_pool_create_help_names_the_infra_scope():
163
+ r = CliRunner().invoke(mctl, ["pool", "create", "--help"])
164
+ assert "--cloud-account" in r.output and "infra" in r.output
165
+
166
+
119
167
  def test_create_from_file_and_flag_override(monkeypatch, tmp_path):
120
168
  # CreatePoolRequest
121
169
  body = {"name": "ci", "github_org": "acme-gh", "clouds": [{"type": "AWS"}], "classes": ["cpu-4"],
@@ -1 +0,0 @@
1
- __version__ = "0.5.1"
File without changes
File without changes