multicloud-cli 0.7.0__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.0 → multicloud_cli-0.9.0}/PKG-INFO +3 -1
  2. {multicloud_cli-0.7.0 → 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.0 → multicloud_cli-0.9.0}/multicloud_cli/cloud_account.py +255 -65
  5. {multicloud_cli-0.7.0 → 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.7.0 → multicloud_cli-0.9.0}/multicloud_cli/pool.py +12 -1
  8. multicloud_cli-0.9.0/multicloud_cli/version_check.py +101 -0
  9. {multicloud_cli-0.7.0 → multicloud_cli-0.9.0}/tests/conftest.py +2 -0
  10. {multicloud_cli-0.7.0 → multicloud_cli-0.9.0}/tests/test_apply.py +12 -0
  11. {multicloud_cli-0.7.0 → multicloud_cli-0.9.0}/tests/test_cloud_account.py +278 -18
  12. {multicloud_cli-0.7.0 → multicloud_cli-0.9.0}/tests/test_conventions.py +2 -1
  13. {multicloud_cli-0.7.0 → multicloud_cli-0.9.0}/tests/test_pool.py +42 -0
  14. multicloud_cli-0.9.0/tests/test_version_check.py +232 -0
  15. multicloud_cli-0.7.0/multicloud_cli/__init__.py +0 -1
  16. multicloud_cli-0.7.0/multicloud_cli/net.py +0 -30
  17. {multicloud_cli-0.7.0 → multicloud_cli-0.9.0}/.gitignore +0 -0
  18. {multicloud_cli-0.7.0 → multicloud_cli-0.9.0}/LICENSE +0 -0
  19. {multicloud_cli-0.7.0 → multicloud_cli-0.9.0}/multicloud_cli/account.py +0 -0
  20. {multicloud_cli-0.7.0 → multicloud_cli-0.9.0}/multicloud_cli/api.py +0 -0
  21. {multicloud_cli-0.7.0 → multicloud_cli-0.9.0}/multicloud_cli/auth.py +0 -0
  22. {multicloud_cli-0.7.0 → multicloud_cli-0.9.0}/multicloud_cli/catalog.py +0 -0
  23. {multicloud_cli-0.7.0 → multicloud_cli-0.9.0}/multicloud_cli/config.py +0 -0
  24. {multicloud_cli-0.7.0 → multicloud_cli-0.9.0}/multicloud_cli/duration.py +0 -0
  25. {multicloud_cli-0.7.0 → multicloud_cli-0.9.0}/multicloud_cli/exitcodes.py +0 -0
  26. {multicloud_cli-0.7.0 → multicloud_cli-0.9.0}/multicloud_cli/extend.py +0 -0
  27. {multicloud_cli-0.7.0 → multicloud_cli-0.9.0}/multicloud_cli/node.py +0 -0
  28. {multicloud_cli-0.7.0 → multicloud_cli-0.9.0}/multicloud_cli/orgopt.py +0 -0
  29. {multicloud_cli-0.7.0 → multicloud_cli-0.9.0}/multicloud_cli/output.py +0 -0
  30. {multicloud_cli-0.7.0 → multicloud_cli-0.9.0}/multicloud_cli/ssh.py +0 -0
  31. {multicloud_cli-0.7.0 → multicloud_cli-0.9.0}/multicloud_cli/ssh_cert.py +0 -0
  32. {multicloud_cli-0.7.0 → multicloud_cli-0.9.0}/multicloud_cli/sso.py +0 -0
  33. {multicloud_cli-0.7.0 → multicloud_cli-0.9.0}/pyproject.toml +0 -0
  34. {multicloud_cli-0.7.0 → multicloud_cli-0.9.0}/tests/__init__.py +0 -0
  35. {multicloud_cli-0.7.0 → multicloud_cli-0.9.0}/tests/helpers.py +0 -0
  36. {multicloud_cli-0.7.0 → multicloud_cli-0.9.0}/tests/test_account_extend.py +0 -0
  37. {multicloud_cli-0.7.0 → multicloud_cli-0.9.0}/tests/test_auth.py +0 -0
  38. {multicloud_cli-0.7.0 → multicloud_cli-0.9.0}/tests/test_catalog.py +0 -0
  39. {multicloud_cli-0.7.0 → multicloud_cli-0.9.0}/tests/test_net.py +0 -0
  40. {multicloud_cli-0.7.0 → multicloud_cli-0.9.0}/tests/test_ssh.py +0 -0
  41. {multicloud_cli-0.7.0 → multicloud_cli-0.9.0}/tests/test_ssh_cert.py +0 -0
  42. {multicloud_cli-0.7.0 → multicloud_cli-0.9.0}/tests/test_sso.py +0 -0
  43. {multicloud_cli-0.7.0 → 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.0
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
 
@@ -60,6 +88,14 @@ def call(method: str, org: Optional[str], tail: str = "", *, body: Optional[Dict
60
88
  _NOUN = {"AWS": "AWS account", "GCE": "GCP project", "AZURE": "Azure subscription"}
61
89
 
62
90
 
91
+ # The cloud's own id of an account (what accept-shared-account wants typed), and what it looks like.
92
+ _NATIVE_ID = {
93
+ "AWS": ("AWS account ID", "12 digits, for example 123456789012"),
94
+ "GCE": ("GCP project ID", "lower-case letters, digits and hyphens, for example my-project-123"),
95
+ "AZURE": ("Azure subscription ID", "a GUID, for example 0f1e2d3c-4b5a-6978-8796-a5b4c3d2e1f0"),
96
+ }
97
+
98
+
63
99
  def noun_of(cloud: Optional[str]) -> str:
64
100
  return _NOUN.get(str(cloud or "").upper(), "cloud account")
65
101
 
@@ -172,8 +208,9 @@ def opt_in_lines(block: Optional[Dict[str, Any]], account_id: Any = None) -> lis
172
208
 
173
209
  def terraform_outputs() -> Dict[str, Any]:
174
210
  """The connect body from ``tofu output -json`` in the cwd (``terraform`` when ``tofu`` is not on
175
- the PATH, as for ``apply``): ``role_arn`` (AWS) or ``wif_provider`` and ``service_account_email``
176
- (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``."""
177
214
  try:
178
215
  tool = next((t for t in ("tofu", "terraform") if shutil.which(t)), None) # the order of apply
179
216
  if tool is None:
@@ -183,7 +220,12 @@ def terraform_outputs() -> Dict[str, Any]:
183
220
  except (OSError, subprocess.CalledProcessError, ValueError) as ex:
184
221
  raise CloudAccountError(f"Could not read 'terraform output -json' in this directory: {ex}")
185
222
  values = {}
186
- 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",)
187
229
  for name in names + ("policy_version", "module_version"):
188
230
  item = outputs.get(name)
189
231
  if not isinstance(item, dict) or item.get("value") in (None, ""):
@@ -239,7 +281,7 @@ def _tf_file_exists():
239
281
  @org_option()
240
282
  @click.pass_context
241
283
  def cloud_account(ctx, org):
242
- """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)."""
243
285
  ctx.ensure_object(dict)
244
286
  ctx.obj["cloud_account_org"] = org
245
287
 
@@ -261,8 +303,12 @@ def _file_exists(name: str):
261
303
 
262
304
 
263
305
  @cloud_account.command()
264
- @click.option("--cloud", required=True, type=click.Choice(["AWS", "GCE"], case_sensitive=False))
265
- @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)")
266
312
  @click.option("--new-account-email", "new_email", metavar="EMAIL",
267
313
  help="AWS: create a new AWS account for Multicloud in your AWS Organizations, with this email "
268
314
  "(not allowed with --account)")
@@ -272,11 +318,11 @@ def _file_exists(name: str):
272
318
  help="AWS: turn on the opt-in regions of the account that are off (default: yes; "
273
319
  "asks when stdin is a terminal)")
274
320
  @click.option("--allow-quota-requests/--no-allow-quota-requests", "allow_quota", default=None,
275
- help="AWS: allow Multicloud to request higher quotas in this account (default: no; asks when "
276
- "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")
277
323
  @json_option
278
324
  @click.pass_context
279
- 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):
280
326
  """Register an account and write multicloud.tf. No token is printed.
281
327
 
282
328
  An existing multicloud.tf is kept: a new external id in it would cut off a connected account.
@@ -289,10 +335,32 @@ def create(ctx, cloud, account, new_email, regions, force, opt_in, allow_quota,
289
335
  turns them on (only the --region ones when you give --region). That takes minutes to hours; verify
290
336
  again to add them.
291
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
+
292
342
  Quota requests: Multicloud files a quota increase request in the account only when you allow it
293
343
  (--allow-quota-requests, or 'y' at the question). Without it, verify only reads the quotas and tells
294
344
  you what to request. Change it later with allow-quota-requests or revoke-quota-requests."""
