multicloud-cli 0.7.1__tar.gz → 0.9.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 (43) hide show
  1. {multicloud_cli-0.7.1 → multicloud_cli-0.9.0}/PKG-INFO +3 -1
  2. {multicloud_cli-0.7.1 → multicloud_cli-0.9.0}/README.md +2 -0
  3. multicloud_cli-0.9.0/multicloud_cli/__init__.py +1 -0
  4. {multicloud_cli-0.7.1 → multicloud_cli-0.9.0}/multicloud_cli/cloud_account.py +232 -63
  5. {multicloud_cli-0.7.1 → multicloud_cli-0.9.0}/multicloud_cli/main.py +11 -1
  6. multicloud_cli-0.9.0/multicloud_cli/net.py +55 -0
  7. multicloud_cli-0.9.0/multicloud_cli/version_check.py +101 -0
  8. {multicloud_cli-0.7.1 → multicloud_cli-0.9.0}/tests/conftest.py +2 -0
  9. {multicloud_cli-0.7.1 → multicloud_cli-0.9.0}/tests/test_apply.py +12 -0
  10. {multicloud_cli-0.7.1 → multicloud_cli-0.9.0}/tests/test_cloud_account.py +245 -21
  11. multicloud_cli-0.9.0/tests/test_version_check.py +232 -0
  12. multicloud_cli-0.7.1/multicloud_cli/__init__.py +0 -1
  13. multicloud_cli-0.7.1/multicloud_cli/net.py +0 -30
  14. {multicloud_cli-0.7.1 → multicloud_cli-0.9.0}/.gitignore +0 -0
  15. {multicloud_cli-0.7.1 → multicloud_cli-0.9.0}/LICENSE +0 -0
  16. {multicloud_cli-0.7.1 → multicloud_cli-0.9.0}/multicloud_cli/account.py +0 -0
  17. {multicloud_cli-0.7.1 → multicloud_cli-0.9.0}/multicloud_cli/api.py +0 -0
  18. {multicloud_cli-0.7.1 → multicloud_cli-0.9.0}/multicloud_cli/auth.py +0 -0
  19. {multicloud_cli-0.7.1 → multicloud_cli-0.9.0}/multicloud_cli/catalog.py +0 -0
  20. {multicloud_cli-0.7.1 → multicloud_cli-0.9.0}/multicloud_cli/config.py +0 -0
  21. {multicloud_cli-0.7.1 → multicloud_cli-0.9.0}/multicloud_cli/duration.py +0 -0
  22. {multicloud_cli-0.7.1 → multicloud_cli-0.9.0}/multicloud_cli/exitcodes.py +0 -0
  23. {multicloud_cli-0.7.1 → multicloud_cli-0.9.0}/multicloud_cli/extend.py +0 -0
  24. {multicloud_cli-0.7.1 → multicloud_cli-0.9.0}/multicloud_cli/node.py +0 -0
  25. {multicloud_cli-0.7.1 → multicloud_cli-0.9.0}/multicloud_cli/orgopt.py +0 -0
  26. {multicloud_cli-0.7.1 → multicloud_cli-0.9.0}/multicloud_cli/output.py +0 -0
  27. {multicloud_cli-0.7.1 → multicloud_cli-0.9.0}/multicloud_cli/pool.py +0 -0
  28. {multicloud_cli-0.7.1 → multicloud_cli-0.9.0}/multicloud_cli/ssh.py +0 -0
  29. {multicloud_cli-0.7.1 → multicloud_cli-0.9.0}/multicloud_cli/ssh_cert.py +0 -0
  30. {multicloud_cli-0.7.1 → multicloud_cli-0.9.0}/multicloud_cli/sso.py +0 -0
  31. {multicloud_cli-0.7.1 → multicloud_cli-0.9.0}/pyproject.toml +0 -0
  32. {multicloud_cli-0.7.1 → multicloud_cli-0.9.0}/tests/__init__.py +0 -0
  33. {multicloud_cli-0.7.1 → multicloud_cli-0.9.0}/tests/helpers.py +0 -0
  34. {multicloud_cli-0.7.1 → multicloud_cli-0.9.0}/tests/test_account_extend.py +0 -0
  35. {multicloud_cli-0.7.1 → multicloud_cli-0.9.0}/tests/test_auth.py +0 -0
  36. {multicloud_cli-0.7.1 → multicloud_cli-0.9.0}/tests/test_catalog.py +0 -0
  37. {multicloud_cli-0.7.1 → multicloud_cli-0.9.0}/tests/test_conventions.py +0 -0
  38. {multicloud_cli-0.7.1 → multicloud_cli-0.9.0}/tests/test_net.py +0 -0
  39. {multicloud_cli-0.7.1 → multicloud_cli-0.9.0}/tests/test_pool.py +0 -0
  40. {multicloud_cli-0.7.1 → multicloud_cli-0.9.0}/tests/test_ssh.py +0 -0
  41. {multicloud_cli-0.7.1 → multicloud_cli-0.9.0}/tests/test_ssh_cert.py +0 -0
  42. {multicloud_cli-0.7.1 → multicloud_cli-0.9.0}/tests/test_sso.py +0 -0
  43. {multicloud_cli-0.7.1 → multicloud_cli-0.9.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.7.1
3
+ Version: 0.9.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>
@@ -44,6 +44,8 @@ pipx install multicloud-cli # or: uv tool install multicloud-cli
44
44
 
45
45
  If `mctl` is not found after the install, run `uv tool update-shell` (or `pipx ensurepath`) and open a new shell.
46
46
  Upgrade with `uv tool upgrade multicloud-cli` (or `pipx upgrade multicloud-cli`). Check the version with `mctl --version`.
47
+ Once a day, `mctl` asks PyPI for the latest version and prints one line when a newer version exists. It never
48
+ upgrades itself. Turn the check off with `MCTL_NO_UPDATE_CHECK=1`.
47
49
 
48
50
  ## Connect an AWS account
49
51
 
@@ -13,6 +13,8 @@ pipx install multicloud-cli # or: uv tool install multicloud-cli
13
13
 
14
14
  If `mctl` is not found after the install, run `uv tool update-shell` (or `pipx ensurepath`) and open a new shell.
15
15
  Upgrade with `uv tool upgrade multicloud-cli` (or `pipx upgrade multicloud-cli`). Check the version with `mctl --version`.
16
+ Once a day, `mctl` asks PyPI for the latest version and prints one line when a newer version exists. It never
17
+ upgrades itself. Turn the check off with `MCTL_NO_UPDATE_CHECK=1`.
16
18
 
17
19
  ## Connect an AWS account
18
20
 
@@ -0,0 +1 @@
1
+ __version__ = "0.9.0"
@@ -1,4 +1,4 @@
1
- """``mctl cloud-account``: connect an AWS account or GCP project to an organization.
1
+ """``mctl cloud-account``: connect an AWS account, GCP project or Azure subscription to an organization.
2
2
 
3
3
  These commands call the Multicloud API (``/api/v1/orgs/{slug}/cloud-accounts``) with an API key that
4
4
  holds the ``infra`` scope. The key comes from
@@ -33,6 +33,34 @@ ACCOUNT_MODULE = "module.multicloud_account"
33
33
  ACCOUNT_RESOURCE = ACCOUNT_MODULE + ".aws_organizations_account.this"
34
34
  _PATH_A = re.compile(r'^\s*module\s+"multicloud_account"\s*\{', re.M)
35
35
  _EMAIL = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")
36
+ _GUID = re.compile(r"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$")
37
+ _AZURE_LOCATION = re.compile(r"^[a-z][a-z0-9]{2,29}$") # the API's rule for an Azure location name
38
+ _LOCATION_LINE = re.compile(r'^(\s*location\s*=\s*)"[^"\n]*"', re.M)
39
+ #: The API snippet has no provider block, and azurerm needs one (features {}, the subscription).
40
+ #: Same as deploy/customer-terraform/examples/azure/main.tf.
41
+ AZURE_HEADER = """terraform {{
42
+ required_version = ">= 1.6.0"
43
+
44
+ required_providers {{
45
+ azurerm = {{
46
+ source = "hashicorp/azurerm"
47
+ version = ">= 5.0"
48
+ }}
49
+ }}
50
+ }}
51
+
52
+ # Sign in with the Azure CLI (az login) as an Owner of the subscription (or User Access
53
+ # Administrator plus Contributor).
54
+ provider "azurerm" {{
55
+ features {{}}
56
+
57
+ subscription_id = "{subscription}"
58
+
59
+ # The module registers the resource providers that it needs.
60
+ resource_provider_registrations = "none"
61
+ }}
62
+
63
+ """
36
64
  PLAN_PLACEHOLDER = "plan-placeholder"
37
65
  _sleep = time.sleep # tests patch this name
38
66
 
@@ -180,8 +208,9 @@ def opt_in_lines(block: Optional[Dict[str, Any]], account_id: Any = None) -> lis
180
208
 
181
209
  def terraform_outputs() -> Dict[str, Any]:
182
210
  """The connect body from ``tofu output -json`` in the cwd (``terraform`` when ``tofu`` is not on
183
- the PATH, as for ``apply``): ``role_arn`` (AWS) or ``wif_provider`` and ``service_account_email``
184
- (GCE), plus ``policy_version`` and ``module_version``."""
211
+ the PATH, as for ``apply``): ``role_arn`` (AWS), ``wif_provider`` and ``service_account_email``
212
+ (GCE), or ``tenant_id``, ``client_id`` and ``uami_resource_id`` (Azure), plus ``policy_version`` and
213
+ ``module_version``."""
185
214
  try:
186
215
  tool = next((t for t in ("tofu", "terraform") if shutil.which(t)), None) # the order of apply
187
216
  if tool is None:
@@ -191,7 +220,12 @@ def terraform_outputs() -> Dict[str, Any]:
191
220
  except (OSError, subprocess.CalledProcessError, ValueError) as ex:
192
221
  raise CloudAccountError(f"Could not read 'terraform output -json' in this directory: {ex}")
193
222
  values = {}
194
- names = ("wif_provider", "service_account_email") if "wif_provider" in outputs else ("role_arn",)
223
+ if "uami_resource_id" in outputs:
224
+ names = ("tenant_id", "client_id", "uami_resource_id")
225
+ elif "wif_provider" in outputs:
226
+ names = ("wif_provider", "service_account_email")
227
+ else:
228
+ names = ("role_arn",)
195
229
  for name in names + ("policy_version", "module_version"):
196
230
  item = outputs.get(name)
197
231
  if not isinstance(item, dict) or item.get("value") in (None, ""):
@@ -247,7 +281,7 @@ def _tf_file_exists():
247
281
  @org_option()
248
282
  @click.pass_context
249
283
  def cloud_account(ctx, org):
250
- """Connect a customer AWS account or GCP project (sign in first: mctl auth login)."""
284
+ """Connect a customer AWS account, GCP project or Azure subscription (sign in first: mctl auth login)."""
251
285
  ctx.ensure_object(dict)
252
286
  ctx.obj["cloud_account_org"] = org
253
287
 
@@ -269,9 +303,12 @@ def _file_exists(name: str):
269
303
 
270
304
 
271
305
  @cloud_account.command()
272
- @click.option("--cloud", required=True, type=click.Choice(["AWS", "GCE"], case_sensitive=False),
273
- help="AWS or GCE (Google Cloud). Azure: not available in mctl yet")
274
- @click.option("--account", help="AWS: pin the 12-digit AWS account id (optional; not allowed for GCE)")
306
+ @click.option("--cloud", required=True, type=click.Choice(["AWS", "GCE", "AZURE"], case_sensitive=False),
307
+ help="AWS, GCE (Google Cloud) or AZURE")
308
+ @click.option("--account", help="AWS: pin the 12-digit AWS account id (optional). AZURE: the subscription id, "
309
+ "a GUID (required). Not allowed for GCE")
310
+ @click.option("--location", help="AZURE: the Azure location of the Multicloud identity, for example "
311
+ "westeurope (required; Azure only)")
275
312
  @click.option("--new-account-email", "new_email", metavar="EMAIL",
276
313
  help="AWS: create a new AWS account for Multicloud in your AWS Organizations, with this email "
277
314
  "(not allowed with --account)")
@@ -281,11 +318,11 @@ def _file_exists(name: str):
281
318
  help="AWS: turn on the opt-in regions of the account that are off (default: yes; "
282
319
  "asks when stdin is a terminal)")
283
320
  @click.option("--allow-quota-requests/--no-allow-quota-requests", "allow_quota", default=None,
284
- help="AWS: allow Multicloud to request higher quotas in this account (default: no; asks when "
285
- "stdin is a terminal). Needs an organization owner's sign-in")
321
+ help="AWS and AZURE: allow Multicloud to request higher quotas in this account (default: no; "
322
+ "asks when stdin is a terminal). Needs an organization owner's sign-in")
286
323
  @json_option
287
324
  @click.pass_context
288
- def create(ctx, cloud, account, new_email, regions, force, opt_in, allow_quota, as_json):
325
+ def create(ctx, cloud, account, location, new_email, regions, force, opt_in, allow_quota, as_json):
289
326
  """Register an account and write multicloud.tf. No token is printed.
