multicloud-cli 0.4.1__tar.gz → 0.5.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.4.1 → multicloud_cli-0.5.0}/PKG-INFO +3 -2
  2. {multicloud_cli-0.4.1 → multicloud_cli-0.5.0}/README.md +2 -1
  3. multicloud_cli-0.5.0/multicloud_cli/__init__.py +1 -0
  4. {multicloud_cli-0.4.1 → multicloud_cli-0.5.0}/multicloud_cli/cloud_account.py +210 -18
  5. {multicloud_cli-0.4.1 → multicloud_cli-0.5.0}/multicloud_cli/extend.py +2 -1
  6. {multicloud_cli-0.4.1 → multicloud_cli-0.5.0}/tests/test_account_extend.py +6 -0
  7. {multicloud_cli-0.4.1 → multicloud_cli-0.5.0}/tests/test_cloud_account.py +264 -0
  8. multicloud_cli-0.4.1/multicloud_cli/__init__.py +0 -1
  9. {multicloud_cli-0.4.1 → multicloud_cli-0.5.0}/.gitignore +0 -0
  10. {multicloud_cli-0.4.1 → multicloud_cli-0.5.0}/LICENSE +0 -0
  11. {multicloud_cli-0.4.1 → multicloud_cli-0.5.0}/multicloud_cli/account.py +0 -0
  12. {multicloud_cli-0.4.1 → multicloud_cli-0.5.0}/multicloud_cli/api.py +0 -0
  13. {multicloud_cli-0.4.1 → multicloud_cli-0.5.0}/multicloud_cli/auth.py +0 -0
  14. {multicloud_cli-0.4.1 → multicloud_cli-0.5.0}/multicloud_cli/catalog.py +0 -0
  15. {multicloud_cli-0.4.1 → multicloud_cli-0.5.0}/multicloud_cli/config.py +0 -0
  16. {multicloud_cli-0.4.1 → multicloud_cli-0.5.0}/multicloud_cli/duration.py +0 -0
  17. {multicloud_cli-0.4.1 → multicloud_cli-0.5.0}/multicloud_cli/exitcodes.py +0 -0
  18. {multicloud_cli-0.4.1 → multicloud_cli-0.5.0}/multicloud_cli/main.py +0 -0
  19. {multicloud_cli-0.4.1 → multicloud_cli-0.5.0}/multicloud_cli/net.py +0 -0
  20. {multicloud_cli-0.4.1 → multicloud_cli-0.5.0}/multicloud_cli/node.py +0 -0
  21. {multicloud_cli-0.4.1 → multicloud_cli-0.5.0}/multicloud_cli/orgopt.py +0 -0
  22. {multicloud_cli-0.4.1 → multicloud_cli-0.5.0}/multicloud_cli/output.py +0 -0
  23. {multicloud_cli-0.4.1 → multicloud_cli-0.5.0}/multicloud_cli/pool.py +0 -0
  24. {multicloud_cli-0.4.1 → multicloud_cli-0.5.0}/multicloud_cli/ssh.py +0 -0
  25. {multicloud_cli-0.4.1 → multicloud_cli-0.5.0}/multicloud_cli/ssh_cert.py +0 -0
  26. {multicloud_cli-0.4.1 → multicloud_cli-0.5.0}/multicloud_cli/sso.py +0 -0
  27. {multicloud_cli-0.4.1 → multicloud_cli-0.5.0}/pyproject.toml +0 -0
  28. {multicloud_cli-0.4.1 → multicloud_cli-0.5.0}/tests/__init__.py +0 -0
  29. {multicloud_cli-0.4.1 → multicloud_cli-0.5.0}/tests/conftest.py +0 -0
  30. {multicloud_cli-0.4.1 → multicloud_cli-0.5.0}/tests/helpers.py +0 -0
  31. {multicloud_cli-0.4.1 → multicloud_cli-0.5.0}/tests/test_apply.py +0 -0
  32. {multicloud_cli-0.4.1 → multicloud_cli-0.5.0}/tests/test_auth.py +0 -0
  33. {multicloud_cli-0.4.1 → multicloud_cli-0.5.0}/tests/test_catalog.py +0 -0
  34. {multicloud_cli-0.4.1 → multicloud_cli-0.5.0}/tests/test_conventions.py +0 -0
  35. {multicloud_cli-0.4.1 → multicloud_cli-0.5.0}/tests/test_net.py +0 -0
  36. {multicloud_cli-0.4.1 → multicloud_cli-0.5.0}/tests/test_pool.py +0 -0
  37. {multicloud_cli-0.4.1 → multicloud_cli-0.5.0}/tests/test_ssh.py +0 -0
  38. {multicloud_cli-0.4.1 → multicloud_cli-0.5.0}/tests/test_ssh_cert.py +0 -0
  39. {multicloud_cli-0.4.1 → multicloud_cli-0.5.0}/tests/test_sso.py +0 -0
  40. {multicloud_cli-0.4.1 → multicloud_cli-0.5.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.4.1
3
+ Version: 0.5.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>
@@ -74,8 +74,9 @@ mctl cloud-account verify 7 --wait
74
74
  |---|---|
75
75
  | `mctl auth login` | Sign in with your browser (SSO). `--no-browser` prints a code to enter on another device (SSH, containers). `--api-key` stores an API key instead (hidden prompt or `--key-stdin`). |
76
76
  | `mctl auth status` / `logout` | Show how you are signed in and check it works; end the SSO session (the stored API key stays; `logout --api-key` deletes it). |
77
- | `mctl cloud-account create` | Declare an AWS account and write `multicloud.tf`. |
77
+ | `mctl cloud-account create` | Declare an AWS account (or `--new-account-email` for a new one) and write `multicloud.tf`. |
78
78
  | `mctl cloud-account apply <id>` | `init`, `plan`, a question (`--yes` skips it, `--plan-only` stops after the plan), then `apply` with a fresh connect code and a wait for the check. |
79
+ | `mctl cloud-account destroy <id>` | For a `--new-account-email` file: remove the role and close the AWS account the file created (asks first). |
79
80
  | `mctl cloud-account token <id>` | A new one-time connect code, for a manual `terraform apply`. |
80
81
  | `mctl cloud-account verify <id> [--wait]` | Check the role again: `Ready` (exit 0), the missing permissions (exit 1) or pending (exit 5). |
81
82
  | `mctl cloud-account list` / `show <id> [--json]` | The connections of your organization. |
@@ -43,8 +43,9 @@ mctl cloud-account verify 7 --wait
43
43
  |---|---|
44
44
  | `mctl auth login` | Sign in with your browser (SSO). `--no-browser` prints a code to enter on another device (SSH, containers). `--api-key` stores an API key instead (hidden prompt or `--key-stdin`). |
45
45
  | `mctl auth status` / `logout` | Show how you are signed in and check it works; end the SSO session (the stored API key stays; `logout --api-key` deletes it). |
46
- | `mctl cloud-account create` | Declare an AWS account and write `multicloud.tf`. |
46
+ | `mctl cloud-account create` | Declare an AWS account (or `--new-account-email` for a new one) and write `multicloud.tf`. |
47
47
  | `mctl cloud-account apply <id>` | `init`, `plan`, a question (`--yes` skips it, `--plan-only` stops after the plan), then `apply` with a fresh connect code and a wait for the check. |
48
+ | `mctl cloud-account destroy <id>` | For a `--new-account-email` file: remove the role and close the AWS account the file created (asks first). |
48
49
  | `mctl cloud-account token <id>` | A new one-time connect code, for a manual `terraform apply`. |
49
50
  | `mctl cloud-account verify <id> [--wait]` | Check the role again: `Ready` (exit 0), the missing permissions (exit 1) or pending (exit 5). |
50
51
  | `mctl cloud-account list` / `show <id> [--json]` | The connections of your organization. |
@@ -0,0 +1 @@
1
+ __version__ = "0.5.0"
@@ -28,6 +28,11 @@ from .orgopt import org_group, org_option
28
28
  TOKEN_VARIABLE = "multicloud_connect_token"
29
29
  TOKEN_ENV = "TF_VAR_" + TOKEN_VARIABLE
30
30
  TF_FILE = "multicloud.tf"
31
+ TFVARS_FILE = "multicloud.auto.tfvars"
32
+ ACCOUNT_MODULE = "module.multicloud_account"
33
+ ACCOUNT_RESOURCE = ACCOUNT_MODULE + ".aws_organizations_account.this"
34
+ _PATH_A = re.compile(r'^\s*module\s+"multicloud_account"\s*\{', re.M)
35
+ _EMAIL = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")
31
36
  PLAN_PLACEHOLDER = "plan-placeholder"
32
37
  _sleep = time.sleep # tests patch this name
33
38
 
@@ -186,7 +191,7 @@ def dedicated_label(account: Dict[str, Any]) -> str:
186
191
 
187
192
  def format_table(accounts, headers: bool = True) -> str:
188
193
  rows = ([("ID", "CLOUD", "STATUS", "ACCOUNT", "DEDICATED")] if headers else []) + [
189
- (str(a.get("id")), str(a.get("cloud")), str(a.get("status")), str(a.get("expected_native_id")),
194
+ (str(a.get("id")), str(a.get("cloud")), str(a.get("status")), str(a.get("expected_native_id") or a.get("native_id") or "-"),
190
195
  dedicated_label(a))
191
196
  for a in accounts]
192
197
  if not rows:
@@ -224,9 +229,24 @@ def _run(ctx, fn):
224
229
  return run(ctx.obj.get("cloud_account_org"), fn, (CloudAccountError,))
225
230
 
226
231
 
232
+ def _hcl_string(text: str) -> str:
233
+ """A double-quoted HCL string literal (no interpolation or template directive)."""
234
+ out = text.replace("\\", "\\\\").replace('"', '\\"').replace("\n", "\\n").replace("\r", "\\r")
235
+ return '"' + out.replace("${", "$${").replace("%{", "%%{") + '"'
236
+
237
+
238
+ def _file_exists(name: str):
239
+ click.echo(f"Error: {name} exists in this directory. Move it, or run again with --force to "
240
+ f"overwrite it.", err=True)
241
+ sys.exit(1)
242
+
243
+
227
244
  @cloud_account.command()
228
245
  @click.option("--cloud", required=True, type=click.Choice(["AWS", "GCE"], case_sensitive=False))
229
- @click.option("--account", help="The 12-digit AWS account id (required for AWS, not allowed for GCE)")
246
+ @click.option("--account", help="AWS: pin the 12-digit AWS account id (optional; not allowed for GCE)")
247
+ @click.option("--new-account-email", "new_email", metavar="EMAIL",
248
+ help="AWS: create a new AWS account for Multicloud in your AWS Organizations, with this email "
249
+ "(not allowed with --account)")
230
250
  @click.option("--region", "regions", multiple=True, help="Region to allow; repeat for several")
231
251
  @click.option("--force", is_flag=True, help="Overwrite an existing multicloud.tf")
232
252
  @click.option("--opt-in-regions/--no-opt-in-regions", "opt_in", default=None,
@@ -234,26 +254,49 @@ def _run(ctx, fn):
234
254
  "asks when stdin is a terminal)")
235
255
  @json_option
236
256
  @click.pass_context
237
- def create(ctx, cloud, account, regions, force, opt_in, as_json):
257
+ def create(ctx, cloud, account, new_email, regions, force, opt_in, as_json):
238
258
  """Register an account and write multicloud.tf. No token is printed.
239
259
 
240
260
  An existing multicloud.tf is kept: a new external id in it would cut off a connected account.
241
261
 
262
+ With --new-account-email, the file creates a new AWS account for Multicloud in your AWS Organizations
263
+ and connects it (run 'apply' with your management account credentials). The email goes to
264
+ multicloud.auto.tfvars. Without --account, the account ID is read when the module connects.
265
+
242
266
  AWS opt-in regions (for example af-south-1) are off in a new account. With the default, Multicloud
243
267
  turns them on (only the --region ones when you give --region). That takes minutes to hours; verify
244
268
  again to add them."""
245
269
  gce = cloud.upper() == "GCE"
246
270
  if gce and account:
247
271
  raise click.UsageError("--account is not allowed for GCE: Multicloud generates the project id.")
248
- if not gce and not account:
249
- raise click.UsageError("--account is required for AWS.")
272
+ if gce and new_email:
273
+ raise click.UsageError("--new-account-email applies to AWS only.")
274
+ if new_email and account:
275
+ raise click.UsageError("--new-account-email and --account cannot be used together: a new account "
276
+ "has no ID yet.")
250
277
  if gce and opt_in is not None:
251
278
  raise click.UsageError("--opt-in-regions applies to AWS only.")
279
+ if new_email:
280
+ new_email = new_email.strip()
281
+ if not _EMAIL.match(new_email):
282
+ raise click.UsageError(f"'{new_email}' is not an email address.")
283
+ if _stdin_is_tty():
284
+ again = click.prompt("Type the email of the new AWS account again", default="", show_default=False,
285
+ err=True)
286
+ if again.strip() != new_email:
287
+ click.echo("The two emails are different. Nothing was created. A typo here would make an AWS "
288
+ "account with the wrong email.", err=True)
289
+ sys.exit(1)
252
290
  if Path(TF_FILE).exists() and not force:
253
291
  _tf_file_exists()
292
+ if new_email and Path(TFVARS_FILE).exists() and not force:
293
+ _file_exists(TFVARS_FILE)
254
294
  body = {"cloud": cloud.upper()}
255
295
  if not gce:
256
- body["expected_native_id"] = account
296
+ if account:
297
+ body["expected_native_id"] = account
298
+ if new_email:
299
+ body["new_account"] = True
257
300
  if opt_in is None:
258
301
  opt_in = (click.confirm("Turn on the AWS opt-in regions in this account?", default=True, err=True)
259
302
  if _stdin_is_tty() else True)
@@ -266,12 +309,32 @@ def create(ctx, cloud, account, regions, force, opt_in, as_json):
266
309
  f.write(made["terraform"])
267
310
  except FileExistsError: # created after the check above
268
311
  _tf_file_exists()
312
+ if new_email:
313
+ try:
314
+ with open(TFVARS_FILE, "w" if force else "x") as f: # the email only, never a token
315
+ f.write(f"multicloud_account_email = {_hcl_string(new_email)}\n")
316
+ except FileExistsError:
317
+ _file_exists(TFVARS_FILE)
269
318
  acct_id = made["account"]["id"]
270
319
  if as_json: # the created account; the Terraform file is in multicloud.tf
271
320
  _dump(made["account"])
272
321
  say = lambda text: click.echo(text, err=as_json) # noqa: E731
273
- target = f"GCP project {made['account'].get('expected_native_id')}" if gce else f"AWS account {account}"
274
- say(f"Cloud account {acct_id} created for {target}. Wrote {TF_FILE}.")
322
+ if gce:
323
+ target = f"GCP project {made['account'].get('expected_native_id')}"
324
+ elif account:
325
+ target = f"AWS account {account}"
326
+ elif new_email:
327
+ target = f"a new AWS account (email {new_email})"
328
+ else:
329
+ target = "an AWS account"
330
+ say(f"Cloud account {acct_id} created for {target}. Wrote "
331
+ f"{TF_FILE + ' and ' + TFVARS_FILE if new_email else TF_FILE}.")
332
+ if new_email:
333
+ say("When you apply, AWS creates the new account in your AWS Organizations. Run apply with the "
334
+ "credentials of your AWS management account. Multicloud gets no access to the management account.")
335
+ elif not gce and not account:
336
+ say("The AWS account ID is read when the module connects. The account should be a new AWS account "
337
+ "made for Multicloud.")
275
338
  say(f"Next: mctl cloud-account apply {acct_id}")
276
339
  say(f"By hand: mctl cloud-account token {acct_id}, then tofu apply (or terraform apply).")
277
340
 
@@ -523,6 +586,110 @@ def _tool_run(tool: str, args, cwd: str, env: Dict[str, str]) -> int:
523
586
  raise CloudAccountError(f"Could not run {tool}: {ex}")
524
587
 
525
588
 
589
+ def _tool_capture(tool: str, args, cwd: str, env: Dict[str, str]):
590
+ """Run the tool and return (exit code, stdout + stderr). Used for the read-only state commands."""
591
+ try:
592
+ done = subprocess.run([tool, *args], cwd=cwd, env=env, capture_output=True, text=True)
593
+ except OSError as ex:
594
+ raise CloudAccountError(f"Could not run {tool}: {ex}")
595
+ return done.returncode, (done.stdout or "") + (done.stderr or "")
596
+
597
+
598
+ def _check_file(account_id: int, directory: str) -> str:
599
+ """The text of multicloud.tf in the folder; exits when it is missing or for another cloud account."""
600
+ tf = Path(directory) / TF_FILE
601
+ if not tf.is_file():
602
+ click.echo(f"Error: {tf} does not exist. Run: mctl cloud-account create", err=True)
603
+ sys.exit(1)
604
+ text = tf.read_text()
605
+ found = re.search(r"account_row_id\s*=\s*(\d+)", text)
606
+ if found and int(found.group(1)) != account_id:
607
+ click.echo(f"Error: {TF_FILE} in {directory} is for cloud account {found.group(1)}, not {account_id}.",
608
+ err=True)
609
+ sys.exit(1)
610
+ return text
611
+
612
+
613
+ def _aws_account_state(account_id: str) -> Optional[str]:
614
+ """The state of an AWS account (ACTIVE, PENDING_CLOSURE, CLOSED) from the user's own AWS CLI,
615
+ or None when the CLI is missing or does not answer."""
616
+ if not shutil.which("aws"):
617
+ return None
618
+ try:
619
+ done = subprocess.run(["aws", "organizations", "describe-account", "--account-id", account_id,
620
+ "--query", "Account.State", "--output", "text"],
621
+ capture_output=True, text=True, timeout=30)
622
+ except (OSError, subprocess.SubprocessError):
623
+ return None
624
+ return done.stdout.strip() if done.returncode == 0 else None
625
+
626
+
627
+ @cloud_account.command()
628
+ @click.argument("account_id", type=int)
629
+ @click.option("--dir", "directory", default=".", type=click.Path(file_okay=False), help="Folder with multicloud.tf")
630
+ @click.option("--tool", type=click.Choice(["tofu", "terraform"]), default=None, help="Default: tofu, then terraform")
631
+ @click.option("-y", "--yes", is_flag=True, help="Destroy without asking")
632
+ @click.pass_context
633
+ def destroy(ctx, account_id, directory, tool, yes):
634
+ """Remove the Multicloud role and close the AWS account that multicloud.tf created.
635
+
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."""
638
+ text = _check_file(account_id, directory)
639
+ if not _PATH_A.search(text):
640
+ click.echo(f"{TF_FILE} did not create an AWS account, so there is no account for mctl to close.")
641
+ click.echo("To remove what the file created, run 'tofu destroy' (or 'terraform destroy') in the folder.")
642
+ click.echo("If you made the AWS account yourself, close it in the AWS console.")
643
+ return
644
+ tool = _run(ctx, lambda org: _find_tool(tool))
645
+ base_env = {k: v for k, v in os.environ.items()
646
+ if k not in (TOKEN_ENV, "MULTICLOUD_API_KEY") and not k.startswith("TF_LOG")}
647
+ env = {**base_env, TOKEN_ENV: PLAN_PLACEHOLDER}
648
+ aws_id = None
649
+ code, out = _run(ctx, lambda org: _tool_capture(tool, ["output", "-json"], directory, base_env))
650
+ try:
651
+ aws_id = str(json.loads(out)["multicloud_account_id"]["value"])
652
+ except (ValueError, KeyError, TypeError):
653
+ pass
654
+ which = f"AWS account {aws_id}" if aws_id else "the AWS account"
655
+ if not yes:
656
+ if not _stdin_is_tty():
657
+ click.echo("Error: Refusing to destroy without confirmation. Run again with --yes.", err=True)
658
+ sys.exit(1)
659
+ click.echo(f"This removes the Multicloud role and closes {which} that {TF_FILE} created.")
660
+ click.echo("AWS keeps a closed account for 90 days. Its email cannot be used again for a new AWS account.")
661
+ if not click.confirm(f"Close {which}?", default=False):
662
+ click.echo("Nothing destroyed.", err=True)
663
+ sys.exit(exitcodes.ERROR)
664
+ # The account closes with everything in it. Deleting the Spot service-linked role can be blocked
665
+ # for about 4 minutes after the last spot instance ends, so the destroy must not depend on it.
666
+ code, out = _run(ctx, lambda org: _tool_capture(tool, ["state", "rm", "module.multicloud"], directory, base_env))
667
+ if code != 0 and "No matching objects" not in out:
668
+ click.echo(out.rstrip(), err=True)
669
+ click.echo(f"Error: {tool} state rm module.multicloud failed (exit {code}). Nothing was destroyed.", err=True)
670
+ sys.exit(1)
671
+ click.echo(f"Closing {which}. This can take some minutes.")
672
+ code = _run(ctx, lambda org: _tool_run(tool, ["destroy", "-input=false", "-auto-approve"], directory, env))
673
+ if code == 0:
674
+ click.echo(f"Done. The Multicloud role is removed and {which} is closed.")
675
+ return
676
+ state = _aws_account_state(aws_id) if aws_id else None
677
+ if state in ("CLOSED", "PENDING_CLOSURE"):
678
+ click.echo("AWS closed the account; Terraform stopped waiting before AWS reported it. Nothing is broken.")
679
+ code, out = _run(ctx, lambda org: _tool_capture(tool, ["state", "rm", ACCOUNT_MODULE], directory, base_env))
680
+ if code != 0:
681
+ click.echo(out.rstrip(), err=True)
682
+ click.echo(f"Error: {tool} state rm {ACCOUNT_MODULE} failed (exit {code}). Run it by hand.", err=True)
683
+ sys.exit(1)
684
+ return
685
+ click.echo("Terraform can report a timeout while AWS closes the account. When the AWS console shows the "
686
+ f"account as Closed, run: {tool} state rm {ACCOUNT_MODULE}", err=True)
687
+ click.echo("If the account is not closing, fix the error above and run "
688
+ f"'mctl cloud-account destroy {account_id}' again. Terraform no longer tracks the Multicloud role; "
689
+ "it goes away when AWS closes the account.", err=True)
690
+ sys.exit(1)
691
+
692
+
526
693
  @cloud_account.command()
527
694
  @click.argument("account_id", type=int)
528
695
  @click.option("--dir", "directory", default=".", type=click.Path(file_okay=False), help="Folder with multicloud.tf")
@@ -539,14 +706,7 @@ def apply(ctx, account_id, directory, tool, plan_only, yes, timeout, interval):
539
706
 
540
707
  The token reaches tofu/terraform only through the environment of that one process."""
541
708
  tf = Path(directory) / TF_FILE
542
- if not tf.is_file():
543
- click.echo(f"Error: {tf} does not exist. Run: mctl cloud-account create", err=True)
544
- sys.exit(1)
545
- found = re.search(r"account_row_id\s*=\s*(\d+)", tf.read_text())
546
- if found and int(found.group(1)) != account_id:
547
- click.echo(f"Error: {TF_FILE} in {directory} is for cloud account {found.group(1)}, not {account_id}.",
548
- err=True)
549
- sys.exit(1)
709
+ _check_file(account_id, directory)
550
710
  tool = _run(ctx, lambda org: _find_tool(tool))
551
711
  # Terraform, its providers and the module's curl see this environment: no API key, no old token,
552
712
  # and no TF_LOG (a debug log could record the token).
@@ -559,13 +719,45 @@ def apply(ctx, account_id, directory, tool, plan_only, yes, timeout, interval):
559
719
  click.echo(f"Error: {tool} {what} failed (exit {code}).", err=True)
560
720
  sys.exit(1)
561
721
 
722
+ placeholder_env = {**base_env, TOKEN_ENV: PLAN_PLACEHOLDER}
562
723
  step(["init", "-input=false"], base_env, "init")
724
+ confirmed = False
725
+ if _PATH_A.search(tf.read_text()):
726
+ code, listed = _run(ctx, lambda org: _tool_capture(tool, ["state", "list"], directory, base_env))
727
+ if code != 0 and "No state file" not in listed:
728
+ # A lock or a backend error: never guess that the account is missing and create a second one.
729
+ click.echo(listed.rstrip(), err=True)
730
+ click.echo(f"Error: {tool} state list failed (exit {code}). Nothing was applied.", err=True)
731
+ sys.exit(1)
732
+ if ACCOUNT_RESOURCE not in listed.split():
733
+ click.echo("Stage 1 of 2: create the new AWS account. The plan uses a placeholder connect token.")
734
+ step(["plan", "-input=false", f"-target={ACCOUNT_MODULE}"], placeholder_env, "plan")
735
+ if plan_only:
736
+ click.echo("Plan only: no token issued. The plan of the Multicloud role can be shown only "
737
+ "after the new AWS account exists.")
738
+ click.echo(f"To create the account and connect it: mctl cloud-account apply {account_id}")
739
+ return
740
+ if not yes:
741
+ if not _stdin_is_tty():
742
+ click.echo("Error: Refusing to apply without confirmation. Review the plan, then run "
743
+ "again with --yes.", err=True)
744
+ sys.exit(1)
745
+ if not click.confirm("Create a new AWS account for Multicloud in your AWS Organizations, "
746
+ "then connect it?", default=False):
747
+ click.echo("Nothing applied.", err=True)
748
+ sys.exit(exitcodes.ERROR)
749
+ confirmed = True
750
+ step(["apply", "-input=false", "-auto-approve", f"-target={ACCOUNT_MODULE}"], placeholder_env,
751
+ "apply of the new AWS account")
752
+ click.echo("Stage 2 of 2: connect the new AWS account to Multicloud.")
753
+ else:
754
+ click.echo("The new AWS account exists already. Continuing with stage 2 of 2.")
563
755
  click.echo("The plan uses a placeholder connect token. The real token is issued only for the apply.")
564
- step(["plan", "-input=false"], {**base_env, TOKEN_ENV: PLAN_PLACEHOLDER}, "plan")
756
+ step(["plan", "-input=false"], placeholder_env, "plan")
565
757
  if plan_only:
566
758
  click.echo(f"Plan only: no token issued. To apply: mctl cloud-account apply {account_id} --yes")
567
759
  return
568
- if not yes:
760
+ if not yes and not confirmed:
569
761
  if not _stdin_is_tty():
570
762
  click.echo("Error: Refusing to apply without confirmation. Review the plan, then run again "
571
763
  "with --yes.", err=True)
@@ -104,7 +104,8 @@ def create_pool(ctx, name, max_servers, max_cost_per_hour, from_file, idempotenc
104
104
  GRANT_OPTIONS = (("cpu_millicores", "CPU the peering may use, in millicores (100-1000000)"),
105
105
  ("memory_mb", "Memory in MB (128-4000000)"),
106
106
  ("pods", "Number of pods (1-10000)"),
107
- ("ephemeral_storage_mb", "Ephemeral storage in MB (1024-10000000)"))
107
+ ("ephemeral_storage_mb", "Ephemeral storage in MB (1024-10000000)"),
108
+ ("gpu", "Whole NVIDIA GPUs (nvidia.com/gpu), 0-1000"))
108
109
 
109
110
 
110
111
  def _grant_options(f):
@@ -222,6 +222,12 @@ def test_peering_create_with_grant(monkeypatch):
222
222
  assert "Next: mctl peering show edge 4" in r.stdout
223
223
 
224
224
 
225
+ def test_peering_create_with_gpu(monkeypatch):
226
+ r, calls = run(["peering", "create", "edge", "--gpu", "1"], [reply(202, PEERING)], monkeypatch)
227
+ assert r.exit_code == 0, r.output
228
+ assert calls[0][2]["json"] == {"gpu": 1}
229
+
230
+
225
231
  def test_peering_create_no_grant_sends_empty_body_and_file(monkeypatch, tmp_path):
226
232
  r, calls = run(["peering", "create", "edge"], [reply(202, PEERING)], monkeypatch)
227
233
  assert calls[0][2]["json"] == {}
@@ -565,3 +565,267 @@ def test_list_and_show_name_dedicated_and_the_approval():
565
565
  assert "Shared account approved on: 2026-11-10T10:00:00Z" in r.stdout
566
566
  r, _ = invoke(["cloud-account", "show", "7"], reply(200, SHARED))
567
567
  assert "mctl cloud-account accept-shared-account 7" in r.stdout
568
+
569
+
570
+ # ---- AWS dedicated account (path A) ----
571
+
572
+ PATH_A_TF = ('module "multicloud_account" {\n name = "x"\n}\nmodule "multicloud" {\n account_row_id = 5\n}\n')
573
+ EMAIL = "aws+multicloud@example.com"
574
+
575
+
576
+ def _runner():
577
+ try:
578
+ return CliRunner(mix_stderr=False)
579
+ except TypeError:
580
+ return CliRunner()
581
+
582
+
583
+ def _create_a(args, tty=False, typed=None, monkeypatch=None):
584
+ body = {"account": {"id": 5, "status": "pending"}, "connect_token": TOKEN,
585
+ "connect_token_expires_at": "x", "terraform": PATH_A_TF}
586
+ monkeypatch.setenv("MULTICLOUD_API_KEY", "fake-key-0000")
587
+ monkeypatch.setenv("MULTICLOUD_ORG", "acme")
588
+ monkeypatch.setattr(cmds, "_stdin_is_tty", lambda: tty)
589
+ with patch.object(cmds.requests, "request", return_value=reply(201, body)) as req:
590
+ r = _runner().invoke(mctl, ["cloud-account", "create", *args], input=typed)
591
+ return r, req
592
+
593
+
594
+ def test_create_new_account_sends_new_account_and_writes_tfvars(tmp_path, monkeypatch):
595
+ monkeypatch.chdir(tmp_path)
596
+ r, req = _create_a(["--cloud", "AWS", "--new-account-email", EMAIL], monkeypatch=monkeypatch)
597
+ assert r.exit_code == 0, r.output
598
+ sent = req.call_args.kwargs["json"]
599
+ assert sent["new_account"] is True and "expected_native_id" not in sent
600
+ assert (tmp_path / "multicloud.auto.tfvars").read_text() == f'multicloud_account_email = "{EMAIL}"\n'
601
+ for f in tmp_path.iterdir():
602
+ assert TOKEN not in f.read_text()
603
+ assert TOKEN not in r.stdout + r.stderr
604
+
605
+
606
+ def test_create_new_account_keeps_an_existing_tfvars(tmp_path, monkeypatch):
607
+ monkeypatch.chdir(tmp_path)
608
+ (tmp_path / "multicloud.auto.tfvars").write_text("keep\n")
609
+ r, req = _create_a(["--cloud", "AWS", "--new-account-email", EMAIL], monkeypatch=monkeypatch)
610
+ assert r.exit_code == 1 and not req.called
611
+ assert (tmp_path / "multicloud.auto.tfvars").read_text() == "keep\n"
612
+
613
+
614
+ def test_create_new_account_with_account_is_a_usage_error(tmp_path, monkeypatch):
615
+ monkeypatch.chdir(tmp_path)
616
+ r, req = _create_a(["--cloud", "AWS", "--account", ACCT, "--new-account-email", EMAIL], monkeypatch=monkeypatch)
617
+ assert r.exit_code == 2 and not req.called
618
+
619
+
620
+ def test_create_new_account_for_gce_or_bad_email_is_a_usage_error(tmp_path, monkeypatch):
621
+ monkeypatch.chdir(tmp_path)
622
+ r, req = _create_a(["--cloud", "GCE", "--new-account-email", EMAIL], monkeypatch=monkeypatch)
623
+ assert r.exit_code == 2 and not req.called
624
+ r, req = _create_a(["--cloud", "AWS", "--new-account-email", "nope"], monkeypatch=monkeypatch)
625
+ assert r.exit_code == 2 and not req.called
626
+
627
+
628
+ def test_create_new_account_email_retype_mismatch_is_refused(tmp_path, monkeypatch):
629
+ monkeypatch.chdir(tmp_path)
630
+ r, req = _create_a(["--cloud", "AWS", "--new-account-email", EMAIL], tty=True,
631
+ typed="aws+multicloud@exmaple.com\n", monkeypatch=monkeypatch)
632
+ assert r.exit_code == 1 and not req.called
633
+ assert "different" in r.stderr
634
+ assert not (tmp_path / "multicloud.tf").exists()
635
+
636
+
637
+ def test_create_new_account_email_retype_match_works(tmp_path, monkeypatch):
638
+ monkeypatch.chdir(tmp_path)
639
+ r, req = _create_a(["--cloud", "AWS", "--new-account-email", EMAIL, "--opt-in-regions"], tty=True,
640
+ typed=EMAIL + "\n", monkeypatch=monkeypatch)
641
+ assert r.exit_code == 0, r.output
642
+ assert (tmp_path / "multicloud.auto.tfvars").exists()
643
+
644
+
645
+ def test_create_aws_without_account_is_allowed(tmp_path, monkeypatch):
646
+ monkeypatch.chdir(tmp_path)
647
+ r, req = _create_a(["--cloud", "AWS"], monkeypatch=monkeypatch)
648
+ assert r.exit_code == 0, r.output
649
+ sent = req.call_args.kwargs["json"]
650
+ assert "expected_native_id" not in sent and "new_account" not in sent
651
+ assert "account ID is read when the module connects" in r.stdout
652
+ assert "new AWS account made for Multicloud" in r.stdout
653
+ assert not (tmp_path / "multicloud.auto.tfvars").exists()
654
+
655
+
656
+ def test_hcl_string_escapes():
657
+ assert cmds._hcl_string('a"b\\c${x}') == '"a\\"b\\\\c$${x}"'
658
+
659
+
660
+ class Tool:
661
+ """subprocess.run replacement: records (args, env) and answers by the tool arguments."""
662
+
663
+ def __init__(self, state_list="", outputs=None, fail=(), aws=None, destroy_code=0):
664
+ self.calls, self.state_list, self.fail = [], state_list, set(fail)
665
+ self.outputs = outputs if outputs is not None else {"multicloud_account_id": {"value": "999999999999"}}
666
+ self.aws, self.destroy_code = aws, destroy_code
667
+
668
+ def __call__(self, cmd, **kw):
669
+ args = cmd[1:]
670
+ self.calls.append((cmd[0], list(args), kw.get("env")))
671
+ out, code = "", 0
672
+ if cmd[0] == "aws":
673
+ return MagicMock(returncode=0, stdout=self.aws or "", stderr="")
674
+ if args[:2] == ["state", "list"]:
675
+ out = self.state_list
676
+ elif args[:1] == ["output"]:
677
+ out = json.dumps(self.outputs)
678
+ elif args[:1] == ["destroy"]:
679
+ code = self.destroy_code
680
+ if args[0] in self.fail:
681
+ code = 1
682
+ return MagicMock(returncode=code, stdout=out, stderr="")
683
+
684
+ def seq(self):
685
+ return [" ".join(a[:3]) for _, a, _ in self.calls]
686
+
687
+
688
+ def _run_cmd(args, tool, tmp_path, monkeypatch, tty=False, tf=PATH_A_TF, answers=None, aws=True):
689
+ (tmp_path / "multicloud.tf").write_text(tf)
690
+ monkeypatch.setenv("MULTICLOUD_API_KEY", "fake-key-0000")
691
+ monkeypatch.setenv("MULTICLOUD_ORG", "acme")
692
+ monkeypatch.setenv("TF_LOG", "DEBUG")
693
+ monkeypatch.setattr(cmds, "_stdin_is_tty", lambda: tty)
694
+ monkeypatch.setattr(cmds, "_sleep", lambda s: None)
695
+ fake = sequence(*(answers or [reply(200, {"connect_token": TOKEN}), reply(200, VERIFIED)]))
696
+ monkeypatch.setattr(cmds.requests, "request", fake)
697
+ monkeypatch.setattr(cmds.shutil, "which", lambda n: f"/bin/{n}" if (aws or n != "aws") else None)
698
+ monkeypatch.setattr(cmds.subprocess, "run", tool)
699
+ r = _runner().invoke(mctl, ["cloud-account", *args, "--dir", str(tmp_path)])
700
+ return r, fake
701
+
702
+
703
+ def _tool_calls(tool):
704
+ return [(c[1], c[2]) for c in tool.calls if c[0] != "aws"]
705
+
706
+
707
+ def test_apply_path_a_runs_stage_1_then_the_full_apply(tmp_path, monkeypatch):
708
+ tool = Tool()
709
+ r, fake = _run_cmd(["apply", "5", "--yes"], tool, tmp_path, monkeypatch)
710
+ assert r.exit_code == 0, r.output + r.stderr
711
+ assert tool.seq() == ["init -input=false", "state list", "plan -input=false -target=module.multicloud_account",
712
+ "apply -input=false -auto-approve", "plan -input=false", "apply -input=false -auto-approve"]
713
+ calls = _tool_calls(tool)
714
+ stage1_plan, stage1_apply, plan, apply_ = calls[2], calls[3], calls[4], calls[5]
715
+ assert stage1_apply[0][-1] == "-target=module.multicloud_account"
716
+ for _, env in (stage1_plan, stage1_apply, plan):
717
+ assert env[cmds.TOKEN_ENV] == cmds.PLAN_PLACEHOLDER
718
+ for _, env in calls:
719
+ assert "MULTICLOUD_API_KEY" not in env and "TF_LOG" not in env
720
+ assert apply_[1][cmds.TOKEN_ENV] == TOKEN and apply_[0] == ["apply", "-input=false", "-auto-approve"]
721
+ assert [c for c in fake.calls if "connect-token" in c[1]]
722
+ assert all(TOKEN not in str(a) for a, _ in calls)
723
+ assert TOKEN not in r.stdout + r.stderr
724
+
725
+
726
+ def test_apply_path_a_asks_once_with_the_aws_wording(tmp_path, monkeypatch):
727
+ tool = Tool()
728
+ r, _ = _run_cmd(["apply", "5"], tool, tmp_path, monkeypatch, tty=True)
729
+ r2 = _runner().invoke(mctl, ["cloud-account", "apply", "5", "--dir", str(tmp_path)], input="n\n")
730
+ assert r2.exit_code == 1
731
+ assert "Create a new AWS account for Multicloud in your AWS Organizations, then connect it?" in r2.stdout + r2.stderr
732
+ assert not [c for c in _tool_calls(tool) if c[0][:1] == ["apply"]]
733
+
734
+
735
+ def test_apply_path_a_confirmed_asks_only_once(tmp_path, monkeypatch):
736
+ tool = Tool()
737
+ (tmp_path / "multicloud.tf").write_text(PATH_A_TF)
738
+ r, _ = _run_cmd(["apply", "5"], tool, tmp_path, monkeypatch, tty=True)
739
+ assert r.exit_code == 1 # no input: the question is declined
740
+ tool2 = Tool()
741
+ monkeypatch.setattr(cmds.subprocess, "run", tool2)
742
+ r = _runner().invoke(mctl, ["cloud-account", "apply", "5", "--dir", str(tmp_path)], input="y\n")
743
+ assert r.exit_code == 0, r.output + r.stderr
744
+ assert len([c for c in _tool_calls(tool2) if c[0][:1] == ["apply"]]) == 2
745
+
746
+
747
+ def test_apply_path_a_without_a_terminal_needs_yes(tmp_path, monkeypatch):
748
+ tool = Tool()
749
+ r, _ = _run_cmd(["apply", "5"], tool, tmp_path, monkeypatch)
750
+ assert r.exit_code == 1 and "--yes" in r.stderr
751
+ assert not [c for c in _tool_calls(tool) if c[0][:1] == ["apply"]]
752
+
753
+
754
+ def test_apply_path_a_skips_stage_1_when_the_account_exists(tmp_path, monkeypatch):
755
+ tool = Tool(state_list="module.multicloud_account.aws_organizations_account.this\n")
756
+ r, _ = _run_cmd(["apply", "5", "--yes"], tool, tmp_path, monkeypatch)
757
+ assert r.exit_code == 0, r.output + r.stderr
758
+ assert tool.seq() == ["init -input=false", "state list", "plan -input=false", "apply -input=false -auto-approve"]
759
+
760
+
761
+ def test_apply_path_a_stops_when_the_state_cannot_be_read(tmp_path, monkeypatch):
762
+ # A lock or backend error must not read as "no account yet": that would create a second AWS account.
763
+ tool = Tool(state_list="Error acquiring the state lock\n")
764
+ tool.fail = ["state"]
765
+ r, _ = _run_cmd(["apply", "5", "--yes"], tool, tmp_path, monkeypatch)
766
+ assert r.exit_code == 1 and "state list failed" in r.stderr
767
+ assert tool.seq() == ["init -input=false", "state list"]
768
+
769
+
770
+ def test_apply_path_a_plan_only_shows_the_stage_1_plan(tmp_path, monkeypatch):
771
+ tool = Tool()
772
+ r, fake = _run_cmd(["apply", "5", "--plan-only"], tool, tmp_path, monkeypatch)
773
+ assert r.exit_code == 0
774
+ assert tool.seq() == ["init -input=false", "state list", "plan -input=false -target=module.multicloud_account"]
775
+ assert "only after the new AWS account exists" in r.stdout
776
+ assert not fake.calls
777
+
778
+
779
+ def test_destroy_removes_the_role_from_state_then_destroys(tmp_path, monkeypatch):
780
+ tool = Tool()
781
+ r, _ = _run_cmd(["destroy", "5", "--yes"], tool, tmp_path, monkeypatch)
782
+ assert r.exit_code == 0, r.output + r.stderr
783
+ assert tool.seq() == ["output -json", "state rm module.multicloud", "destroy -input=false -auto-approve"]
784
+ assert _tool_calls(tool)[2][1][cmds.TOKEN_ENV] == cmds.PLAN_PLACEHOLDER
785
+
786
+
787
+ def test_destroy_asks_and_names_the_account(tmp_path, monkeypatch):
788
+ tool = Tool()
789
+ r, _ = _run_cmd(["destroy", "5"], tool, tmp_path, monkeypatch) # no terminal
790
+ assert r.exit_code == 1 and "--yes" in r.stderr
791
+ assert tool.seq() == ["output -json"]
792
+ r = _runner().invoke(mctl, ["cloud-account", "destroy", "5", "--dir", str(tmp_path)], input="n\n")
793
+ monkeypatch.setattr(cmds, "_stdin_is_tty", lambda: True)
794
+ r = _runner().invoke(mctl, ["cloud-account", "destroy", "5", "--dir", str(tmp_path)], input="n\n")
795
+ assert r.exit_code == 1
796
+ assert "999999999999" in r.stdout and "90 days" in r.stdout and "cannot be used again" in r.stdout
797
+ assert "state rm module.multicloud" not in tool.seq()
798
+
799
+
800
+ def test_destroy_timeout_with_a_closed_account_removes_the_account_from_state(tmp_path, monkeypatch):
801
+ tool = Tool(destroy_code=1, aws="CLOSED\n")
802
+ r, _ = _run_cmd(["destroy", "5", "--yes"], tool, tmp_path, monkeypatch)
803
+ assert r.exit_code == 0, r.output + r.stderr
804
+ assert "AWS closed the account; Terraform stopped waiting before AWS reported it. Nothing is broken." in r.stdout
805
+ assert tool.calls[-1][1] == ["state", "rm", "module.multicloud_account"]
806
+ aws = [c for c in tool.calls if c[0] == "aws"][0]
807
+ assert "999999999999" in aws[1] and "Account.State" in aws[1]
808
+
809
+
810
+ @pytest.mark.parametrize("aws,has_cli", [("ACTIVE\n", True), (None, False)])
811
+ def test_destroy_failure_without_a_closed_account_prints_the_by_hand_text(tmp_path, monkeypatch, aws, has_cli):
812
+ tool = Tool(destroy_code=1, aws=aws)
813
+ r, _ = _run_cmd(["destroy", "5", "--yes"], tool, tmp_path, monkeypatch, aws=has_cli)
814
+ assert r.exit_code == 1
815
+ assert ("When the AWS console shows the account as Closed, run: tofu state rm module.multicloud_account"
816
+ in r.stderr)
817
+ assert ["state", "rm", "module.multicloud_account"] not in [c[1] for c in tool.calls]
818
+
819
+
820
+ def test_destroy_for_another_file_runs_nothing(tmp_path, monkeypatch):
821
+ tool = Tool()
822
+ r, _ = _run_cmd(["destroy", "5", "--yes"], tool, tmp_path, monkeypatch, tf='module "multicloud" {\n}\n')
823
+ assert r.exit_code == 0
824
+ assert not tool.calls
825
+ assert "tofu destroy" in r.stdout and "AWS console" in r.stdout
826
+
827
+
828
+ def test_destroy_for_another_cloud_account_is_refused(tmp_path, monkeypatch):
829
+ tool = Tool()
830
+ r, _ = _run_cmd(["destroy", "6", "--yes"], tool, tmp_path, monkeypatch)
831
+ assert r.exit_code == 1 and not tool.calls
@@ -1 +0,0 @@
1
- __version__ = "0.4.1"
File without changes