295
- 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
296
364
  if gce and account:
297
365
  raise click.UsageError("--account is not allowed for GCE: Multicloud generates the project id.")
298
366
  if gce and new_email:
@@ -303,8 +371,8 @@ def create(ctx, cloud, account, new_email, regions, force, opt_in, allow_quota,
303
371
  if gce and opt_in is not None:
304
372
  raise click.UsageError("--opt-in-regions applies to AWS only.")
305
373
  if gce and allow_quota is not None:
306
- raise click.UsageError("--allow-quota-requests applies to AWS only: Multicloud files no GCP quota "
307
- "request.")
374
+ raise click.UsageError("--allow-quota-requests applies to AWS and Azure only: Multicloud files no GCP "
375
+ "quota request.")
308
376
  if new_email:
309
377
  new_email = new_email.strip()
310
378
  if not _EMAIL.match(new_email):
@@ -320,8 +388,10 @@ def create(ctx, cloud, account, new_email, regions, force, opt_in, allow_quota,
320
388
  _tf_file_exists()
321
389
  if new_email and Path(TFVARS_FILE).exists() and not force:
322
390
  _file_exists(TFVARS_FILE)
323
- body = {"cloud": cloud.upper()}
324
- if not gce:
391
+ body = {"cloud": cloud}
392
+ if azure:
393
+ body["expected_native_id"] = account
394
+ elif not gce:
325
395
  if account:
326
396
  body["expected_native_id"] = account
327
397
  if new_email:
@@ -331,19 +401,18 @@ def create(ctx, cloud, account, new_email, regions, force, opt_in, allow_quota,
331
401
  if _stdin_is_tty() else True)
332
402
  body["enable_opt_in_regions"] = bool(opt_in)
333
403
  if allow_quota is None:
334
- if _stdin_is_tty():
335
- click.echo("Multicloud can request higher spot quotas in this account (AWS Service Quotas) when "
336
- "they are too low for your pools. Without it, Multicloud only reads the quotas and "
337
- "tells you what to request.", err=True)
338
- allow_quota = click.confirm(QUOTA_QUESTION, default=False, err=True)
339
- else:
340
- allow_quota = False
404
+ allow_quota = _ask_quota(cloud)
405
+ if azure and allow_quota is None:
406
+ allow_quota = _ask_quota(cloud)
341
407
  if regions:
342
408
  body["regions"] = list(regions)
343
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)
344
413
  try:
345
414
  with open(TF_FILE, "w" if force else "x") as f:
346
- f.write(made["terraform"])
415
+ f.write(terraform)
347
416
  except FileExistsError: # created after the check above
348
417
  _tf_file_exists()
349
418
  if new_email:
@@ -361,6 +430,8 @@ def create(ctx, cloud, account, new_email, regions, force, opt_in, allow_quota,
361
430
  _dump(shown)
362
431
  if gce:
363
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}"
364
435
  elif account:
365
436
  target = f"AWS account {account}"
366
437
  elif new_email:
@@ -375,12 +446,38 @@ def create(ctx, cloud, account, new_email, regions, force, opt_in, allow_quota,
375
446
  elif not gce and not account:
376
447
  say("The AWS account ID is read when the module connects. The account should be a new AWS account "
377
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}.")
378
452
  for line in consent_lines:
379
453
  say(line)
380
454
  say(f"Next: mctl cloud-account apply {acct_id}")
381
455
  say(f"By hand: mctl cloud-account token {acct_id}, then tofu apply (or terraform apply).")
382
456
 
383
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
+
384
481
  def _create_quota_consent(ctx, acct_id, allow: bool, say) -> Optional[Dict[str, Any]]:
385
482
  """After create: allow quota requests when asked to. Returns the account the allow call answered, else None.
386
483
  A refusal (no owner sign-in) keeps the account and says so on stderr."""
@@ -443,6 +540,9 @@ def _readable(data: Dict[str, Any]) -> str:
443
540
  ("Role", data.get("role_arn")),
444
541
  ("Workload identity provider", data.get("wif_provider")),
445
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")),
446
546
  ("Policy version", data.get("policy_version")),
447
547
  ("Module version", data.get("module_version")),
448
548
  ("Connected", data.get("connected_on")),
@@ -542,7 +642,7 @@ def _verify_loop(org, account_id: int, wait: bool, timeout: int, interval: int,
542
642
  if as_json:
543
643
  _dump(data)
544
644
  native = data.get("native_id") or data.get("expected_native_id")
545
- 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 "
546
646
  f"(policy version {data.get('policy_version')}).")
547
647
  for line in quota_lines(data.get("quota")):
548
648
  say(line)
@@ -552,9 +652,10 @@ def _verify_loop(org, account_id: int, wait: bool, timeout: int, interval: int,
552
652
  say("quota WAIT AWS may still apply an IAM change. Wait a few minutes, then run: "
553
653
  f"mctl cloud-account verify {account_id}")
554
654
  return exitcodes.OK
555
- note(f"Pending: the role is not usable yet ({data.get('status_reason') or 'no reason given'}). "
556
- f"{'Google Cloud can take some minutes' if data.get('cloud') == 'GCE' else 'AWS can take up to 15 minutes'} "
557
- 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.")
558
659
  if not wait or waited >= timeout:
559
660
  if as_json:
560
661
  _dump(data)
@@ -601,6 +702,10 @@ def accept_shared_account(ctx, account_id):
601
702
  click.echo(f"Error: cloud account {account_id} needs no approval ({describe_verify(data)}; "
602
703
  f"dedicated: {dedicated_label(data)}).", err=True)
603
704
  sys.exit(exitcodes.ERROR)
705
+ if not native:
706
+ click.echo(f"Error: cloud account {account_id} has no cloud id yet, so there is nothing to approve. "
707
+ f"Run: mctl cloud-account verify {account_id}", err=True)
708
+ sys.exit(exitcodes.ERROR)
604
709
  noun = noun_of(cloud)
605
710
  for line in shared_warning(cloud):
606
711
  click.echo(line)
@@ -608,9 +713,17 @@ def accept_shared_account(ctx, account_id):
608
713
  if not _stdin_is_tty():
609
714
  click.echo("Error: the approval needs a person at a terminal: type the id when asked.", err=True)
610
715
  sys.exit(exitcodes.ERROR)
611
- typed = click.prompt(f"To connect {noun} {native} anyway, type its id", default="", show_default=False)
612
- if not native or not typed.strip() or typed.strip().lower() != str(native).lower():
613
- click.echo("The id does not match. Nothing approved.", err=True)
716
+ kind, example = _NATIVE_ID.get(str(cloud or "").upper(), ("cloud id", "the id your cloud shows"))
717
+ click.echo(f"To connect it anyway, type the {kind} ({native}). The {kind} is {example}. "
718
+ f"It is not the Multicloud cloud account id {account_id}.")
719
+ typed = click.prompt(kind, default="", show_default=False).strip()
720
+ if not native or not typed or typed.lower() != str(native).lower():
721
+ if typed == str(account_id):
722
+ click.echo(f"You typed the Multicloud cloud account id {account_id}. Type the {kind} {native} "
723
+ f"instead.", err=True)
724
+ else:
725
+ click.echo(f"The id does not match the {kind} {native}.", err=True)
726
+ click.echo("Nothing approved.", err=True)
614
727
  sys.exit(exitcodes.ERROR)
615
728
  answer = _run(ctx, lambda org: call("POST", org, f"/{account_id}/accept-shared-account",
616
729
  body={"account_id": typed.strip()}, prefer_sso=True))
@@ -655,44 +768,89 @@ def revoke_quota_requests(ctx, account_id):
655
768
  f"filed stay open in the cloud.")
656
769
 
657
770
 
658
- IN_USE = "ACCOUNT_IN_USE"
771
+ WAIT_DEFAULT = "130m" # the cleanup job gives up after about two hours
772
+ WAIT_INTERVAL = 30
659
773
 
660
774
 
661
- def _disconnect(org, account_id: int, again: str = "disconnect") -> Dict[str, Any]:
662
- """``DELETE /cloud-accounts/{id}`` with the sign-in. Returns the account; raises ``CloudAccountError`` with
663
- 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."""
664
778
  try:
665
- 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)
666
780
  except api.ApiError as ex:
667
781
  raise CloudAccountError(str(ex), ex.exit_code)
668
- status = answer.pop("_status", 200)
669
- if status == 409:
670
- detail = answer.get("detail") or {}
671
- details = detail.get("details") or {}
672
- lines = [f"Cloud account {account_id} is still in use, so it stays connected. Nothing changed."]
673
- for name in details.get("pools") or []:
674
- lines.append(f" Pool {name}: delete it with 'mctl pool delete {name}'.")
675
- if details.get("other_organization_pools"):
676
- lines.append(f" {details['other_organization_pools']} pool(s) of other organizations use it: "
677
- "ask Multicloud support.")
678
- if details.get("live_servers"):
679
- lines.append(f" {details['live_servers']} server(s) still run in it. They stop a few minutes after "
680
- "their pool is deleted.")
681
- lines.append(f"Then run 'mctl cloud-account {again} {account_id}' again.")
682
- raise CloudAccountError("\n".join(lines), exitcodes.ERROR)
782
+ answer.pop("_status", None)
683
783
  return answer
684
784
 
685
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
+
686
840
  @cloud_account.command()
687
841
  @click.argument("account_id", type=int)
688
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)")
689
846
  @click.pass_context
690
- def disconnect(ctx, account_id, yes):
847
+ def disconnect(ctx, account_id, yes, wait, timeout):
691
848
  """Disconnect a cloud account from the organization (organization owners only).
692
849
 
693
- Multicloud stops using the account at once. Nothing in the account is deleted: remove the Multicloud role
694
- afterwards with 'tofu destroy' (or 'mctl cloud-account destroy' for an AWS account that mctl created). A pool
695
- 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."""
696
854
  # The sign-in from the start: the API refuses an API key here, so fail before the prompt.
697
855
  data = _run(ctx, lambda org: call("GET", org, f"/{account_id}", prefer_sso=True))
698
856
  data.pop("_status", None)
@@ -711,10 +869,29 @@ def disconnect(ctx, account_id, yes):
711
869
  if not click.confirm(f"Disconnect {which}?", default=False):
712
870
  click.echo("Nothing changed.", err=True)
713
871
  sys.exit(exitcodes.ERROR)
714
- _run(ctx, lambda org: _disconnect(org, account_id))
715
- 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)
716
889
  if not data.get("connected_on"):