290
327
 
291
328
  An existing multicloud.tf is kept: a new external id in it would cut off a connected account.
@@ -298,10 +335,32 @@ def create(ctx, cloud, account, new_email, regions, force, opt_in, allow_quota,
298
335
  turns them on (only the --region ones when you give --region). That takes minutes to hours; verify
299
336
  again to add them.
300
337
 
338
+ Azure: give the subscription id (--account) and the location of the Multicloud identity (--location).
339
+ --region stays the list of locations Multicloud may use. Run apply after 'az login' as an Owner of the
340
+ subscription.
341
+
301
342
  Quota requests: Multicloud files a quota increase request in the account only when you allow it
302
343
  (--allow-quota-requests, or 'y' at the question). Without it, verify only reads the quotas and tells
303
344
  you what to request. Change it later with allow-quota-requests or revoke-quota-requests."""
304
- gce = cloud.upper() == "GCE"
345
+ cloud = cloud.upper()
346
+ gce, azure = cloud == "GCE", cloud == "AZURE"
347
+ if location and not azure:
348
+ raise click.UsageError("--location applies to Azure only.")
349
+ if azure:
350
+ if new_email:
351
+ raise click.UsageError("--new-account-email applies to AWS only.")
352
+ if opt_in is not None:
353
+ raise click.UsageError("--opt-in-regions applies to AWS only.")
354
+ if not account:
355
+ raise click.UsageError("Azure needs --account: the subscription id (a GUID).")
356
+ if not _GUID.match(account.strip()):
357
+ raise click.UsageError(f"'{account}' is not an Azure subscription id (a GUID).")
358
+ if not location:
359
+ raise click.UsageError("Azure needs --location: the Azure location of the Multicloud identity, "
360
+ "for example westeurope.")
361
+ if not _AZURE_LOCATION.match(location):
362
+ raise click.UsageError(f"'{location}' is not an Azure location name such as westeurope.")
363
+ account = account.strip().lower() # Azure reports GUIDs in lower case
305
364
  if gce and account:
306
365
  raise click.UsageError("--account is not allowed for GCE: Multicloud generates the project id.")
307
366
  if gce and new_email:
@@ -312,8 +371,8 @@ def create(ctx, cloud, account, new_email, regions, force, opt_in, allow_quota,
312
371
  if gce and opt_in is not None:
313
372
  raise click.UsageError("--opt-in-regions applies to AWS only.")
314
373
  if gce and allow_quota is not None:
315
- raise click.UsageError("--allow-quota-requests applies to AWS only: Multicloud files no GCP quota "
316
- "request.")
374
+ raise click.UsageError("--allow-quota-requests applies to AWS and Azure only: Multicloud files no GCP "
375
+ "quota request.")
317
376
  if new_email:
318
377
  new_email = new_email.strip()
319
378
  if not _EMAIL.match(new_email):
@@ -329,8 +388,10 @@ def create(ctx, cloud, account, new_email, regions, force, opt_in, allow_quota,
329
388
  _tf_file_exists()
330
389
  if new_email and Path(TFVARS_FILE).exists() and not force:
331
390
  _file_exists(TFVARS_FILE)
332
- body = {"cloud": cloud.upper()}
333
- if not gce:
391
+ body = {"cloud": cloud}
392
+ if azure:
393
+ body["expected_native_id"] = account
394
+ elif not gce:
334
395
  if account:
335
396
  body["expected_native_id"] = account
336
397
  if new_email:
@@ -340,19 +401,18 @@ def create(ctx, cloud, account, new_email, regions, force, opt_in, allow_quota,
340
401
  if _stdin_is_tty() else True)
341
402
  body["enable_opt_in_regions"] = bool(opt_in)
342
403
  if allow_quota is None:
343
- if _stdin_is_tty():
344
- click.echo("Multicloud can request higher spot quotas in this account (AWS Service Quotas) when "
345
- "they are too low for your pools. Without it, Multicloud only reads the quotas and "
346
- "tells you what to request.", err=True)
347
- allow_quota = click.confirm(QUOTA_QUESTION, default=False, err=True)
348
- else:
349
- allow_quota = False
404
+ allow_quota = _ask_quota(cloud)
405
+ if azure and allow_quota is None:
406
+ allow_quota = _ask_quota(cloud)
350
407
  if regions:
351
408
  body["regions"] = list(regions)
352
409
  made = _run(ctx, lambda org: call("POST", org, body=body))
410
+ terraform = made["terraform"]
411
+ if azure:
412
+ terraform = azure_file(terraform, made["account"].get("expected_native_id") or account, location)
353
413
  try:
354
414
  with open(TF_FILE, "w" if force else "x") as f:
355
- f.write(made["terraform"])
415
+ f.write(terraform)
356
416
  except FileExistsError: # created after the check above
357
417
  _tf_file_exists()
358
418
  if new_email:
@@ -370,6 +430,8 @@ def create(ctx, cloud, account, new_email, regions, force, opt_in, allow_quota,
370
430
  _dump(shown)
371
431
  if gce:
372
432
  target = f"GCP project {made['account'].get('expected_native_id')}"
433
+ elif azure:
434
+ target = f"Azure subscription {made['account'].get('expected_native_id') or account}"
373
435
  elif account:
374
436
  target = f"AWS account {account}"
375
437
  elif new_email:
@@ -384,12 +446,38 @@ def create(ctx, cloud, account, new_email, regions, force, opt_in, allow_quota,
384
446
  elif not gce and not account:
385
447
  say("The AWS account ID is read when the module connects. The account should be a new AWS account "
386
448
  "made for Multicloud.")
449
+ elif azure:
450
+ say(f"Sign in first with the Azure CLI: az login, as an Owner of the subscription. The Multicloud "
451
+ f"identity goes to {location}.")
387
452
  for line in consent_lines:
388
453
  say(line)
389
454
  say(f"Next: mctl cloud-account apply {acct_id}")
390
455
  say(f"By hand: mctl cloud-account token {acct_id}, then tofu apply (or terraform apply).")
391
456
 
392
457
 
458
+ def _ask_quota(cloud: str) -> bool:
459
+ """The quota question at a terminal; no without one."""
460
+ if not _stdin_is_tty():
461
+ return False
462
+ service = "Azure Microsoft.Quota" if cloud == "AZURE" else "AWS Service Quotas"
463
+ click.echo(f"Multicloud can request higher spot quotas in this account ({service}) when they are too low "
464
+ "for your pools. Without it, Multicloud only reads the quotas and tells you what to request.",
465
+ err=True)
466
+ return click.confirm(QUOTA_QUESTION, default=False, err=True)
467
+
468
+
469
+ def azure_file(snippet: str, subscription: str, location: str) -> str:
470
+ """The Azure snippet as a file Terraform can run: the provider block first (when the API wrote none),
471
+ and the location of the identity in place of the API's placeholder or ``regions[0]``."""
472
+ text, found = _LOCATION_LINE.subn(lambda m: m.group(1) + _hcl_string(location), snippet, count=1)
473
+ if not found:
474
+ click.echo(f"Warning: {TF_FILE} has no location line, so --location {location} is not in it. "
475
+ f"Check the file before apply.", err=True)
476
+ if not re.search(r'^\s*(provider\s+"azurerm"|required_providers\b)', text, re.M):
477
+ text = AZURE_HEADER.format(subscription=subscription) + text
478
+ return text
479
+
480
+
393
481
  def _create_quota_consent(ctx, acct_id, allow: bool, say) -> Optional[Dict[str, Any]]:
394
482
  """After create: allow quota requests when asked to. Returns the account the allow call answered, else None.
395
483
  A refusal (no owner sign-in) keeps the account and says so on stderr."""
@@ -452,6 +540,9 @@ def _readable(data: Dict[str, Any]) -> str:
452
540
  ("Role", data.get("role_arn")),
453
541
  ("Workload identity provider", data.get("wif_provider")),
454
542
  ("Service account", data.get("service_account_email")),
543
+ ("Tenant", data.get("tenant_id")),
544
+ ("Managed identity client ID", data.get("client_id")),
545
+ ("Managed identity", data.get("uami_resource_id")),
455
546
  ("Policy version", data.get("policy_version")),
456
547
  ("Module version", data.get("module_version")),
457
548
  ("Connected", data.get("connected_on")),
@@ -551,7 +642,7 @@ def _verify_loop(org, account_id: int, wait: bool, timeout: int, interval: int,
551
642
  if as_json:
552
643
  _dump(data)
553
644
  native = data.get("native_id") or data.get("expected_native_id")
554
- say(f"Ready: {data.get('cloud', 'AWS')} account {native} is connected "
645
+ say(f"Ready: {noun_of(data.get('cloud') or 'AWS')} {native} is connected "
555
646
  f"(policy version {data.get('policy_version')}).")
556
647
  for line in quota_lines(data.get("quota")):
557
648
  say(line)
@@ -561,9 +652,10 @@ def _verify_loop(org, account_id: int, wait: bool, timeout: int, interval: int,
561
652
  say("quota WAIT AWS may still apply an IAM change. Wait a few minutes, then run: "
562
653
  f"mctl cloud-account verify {account_id}")
563
654
  return exitcodes.OK
564
- note(f"Pending: the role is not usable yet ({data.get('status_reason') or 'no reason given'}). "
565
- f"{'Google Cloud can take some minutes' if data.get('cloud') == 'GCE' else 'AWS can take up to 15 minutes'} "
566
- f"to apply IAM changes.")
655
+ wait_text = {"GCE": "Google Cloud can take some minutes",
656
+ "AZURE": "Azure can take some minutes"}.get(data.get("cloud"), "AWS can take up to 15 minutes")
657
+ note(f"Pending: the {'identity' if data.get('cloud') == 'AZURE' else 'role'} is not usable yet "
658
+ f"({data.get('status_reason') or 'no reason given'}). {wait_text} to apply IAM changes.")
567
659
  if not wait or waited >= timeout:
568
660
  if as_json:
569
661
  _dump(data)
@@ -676,44 +768,89 @@ def revoke_quota_requests(ctx, account_id):
676
768
  f"filed stay open in the cloud.")
677
769
 
678
770
 
679
- IN_USE = "ACCOUNT_IN_USE"
771
+ WAIT_DEFAULT = "130m" # the cleanup job gives up after about two hours
772
+ WAIT_INTERVAL = 30
680
773
 
681
774
 
682
- def _disconnect(org, account_id: int, again: str = "disconnect") -> Dict[str, Any]:
683
- """``DELETE /cloud-accounts/{id}`` with the sign-in. Returns the account; raises ``CloudAccountError`` with
684
- calm text when a pool still uses it (nothing changed then)."""
775
+ def _disconnect(org, account_id: int) -> Dict[str, Any]:
776
+ """``DELETE /cloud-accounts/{id}`` with the sign-in. Returns the account view: ``revoked`` at once, or
777
+ ``revoking`` (202) while the cleanup runs. A repeated call on a ``revoking`` account answers 202 again."""
685
778
  try:
686
- answer = api.call("DELETE", org, f"/cloud-accounts/{account_id}", pass_codes=(IN_USE,), prefer_sso=True)
779
+ answer = api.call("DELETE", org, f"/cloud-accounts/{account_id}", prefer_sso=True)
687
780
  except api.ApiError as ex:
688
781
  raise CloudAccountError(str(ex), ex.exit_code)
689
- status = answer.pop("_status", 200)
690
- if status == 409:
691
- detail = answer.get("detail") or {}
692
- details = detail.get("details") or {}
693
- lines = [f"Cloud account {account_id} is still in use, so it stays connected. Nothing changed."]
694
- for name in details.get("pools") or []:
695
- lines.append(f" Pool {name}: delete it with 'mctl pool delete {name}'.")
696
- if details.get("other_organization_pools"):
697
- lines.append(f" {details['other_organization_pools']} pool(s) of other organizations use it: "
698
- "ask Multicloud support.")
699
- if details.get("live_servers"):
700
- lines.append(f" {details['live_servers']} server(s) still run in it. They stop a few minutes after "
701
- "their pool is deleted.")
702
- lines.append(f"Then run 'mctl cloud-account {again} {account_id}' again.")
703
- raise CloudAccountError("\n".join(lines), exitcodes.ERROR)
782
+ answer.pop("_status", None)
704
783
  return answer
705
784
 
706
785
 
786
+ def _step(view: Dict[str, Any]) -> str:
787
+ cleanup = view.get("cleanup") or {}
788
+ return str(cleanup.get("step") or "starting")
789
+
790
+
791
+ def _leftover_line(item: Dict[str, Any]) -> str:
792
+ kind = item.get("kind")
793
+ if kind == "server":
794
+ return f"server {item.get('cloud_id') or item.get('id')} in {item.get('region')}"
795
+ if kind == "bucket":
796
+ return f"bucket {item.get('name')}"
797
+ if kind == "network":
798
+ if item.get("unchecked"):
799
+ return f"network in {item.get('region')} (not checked: look for it yourself)"
800
+ return f"network in {item.get('region')}"
801
+ return json.dumps(item, sort_keys=True)
802
+
803
+
804
+ def _print_leftovers(view: Dict[str, Any]) -> None:
805
+ leftovers = (view.get("cleanup") or {}).get("leftovers")
806
+ if not leftovers:
807
+ click.echo("No leftovers: Multicloud removed everything it created in the account.")
808
+ return
809
+ click.echo(f"Leftovers: Multicloud could not remove {len(leftovers)} item(s) it created. Remove them by hand:")
810
+ for item in leftovers:
811
+ click.echo(f" {_leftover_line(item)}")
812
+
813
+
814
+ def _wait_revoked(org, account_id: int, view: Dict[str, Any], timeout: int,
815
+ interval: int = WAIT_INTERVAL) -> Optional[Dict[str, Any]]:
816
+ """Poll ``GET /cloud-accounts/{id}`` until the status is ``revoked``. Prints each step change. Returns the
817
+ final view, or None when ``timeout`` seconds pass first."""
818
+ waited, last = 0, None
819
+ while True:
820
+ if view.get("status") == "revoked":
821
+ return view
822
+ step = _step(view)
823
+ if step != last:
824
+ click.echo(f"Cleanup step: {step}")
825
+ last = step
826
+ if waited >= timeout:
827
+ return None
828
+ _sleep(interval)
829
+ waited += interval
830
+ view = call("GET", org, f"/{account_id}", prefer_sso=True)
831
+ view.pop("_status", None)
832
+
833
+
834
+ def _timeout_text(account_id: int, view: Dict[str, Any]) -> str:
835
+ return (f"Cloud account {account_id} is still revoking (step: {_step(view)}). "
836
+ f"Watch it with 'mctl cloud-account show {account_id}' or run 'mctl cloud-account disconnect "
837
+ f"{account_id} --wait' again.")
838
+
839
+
707
840
  @cloud_account.command()
708
841
  @click.argument("account_id", type=int)
709
842
  @click.option("-y", "--yes", is_flag=True, help="Disconnect without asking")
843
+ @click.option("--wait", is_flag=True, help="Wait until the cleanup is done and show what is left")
844
+ @click.option("-t", "--timeout", default=WAIT_DEFAULT, show_default=True, callback=duration_option,
845
+ help="How long to wait with --wait (90, 90s, 15m, 2h)")
710
846
  @click.pass_context
711
- def disconnect(ctx, account_id, yes):
847
+ def disconnect(ctx, account_id, yes, wait, timeout):
712
848
  """Disconnect a cloud account from the organization (organization owners only).
713
849
 
714
- Multicloud stops using the account at once. Nothing in the account is deleted: remove the Multicloud role
715
- afterwards with 'tofu destroy' (or 'mctl cloud-account destroy' for an AWS account that mctl created). A pool
716
- that uses the account must be deleted first. Needs a sign-in (mctl auth login), not an API key."""
850
+ Multicloud stops using the account at once. Then a cleanup job drains the servers, ends them and removes the
851
+ network and bucket that Multicloud created in the account (status revoking, then revoked). Use --wait to
852
+ follow it. Remove the Multicloud role afterwards with 'tofu destroy' (or 'mctl cloud-account destroy' for an
853
+ AWS account that mctl created). Needs a sign-in (mctl auth login), not an API key."""
717
854
  # The sign-in from the start: the API refuses an API key here, so fail before the prompt.
718
855
  data = _run(ctx, lambda org: call("GET", org, f"/{account_id}", prefer_sso=True))
719
856
  data.pop("_status", None)
@@ -732,10 +869,29 @@ def disconnect(ctx, account_id, yes):
732
869
  if not click.confirm(f"Disconnect {which}?", default=False):
733
870
  click.echo("Nothing changed.", err=True)
734
871
  sys.exit(exitcodes.ERROR)
735
- _run(ctx, lambda org: _disconnect(org, account_id))
736
- click.echo(f"Disconnected: {which} is no longer connected to Multicloud.")
872
+ view = _run(ctx, lambda org: _disconnect(org, account_id))
873
+ if view.get("status") == "revoked":
874
+ click.echo(f"Disconnected: {which} is no longer connected to Multicloud.")
875
+ else:
876
+ click.echo(f"Disconnected: Multicloud no longer uses {which}. The cleanup runs now "
877
+ f"(status {view.get('status') or 'revoking'}, step {_step(view)}).")
878
+ if not wait:
879
+ click.echo(f"Watch it with 'mctl cloud-account show {account_id}', or run "
880
+ f"'mctl cloud-account disconnect {account_id} --wait'.")
881
+ return
882
+ view = _run(ctx, lambda org: _wait_revoked(org, account_id, view, timeout))
883
+ if view is None:
884
+ click.echo("Timeout: the cleanup is not done yet. It keeps running.", err=True)
885
+ click.echo(f"Watch it with 'mctl cloud-account show {account_id}'.", err=True)
886
+ sys.exit(exitcodes.PENDING)
887
+ click.echo(f"Cloud account {account_id} is revoked.")
888
+ _print_leftovers(view)
737
889
  if not data.get("connected_on"):
738
890
  return # Terraform never connected it: there is no Multicloud role to remove
891
+ if data.get("cloud") == "AZURE":
892
+ click.echo("Next: remove the Multicloud managed identity and role from the subscription. Run 'tofu destroy' "
893
+ f"(or 'terraform destroy') in the folder with {TF_FILE}.")
894
+ return
739
895
  click.echo("Next: remove the Multicloud role from the account. Run 'tofu destroy' (or 'terraform destroy') in "
740
896
  f"the folder with {TF_FILE}, or 'mctl cloud-account destroy {account_id}' if mctl created the AWS account.")
741
897
 
@@ -802,13 +958,15 @@ def _aws_account_state(account_id: str) -> Optional[str]:
802
958
  @click.option("--dir", "directory", default=".", type=click.Path(file_okay=False), help="Folder with multicloud.tf")
803
959
  @click.option("--tool", type=click.Choice(["tofu", "terraform"]), default=None, help="Default: tofu, then terraform")
804
960
  @click.option("-y", "--yes", is_flag=True, help="Destroy without asking")
961
+ @click.option("-t", "--timeout", default=WAIT_DEFAULT, show_default=True, callback=duration_option,
962
+ help="How long to wait for the cleanup before the account closes (90, 90s, 15m, 2h)")
805
963
  @click.pass_context
806
- def destroy(ctx, account_id, directory, tool, yes):
964
+ def destroy(ctx, account_id, directory, tool, yes, timeout):
807
965
  """Disconnect the AWS account that multicloud.tf created, then close it.
808
966
 
809
967
  Only for a file made with 'create --new-account-email'. The account is disconnected from your organization
810
- first (organization owners only; needs mctl auth login), so a pool that still uses it stops the command before
811
- anything is closed. AWS keeps a closed account for 90 days, and its email cannot be used for a new AWS
968
+ first (organization owners only; needs mctl auth login). The command waits until Multicloud has cleaned up
969
+ the account (status revoked), and closes nothing if that takes longer than --timeout. AWS keeps a closed account for 90 days, and its email cannot be used for a new AWS
812
970
  account again."""
813
971
  text = _check_file(account_id, directory)
814
972
  if not _PATH_A.search(text):
@@ -837,10 +995,18 @@ def destroy(ctx, account_id, directory, tool, yes):
837
995
  if not click.confirm(f"Close {which}?", default=False):
838
996
  click.echo("Nothing destroyed.", err=True)
839
997
  sys.exit(exitcodes.ERROR)
840
- # Disconnect first: a closed account must not stay connected, and a pool that still uses it stops us here,
841
- # before anything is closed. An account that is already disconnected answers the same.
842
- _run(ctx, lambda org: _disconnect(org, account_id, again="destroy"))
998
+ # Disconnect first and wait for the cleanup (revoked): the tool must not run while Multicloud still works in
999
+ # the account. An account that is already disconnected answers the same.
1000
+ view = _run(ctx, lambda org: _disconnect(org, account_id))
843
1001
  click.echo(f"Disconnected cloud account {account_id} from your organization.")
1002
+ view = _run(ctx, lambda org: _wait_revoked(org, account_id, view, timeout))
1003
+ if view is None:
1004
+ click.echo(f"Error: the cleanup of cloud account {account_id} did not finish within the timeout. "
1005
+ f"Nothing was closed. Run 'mctl cloud-account destroy {account_id}' again.", err=True)
1006
+ sys.exit(exitcodes.PENDING)
1007
+ if (view.get("cleanup") or {}).get("leftovers"):
1008
+ _print_leftovers(view)
1009
+ click.echo("Closing the account removes these as well.")
844
1010
  # The account closes with everything in it. Deleting the Spot service-linked role can be blocked
845
1011
  # for about 4 minutes after the last spot instance ends, so the destroy must not depend on it.
846
1012
  code, out = _run(ctx, lambda org: _tool_capture(tool, ["state", "rm", "module.multicloud"], directory, base_env))
@@ -942,7 +1108,9 @@ def apply(ctx, account_id, directory, tool, plan_only, yes, timeout, interval):
942
1108
  click.echo("Error: Refusing to apply without confirmation. Review the plan, then run again "
943
1109
  "with --yes.", err=True)
944
1110
  sys.exit(1)
945
- target = "GCP project" if re.search(r"^\s*project_id\s*=", tf.read_text(), re.M) else "AWS account"
1111
+ text = tf.read_text()
1112
+ target = ("Azure subscription" if re.search(r"^\s*subscription_id\s*=", text, re.M)
1113
+ else "GCP project" if re.search(r"^\s*project_id\s*=", text, re.M) else "AWS account")
946
1114
  if not click.confirm(f"Apply this plan to your {target}?", default=False):
947
1115
  click.echo("Nothing applied.", err=True)
948
1116
  sys.exit(exitcodes.ERROR)
@@ -965,12 +1133,13 @@ def apply(ctx, account_id, directory, tool, plan_only, yes, timeout, interval):
965
1133
  @cloud_account.command()
966
1134
  @click.argument("account_id", type=int)
967
1135
  @click.option("--from-terraform-output", "from_tf", is_flag=True,
968
- help="Read the identity outputs (role_arn, or wif_provider and service_account_email), "
1136
+ help="Read the identity outputs (role_arn; wif_provider and service_account_email; or "
1137
+ "tenant_id, client_id and uami_resource_id), "
969
1138
  "policy_version and module_version from 'terraform output -json' "
970
1139
  "(the only input; this is the default)")
971
1140
  @click.pass_context
972
1141
  def connect(ctx, account_id, from_tf):
973
- """Report the role Terraform created. The token comes from TF_VAR_multicloud_connect_token."""
1142
+ """Report the identity Terraform created. The token comes from TF_VAR_multicloud_connect_token."""
974
1143
  token = os.environ.get(TOKEN_ENV)
975
1144
  if not token:
976
1145
  click.echo(f"Error: set {TOKEN_ENV} to a connect token: run 'mctl cloud-account token {account_id}'.", err=True)
@@ -4,7 +4,7 @@ import sys
4
4
 
5
5
  import click
6
6
 
7
- from . import __version__, exitcodes
7
+ from . import __version__, exitcodes, version_check
8
8
  from .account import billing, overview
9
9
  from .auth import auth
10
10
  from .catalog import catalog
@@ -88,8 +88,18 @@ def _run() -> int:
88
88
  return code if isinstance(code, int) else exitcodes.OK
89
89
 
90
90
 
91
+ def _version_notice() -> None:
92
+ """One line on stderr when PyPI has a newer mctl. It never fails or changes the exit code of a command."""
93
+ try:
94
+ version_check.notify()
95
+ except (Exception, KeyboardInterrupt): # a Ctrl-C during the lookup only drops the notice
96
+ pass
97
+
98
+
91
99
  def main():
92
100
  code = _run()
101
+ if code not in (exitcodes.INTERRUPTED, exitcodes.BROKEN_PIPE): # the user or the pipe wants mctl gone
102
+ _version_notice()
93
103
  try:
94
104
  sys.stdout.flush() # a closed pipe shows here, when the output was small and buffered
95
105
  except BrokenPipeError:
@@ -0,0 +1,55 @@
1
+ """Every HTTP request of ``mctl`` goes through ``request``, which adds ``User-Agent: mctl/<version>``.
2
+
3
+ An API with ``MULTICLOUD_MIN_MCTL_VERSION`` answers 426 to an older mctl; ``request`` turns that answer into
4
+ ``UpgradeRequired``, which ``main`` prints as ``Error: <message>`` with exit code 1."""
5
+ from typing import Any
6
+
7
+ import click
8
+ import requests
9
+ from requests.adapters import HTTPAdapter
10
+
11
+ from . import __version__, exitcodes
12
+
13
+ USER_AGENT = f"mctl/{__version__}"
14
+ UPGRADE = "uv tool upgrade multicloud-cli (or pipx upgrade multicloud-cli)"
15
+
16
+
17
+ class UpgradeRequired(click.ClickException):
18
+ """The API refused this mctl as too old (HTTP 426). The message is the API's own, which names the minimum
19
+ version and the upgrade command."""
20
+ exit_code = exitcodes.ERROR
21
+
22
+
23
+ def _upgrade_message(r: requests.Response) -> str:
24
+ try:
25
+ detail = r.json().get("detail")
26
+ except (ValueError, AttributeError):
27
+ detail = None
28
+ if isinstance(detail, dict) and isinstance(detail.get("message"), str) and detail["message"]:
29
+ return detail["message"]
30
+ return f"This mctl is too old for the API. Upgrade: {UPGRADE}"
31
+
32
+
33
+ class IPv4Adapter(HTTPAdapter):
34
+ """Connects over IPv4 only. Binding the local end to ``0.0.0.0`` makes urllib3 skip every IPv6 (AAAA) address:
35
+ its socket cannot bind there, so the next address is tried."""
36
+
37
+ def init_poolmanager(self, connections, maxsize, block=False, **pool_kwargs):
38
+ pool_kwargs["source_address"] = ("0.0.0.0", 0)
39
+ super().init_poolmanager(connections, maxsize, block, **pool_kwargs)
40
+
41
+
42
+ def request(method: str, url: str, ipv4_only: bool = False, **kw: Any) -> requests.Response:
43
+ """One request. ``ipv4_only`` connects over IPv4 only: the SSH grant routes read the address of the caller as
44
+ the API sees it, and ``api.multicloud.io`` has AAAA records."""
45
+ kw["headers"] = {"User-Agent": USER_AGENT, **(kw.get("headers") or {})}
46
+ if ipv4_only:
47
+ with requests.Session() as session:
48
+ session.mount("https://", IPv4Adapter())
49
+ session.mount("http://", IPv4Adapter())
50
+ r = session.request(method, url, **kw)
51
+ else:
52
+ r = requests.request(method, url, **kw)
53
+ if getattr(r, "status_code", None) == 426: # getattr: tests stub the response
54
+ raise UpgradeRequired(_upgrade_message(r))
55
+ return r