717
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
718
895
  click.echo("Next: remove the Multicloud role from the account. Run 'tofu destroy' (or 'terraform destroy') in "
719
896
  f"the folder with {TF_FILE}, or 'mctl cloud-account destroy {account_id}' if mctl created the AWS account.")
720
897
 
@@ -781,13 +958,15 @@ def _aws_account_state(account_id: str) -> Optional[str]:
781
958
  @click.option("--dir", "directory", default=".", type=click.Path(file_okay=False), help="Folder with multicloud.tf")
782
959
  @click.option("--tool", type=click.Choice(["tofu", "terraform"]), default=None, help="Default: tofu, then terraform")
783
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)")
784
963
  @click.pass_context
785
- def destroy(ctx, account_id, directory, tool, yes):
964
+ def destroy(ctx, account_id, directory, tool, yes, timeout):
786
965
  """Disconnect the AWS account that multicloud.tf created, then close it.
787
966
 
788
967
  Only for a file made with 'create --new-account-email'. The account is disconnected from your organization
789
- first (organization owners only; needs mctl auth login), so a pool that still uses it stops the command before
790
- 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
791
970
  account again."""
792
971
  text = _check_file(account_id, directory)
793
972
  if not _PATH_A.search(text):
@@ -816,10 +995,18 @@ def destroy(ctx, account_id, directory, tool, yes):
816
995
  if not click.confirm(f"Close {which}?", default=False):
817
996
  click.echo("Nothing destroyed.", err=True)
818
997
  sys.exit(exitcodes.ERROR)
819
- # Disconnect first: a closed account must not stay connected, and a pool that still uses it stops us here,
820
- # before anything is closed. An account that is already disconnected answers the same.
821
- _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))
822
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.")
823
1010
  # The account closes with everything in it. Deleting the Spot service-linked role can be blocked
824
1011
  # for about 4 minutes after the last spot instance ends, so the destroy must not depend on it.
825
1012
  code, out = _run(ctx, lambda org: _tool_capture(tool, ["state", "rm", "module.multicloud"], directory, base_env))
@@ -921,7 +1108,9 @@ def apply(ctx, account_id, directory, tool, plan_only, yes, timeout, interval):
921
1108
  click.echo("Error: Refusing to apply without confirmation. Review the plan, then run again "
922
1109
  "with --yes.", err=True)
923
1110
  sys.exit(1)
924
- 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")
925
1114
  if not click.confirm(f"Apply this plan to your {target}?", default=False):
926
1115
  click.echo("Nothing applied.", err=True)
927
1116
  sys.exit(exitcodes.ERROR)
@@ -944,12 +1133,13 @@ def apply(ctx, account_id, directory, tool, plan_only, yes, timeout, interval):
944
1133
  @cloud_account.command()
945
1134
  @click.argument("account_id", type=int)
946
1135
  @click.option("--from-terraform-output", "from_tf", is_flag=True,
947
- 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), "
948
1138
  "policy_version and module_version from 'terraform output -json' "
949
1139
  "(the only input; this is the default)")
950
1140
  @click.pass_context
951
1141
  def connect(ctx, account_id, from_tf):
952
- """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."""
953
1143
  token = os.environ.get(TOKEN_ENV)
954
1144
  if not token:
955
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