multicloud-cli 0.4.0__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.
- {multicloud_cli-0.4.0 → multicloud_cli-0.5.0}/PKG-INFO +3 -2
- {multicloud_cli-0.4.0 → multicloud_cli-0.5.0}/README.md +2 -1
- multicloud_cli-0.5.0/multicloud_cli/__init__.py +1 -0
- {multicloud_cli-0.4.0 → multicloud_cli-0.5.0}/multicloud_cli/cloud_account.py +311 -23
- {multicloud_cli-0.4.0 → multicloud_cli-0.5.0}/multicloud_cli/extend.py +2 -1
- {multicloud_cli-0.4.0 → multicloud_cli-0.5.0}/tests/test_account_extend.py +6 -0
- {multicloud_cli-0.4.0 → multicloud_cli-0.5.0}/tests/test_cloud_account.py +360 -0
- multicloud_cli-0.4.0/multicloud_cli/__init__.py +0 -1
- {multicloud_cli-0.4.0 → multicloud_cli-0.5.0}/.gitignore +0 -0
- {multicloud_cli-0.4.0 → multicloud_cli-0.5.0}/LICENSE +0 -0
- {multicloud_cli-0.4.0 → multicloud_cli-0.5.0}/multicloud_cli/account.py +0 -0
- {multicloud_cli-0.4.0 → multicloud_cli-0.5.0}/multicloud_cli/api.py +0 -0
- {multicloud_cli-0.4.0 → multicloud_cli-0.5.0}/multicloud_cli/auth.py +0 -0
- {multicloud_cli-0.4.0 → multicloud_cli-0.5.0}/multicloud_cli/catalog.py +0 -0
- {multicloud_cli-0.4.0 → multicloud_cli-0.5.0}/multicloud_cli/config.py +0 -0
- {multicloud_cli-0.4.0 → multicloud_cli-0.5.0}/multicloud_cli/duration.py +0 -0
- {multicloud_cli-0.4.0 → multicloud_cli-0.5.0}/multicloud_cli/exitcodes.py +0 -0
- {multicloud_cli-0.4.0 → multicloud_cli-0.5.0}/multicloud_cli/main.py +0 -0
- {multicloud_cli-0.4.0 → multicloud_cli-0.5.0}/multicloud_cli/net.py +0 -0
- {multicloud_cli-0.4.0 → multicloud_cli-0.5.0}/multicloud_cli/node.py +0 -0
- {multicloud_cli-0.4.0 → multicloud_cli-0.5.0}/multicloud_cli/orgopt.py +0 -0
- {multicloud_cli-0.4.0 → multicloud_cli-0.5.0}/multicloud_cli/output.py +0 -0
- {multicloud_cli-0.4.0 → multicloud_cli-0.5.0}/multicloud_cli/pool.py +0 -0
- {multicloud_cli-0.4.0 → multicloud_cli-0.5.0}/multicloud_cli/ssh.py +0 -0
- {multicloud_cli-0.4.0 → multicloud_cli-0.5.0}/multicloud_cli/ssh_cert.py +0 -0
- {multicloud_cli-0.4.0 → multicloud_cli-0.5.0}/multicloud_cli/sso.py +0 -0
- {multicloud_cli-0.4.0 → multicloud_cli-0.5.0}/pyproject.toml +0 -0
- {multicloud_cli-0.4.0 → multicloud_cli-0.5.0}/tests/__init__.py +0 -0
- {multicloud_cli-0.4.0 → multicloud_cli-0.5.0}/tests/conftest.py +0 -0
- {multicloud_cli-0.4.0 → multicloud_cli-0.5.0}/tests/helpers.py +0 -0
- {multicloud_cli-0.4.0 → multicloud_cli-0.5.0}/tests/test_apply.py +0 -0
- {multicloud_cli-0.4.0 → multicloud_cli-0.5.0}/tests/test_auth.py +0 -0
- {multicloud_cli-0.4.0 → multicloud_cli-0.5.0}/tests/test_catalog.py +0 -0
- {multicloud_cli-0.4.0 → multicloud_cli-0.5.0}/tests/test_conventions.py +0 -0
- {multicloud_cli-0.4.0 → multicloud_cli-0.5.0}/tests/test_net.py +0 -0
- {multicloud_cli-0.4.0 → multicloud_cli-0.5.0}/tests/test_pool.py +0 -0
- {multicloud_cli-0.4.0 → multicloud_cli-0.5.0}/tests/test_ssh.py +0 -0
- {multicloud_cli-0.4.0 → multicloud_cli-0.5.0}/tests/test_ssh_cert.py +0 -0
- {multicloud_cli-0.4.0 → multicloud_cli-0.5.0}/tests/test_sso.py +0 -0
- {multicloud_cli-0.4.0 → 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.
|
|
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
|
|
|
@@ -41,15 +46,45 @@ class CloudAccountError(exitcodes.CliError):
|
|
|
41
46
|
|
|
42
47
|
|
|
43
48
|
def call(method: str, org: Optional[str], tail: str = "", *, body: Optional[Dict[str, Any]] = None,
|
|
44
|
-
headers: Optional[Dict[str, str]] = None, accept=(200, 201, 202)
|
|
45
|
-
|
|
49
|
+
headers: Optional[Dict[str, str]] = None, accept=(200, 201, 202),
|
|
50
|
+
prefer_sso: bool = False) -> Dict[str, Any]:
|
|
51
|
+
"""One API call. Returns the JSON body with ``_status`` added; raises on other statuses.
|
|
52
|
+
``prefer_sso`` uses the sign-in even when ``MULTICLOUD_API_KEY`` is set (the owner-only routes)."""
|
|
46
53
|
try:
|
|
47
54
|
return api.call(method, org, "/cloud-accounts" + tail, body=body, headers=headers, accept=accept,
|
|
48
|
-
pass_codes=("VERIFY_FAILED",))
|
|
55
|
+
pass_codes=("VERIFY_FAILED",), prefer_sso=prefer_sso)
|
|
49
56
|
except api.ApiError as ex:
|
|
50
57
|
raise CloudAccountError(str(ex), ex.exit_code)
|
|
51
58
|
|
|
52
59
|
|
|
60
|
+
_NOUN = {"AWS": "AWS account", "GCE": "GCP project", "AZURE": "Azure subscription"}
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def noun_of(cloud: Optional[str]) -> str:
|
|
64
|
+
return _NOUN.get(str(cloud or "").upper(), "cloud account")
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def shared_warning(cloud: Optional[str]) -> list:
|
|
68
|
+
"""The warning for a cloud account that is not dedicated to Multicloud (D2): short, says what to do."""
|
|
69
|
+
noun = noun_of(cloud)
|
|
70
|
+
return [
|
|
71
|
+
f"This {noun} is also used for other work.",
|
|
72
|
+
f"Multicloud works best in a new {noun} made only for Multicloud.",
|
|
73
|
+
"If you connect it anyway:",
|
|
74
|
+
" - Multicloud changes only the resources it created.",
|
|
75
|
+
f" - Multicloud shares the limits (quotas) and the bill of this {noun} with your other work.",
|
|
76
|
+
f" - To remove Multicloud later, you delete its resources; you cannot simply delete the {noun}.",
|
|
77
|
+
]
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def approval_lines(cloud: Optional[str], account_id) -> list:
|
|
81
|
+
"""The warning plus the two next steps: a new account (recommended), or an owner's approval."""
|
|
82
|
+
return shared_warning(cloud) + [
|
|
83
|
+
f"Recommended: use a new {noun_of(cloud)} instead (mctl cloud-account create).",
|
|
84
|
+
f"Connect anyway (organization owners only): mctl cloud-account accept-shared-account {account_id}",
|
|
85
|
+
]
|
|
86
|
+
|
|
87
|
+
|
|
53
88
|
def describe_verify(answer: Dict[str, Any]) -> str:
|
|
54
89
|
"""The text for a connect or verify answer, including the missing permissions of a 422."""
|
|
55
90
|
detail = answer.get("detail")
|
|
@@ -143,13 +178,25 @@ def terraform_outputs() -> Dict[str, Any]:
|
|
|
143
178
|
return values
|
|
144
179
|
|
|
145
180
|
|
|
181
|
+
def dedicated_label(account: Dict[str, Any]) -> str:
|
|
182
|
+
"""yes, no (approved), no (approval required), or - before the first check."""
|
|
183
|
+
if account.get("dedicated") is True:
|
|
184
|
+
return "yes"
|
|
185
|
+
if account.get("dedicated") is False:
|
|
186
|
+
if account.get("shared_risk_accepted_on"):
|
|
187
|
+
return "no (approved)"
|
|
188
|
+
return "no (approval required)" if account.get("approval_required") else "no"
|
|
189
|
+
return "-"
|
|
190
|
+
|
|
191
|
+
|
|
146
192
|
def format_table(accounts, headers: bool = True) -> str:
|
|
147
|
-
rows = ([("ID", "CLOUD", "STATUS", "ACCOUNT")] if headers else []) + [
|
|
148
|
-
(str(a.get("id")), str(a.get("cloud")), str(a.get("status")), str(a.get("expected_native_id")))
|
|
193
|
+
rows = ([("ID", "CLOUD", "STATUS", "ACCOUNT", "DEDICATED")] if headers else []) + [
|
|
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 "-"),
|
|
195
|
+
dedicated_label(a))
|
|
149
196
|
for a in accounts]
|
|
150
197
|
if not rows:
|
|
151
198
|
return ""
|
|
152
|
-
widths = [max(len(r[i]) for r in rows) for i in range(
|
|
199
|
+
widths = [max(len(r[i]) for r in rows) for i in range(5)]
|
|
153
200
|
return "\n".join(" ".join(c.ljust(w) for c, w in zip(r, widths)).rstrip() for r in rows)
|
|
154
201
|
|
|
155
202
|
|
|
@@ -182,9 +229,24 @@ def _run(ctx, fn):
|
|
|
182
229
|
return run(ctx.obj.get("cloud_account_org"), fn, (CloudAccountError,))
|
|
183
230
|
|
|
184
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
|
+
|
|
185
244
|
@cloud_account.command()
|
|
186
245
|
@click.option("--cloud", required=True, type=click.Choice(["AWS", "GCE"], case_sensitive=False))
|
|
187
|
-
@click.option("--account", help="
|
|
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)")
|
|
188
250
|
@click.option("--region", "regions", multiple=True, help="Region to allow; repeat for several")
|
|
189
251
|
@click.option("--force", is_flag=True, help="Overwrite an existing multicloud.tf")
|
|
190
252
|
@click.option("--opt-in-regions/--no-opt-in-regions", "opt_in", default=None,
|
|
@@ -192,26 +254,49 @@ def _run(ctx, fn):
|
|
|
192
254
|
"asks when stdin is a terminal)")
|
|
193
255
|
@json_option
|
|
194
256
|
@click.pass_context
|
|
195
|
-
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):
|
|
196
258
|
"""Register an account and write multicloud.tf. No token is printed.
|
|
197
259
|
|
|
198
260
|
An existing multicloud.tf is kept: a new external id in it would cut off a connected account.
|
|
199
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
|
+
|
|
200
266
|
AWS opt-in regions (for example af-south-1) are off in a new account. With the default, Multicloud
|
|
201
267
|
turns them on (only the --region ones when you give --region). That takes minutes to hours; verify
|
|
202
268
|
again to add them."""
|
|
203
269
|
gce = cloud.upper() == "GCE"
|
|
204
270
|
if gce and account:
|
|
205
271
|
raise click.UsageError("--account is not allowed for GCE: Multicloud generates the project id.")
|
|
206
|
-
if
|
|
207
|
-
raise click.UsageError("--account
|
|
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.")
|
|
208
277
|
if gce and opt_in is not None:
|
|
209
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)
|
|
210
290
|
if Path(TF_FILE).exists() and not force:
|
|
211
291
|
_tf_file_exists()
|
|
292
|
+
if new_email and Path(TFVARS_FILE).exists() and not force:
|
|
293
|
+
_file_exists(TFVARS_FILE)
|
|
212
294
|
body = {"cloud": cloud.upper()}
|
|
213
295
|
if not gce:
|
|
214
|
-
|
|
296
|
+
if account:
|
|
297
|
+
body["expected_native_id"] = account
|
|
298
|
+
if new_email:
|
|
299
|
+
body["new_account"] = True
|
|
215
300
|
if opt_in is None:
|
|
216
301
|
opt_in = (click.confirm("Turn on the AWS opt-in regions in this account?", default=True, err=True)
|
|
217
302
|
if _stdin_is_tty() else True)
|
|
@@ -224,12 +309,32 @@ def create(ctx, cloud, account, regions, force, opt_in, as_json):
|
|
|
224
309
|
f.write(made["terraform"])
|
|
225
310
|
except FileExistsError: # created after the check above
|
|
226
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)
|
|
227
318
|
acct_id = made["account"]["id"]
|
|
228
319
|
if as_json: # the created account; the Terraform file is in multicloud.tf
|
|
229
320
|
_dump(made["account"])
|
|
230
321
|
say = lambda text: click.echo(text, err=as_json) # noqa: E731
|
|
231
|
-
|
|
232
|
-
|
|
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.")
|
|
233
338
|
say(f"Next: mctl cloud-account apply {acct_id}")
|
|
234
339
|
say(f"By hand: mctl cloud-account token {acct_id}, then tofu apply (or terraform apply).")
|
|
235
340
|
|
|
@@ -284,7 +389,12 @@ def _readable(data: Dict[str, Any]) -> str:
|
|
|
284
389
|
("Verified", data.get("verified_on")),
|
|
285
390
|
("Last check", data.get("last_probe_on")),
|
|
286
391
|
("Reason", data.get("status_reason")),
|
|
392
|
+
("Dedicated", dedicated_label(data)),
|
|
393
|
+
("Shared account approved by", data.get("shared_risk_accepted_by")),
|
|
394
|
+
("Shared account approved on", data.get("shared_risk_accepted_on")),
|
|
287
395
|
]
|
|
396
|
+
if data.get("approval_required"):
|
|
397
|
+
lines += approval_lines(data.get("cloud"), data.get("id"))
|
|
288
398
|
# The refused quota requests the last verify left (the same lines verify prints).
|
|
289
399
|
lines += quota_lines({"refused": data.get("quota_refused")})
|
|
290
400
|
return "\n".join(l if isinstance(l, str) else f"{l[0]}: {l[1]}"
|
|
@@ -345,6 +455,12 @@ def _verify_loop(org, account_id: int, wait: bool, timeout: int, interval: int,
|
|
|
345
455
|
if as_json:
|
|
346
456
|
_dump(data)
|
|
347
457
|
say(describe_verify(data))
|
|
458
|
+
info = (data.get("detail") or {}).get("details") or {}
|
|
459
|
+
if info.get("approval_required"):
|
|
460
|
+
# D2: not a refusal. The account waits for a new account or an owner's approval.
|
|
461
|
+
for line in approval_lines(info.get("cloud"), account_id):
|
|
462
|
+
say(line)
|
|
463
|
+
return exitcodes.ERROR
|
|
348
464
|
say(f"Fix: apply the module again (mctl cloud-account apply {account_id}), then verify.")
|
|
349
465
|
return exitcodes.ERROR
|
|
350
466
|
if status != 202 and data.get("status") != "verified":
|
|
@@ -408,6 +524,49 @@ def verify(ctx, account_id, wait, timeout, interval, opt_in, as_json):
|
|
|
408
524
|
sys.exit(code)
|
|
409
525
|
|
|
410
526
|
|
|
527
|
+
@cloud_account.command(name="accept-shared-account")
|
|
528
|
+
@click.argument("account_id", type=int)
|
|
529
|
+
@click.pass_context
|
|
530
|
+
def accept_shared_account(ctx, account_id):
|
|
531
|
+
"""Connect a cloud account that is not dedicated to Multicloud (organization owners only).
|
|
532
|
+
|
|
533
|
+
Shows the warning, then asks you to type the account's cloud id. There is no --yes: the typed id is
|
|
534
|
+
the approval, and it covers this account only. Needs a sign-in (mctl auth login), not an API key."""
|
|
535
|
+
# The sign-in from the start: the API refuses an API key here, so fail before the prompt.
|
|
536
|
+
data = _run(ctx, lambda org: call("GET", org, f"/{account_id}", prefer_sso=True))
|
|
537
|
+
data.pop("_status", None)
|
|
538
|
+
cloud, native = data.get("cloud"), data.get("native_id") or data.get("expected_native_id")
|
|
539
|
+
if not data.get("approval_required"):
|
|
540
|
+
click.echo(f"Error: cloud account {account_id} needs no approval ({describe_verify(data)}; "
|
|
541
|
+
f"dedicated: {dedicated_label(data)}).", err=True)
|
|
542
|
+
sys.exit(exitcodes.ERROR)
|
|
543
|
+
noun = noun_of(cloud)
|
|
544
|
+
for line in shared_warning(cloud):
|
|
545
|
+
click.echo(line)
|
|
546
|
+
click.echo(f"Recommended: use a new {noun} instead (mctl cloud-account create).")
|
|
547
|
+
if not _stdin_is_tty():
|
|
548
|
+
click.echo("Error: the approval needs a person at a terminal: type the id when asked.", err=True)
|
|
549
|
+
sys.exit(exitcodes.ERROR)
|
|
550
|
+
typed = click.prompt(f"To connect {noun} {native} anyway, type its id", default="", show_default=False)
|
|
551
|
+
if not native or not typed.strip() or typed.strip().lower() != str(native).lower():
|
|
552
|
+
click.echo("The id does not match. Nothing approved.", err=True)
|
|
553
|
+
sys.exit(exitcodes.ERROR)
|
|
554
|
+
answer = _run(ctx, lambda org: call("POST", org, f"/{account_id}/accept-shared-account",
|
|
555
|
+
body={"account_id": typed.strip()}, prefer_sso=True))
|
|
556
|
+
status = answer.pop("_status", 200)
|
|
557
|
+
if status == 200 and answer.get("status") == "verified":
|
|
558
|
+
click.echo(f"Ready: {noun} {native} is connected as a shared account "
|
|
559
|
+
f"(approved by {answer.get('shared_risk_accepted_by')}).")
|
|
560
|
+
for line in quota_lines(answer.get("quota")):
|
|
561
|
+
click.echo(line)
|
|
562
|
+
return
|
|
563
|
+
click.echo(describe_verify(answer))
|
|
564
|
+
if status == 202:
|
|
565
|
+
click.echo(f"Approved. The account is not usable yet: run mctl cloud-account verify {account_id} --wait")
|
|
566
|
+
sys.exit(exitcodes.PENDING)
|
|
567
|
+
sys.exit(exitcodes.ERROR)
|
|
568
|
+
|
|
569
|
+
|
|
411
570
|
def _find_tool(requested: Optional[str]) -> str:
|
|
412
571
|
if requested:
|
|
413
572
|
if not shutil.which(requested):
|
|
@@ -427,6 +586,110 @@ def _tool_run(tool: str, args, cwd: str, env: Dict[str, str]) -> int:
|
|
|
427
586
|
raise CloudAccountError(f"Could not run {tool}: {ex}")
|
|
428
587
|
|
|
429
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
|
+
|
|
430
693
|
@cloud_account.command()
|
|
431
694
|
@click.argument("account_id", type=int)
|
|
432
695
|
@click.option("--dir", "directory", default=".", type=click.Path(file_okay=False), help="Folder with multicloud.tf")
|
|
@@ -443,14 +706,7 @@ def apply(ctx, account_id, directory, tool, plan_only, yes, timeout, interval):
|
|
|
443
706
|
|
|
444
707
|
The token reaches tofu/terraform only through the environment of that one process."""
|
|
445
708
|
tf = Path(directory) / TF_FILE
|
|
446
|
-
|
|
447
|
-
click.echo(f"Error: {tf} does not exist. Run: mctl cloud-account create", err=True)
|
|
448
|
-
sys.exit(1)
|
|
449
|
-
found = re.search(r"account_row_id\s*=\s*(\d+)", tf.read_text())
|
|
450
|
-
if found and int(found.group(1)) != account_id:
|
|
451
|
-
click.echo(f"Error: {TF_FILE} in {directory} is for cloud account {found.group(1)}, not {account_id}.",
|
|
452
|
-
err=True)
|
|
453
|
-
sys.exit(1)
|
|
709
|
+
_check_file(account_id, directory)
|
|
454
710
|
tool = _run(ctx, lambda org: _find_tool(tool))
|
|
455
711
|
# Terraform, its providers and the module's curl see this environment: no API key, no old token,
|
|
456
712
|
# and no TF_LOG (a debug log could record the token).
|
|
@@ -463,13 +719,45 @@ def apply(ctx, account_id, directory, tool, plan_only, yes, timeout, interval):
|
|
|
463
719
|
click.echo(f"Error: {tool} {what} failed (exit {code}).", err=True)
|
|
464
720
|
sys.exit(1)
|
|
465
721
|
|
|
722
|
+
placeholder_env = {**base_env, TOKEN_ENV: PLAN_PLACEHOLDER}
|
|
466
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.")
|
|
467
755
|
click.echo("The plan uses a placeholder connect token. The real token is issued only for the apply.")
|
|
468
|
-
step(["plan", "-input=false"],
|
|
756
|
+
step(["plan", "-input=false"], placeholder_env, "plan")
|
|
469
757
|
if plan_only:
|
|
470
758
|
click.echo(f"Plan only: no token issued. To apply: mctl cloud-account apply {account_id} --yes")
|
|
471
759
|
return
|
|
472
|
-
if not yes:
|
|
760
|
+
if not yes and not confirmed:
|
|
473
761
|
if not _stdin_is_tty():
|
|
474
762
|
click.echo("Error: Refusing to apply without confirmation. Review the plan, then run again "
|
|
475
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"] == {}
|
|
@@ -469,3 +469,363 @@ def test_show_prints_the_opt_in_choice(monkeypatch):
|
|
|
469
469
|
assert "Opt-in regions: leave off" in cmds._readable({"id": 5, "cloud": "AWS", "status": "verified",
|
|
470
470
|
"enable_opt_in_regions": False})
|
|
471
471
|
assert "Opt-in regions" not in cmds._readable({"id": 5, "cloud": "GCE", "status": "verified"})
|
|
472
|
+
|
|
473
|
+
|
|
474
|
+
# --- shared account approval (D2) -------------------------------------------------------------
|
|
475
|
+
|
|
476
|
+
SUB = "11111111-2222-3333-4444-555555555555"
|
|
477
|
+
SHARED = {"id": 7, "cloud": "AZURE", "status": "pending", "expected_native_id": SUB, "dedicated": False,
|
|
478
|
+
"approval_required": True, "status_reason": "SUBSCRIPTION_NOT_DEDICATED"}
|
|
479
|
+
|
|
480
|
+
|
|
481
|
+
def invoke_seq(args, responses, tty=True, input=None, sso=True):
|
|
482
|
+
"""An owner signed in with SSO while MULTICLOUD_API_KEY is also set: the approval must use the sign-in."""
|
|
483
|
+
base = {"MULTICLOUD_API_KEY": "fake-key-0000", "MULTICLOUD_ORG": "acme",
|
|
484
|
+
"MULTICLOUD_ISSUER": "https://auth.example.test/realms/multicloud"}
|
|
485
|
+
with patch.object(cmds.requests, "request", side_effect=list(responses)) as req, \
|
|
486
|
+
patch.object(cmds, "_stdin_is_tty", return_value=tty), \
|
|
487
|
+
patch.object(auth, "load_sso", return_value={"session": "x"} if sso else None), \
|
|
488
|
+
patch.object(auth, "fresh_access_token", return_value="sso-token"), \
|
|
489
|
+
patch.object(cmds.api, "_sso_org", side_effect=lambda slug, token, explicit=True: slug), \
|
|
490
|
+
patch.dict("os.environ", base, clear=False):
|
|
491
|
+
try:
|
|
492
|
+
runner = CliRunner(mix_stderr=False)
|
|
493
|
+
except TypeError:
|
|
494
|
+
runner = CliRunner()
|
|
495
|
+
return runner.invoke(mctl, args, input=input), req
|
|
496
|
+
|
|
497
|
+
|
|
498
|
+
def test_verify_approval_required_prints_the_warning_and_next_steps():
|
|
499
|
+
body = {"detail": {"code": "VERIFY_FAILED", "message": "The role in the customer account failed the verification",
|
|
500
|
+
"details": {"missing": [], "reason": "SUBSCRIPTION_NOT_DEDICATED", "approval_required": True,
|
|
501
|
+
"dedicated": False, "cloud": "AZURE"}}}
|
|
502
|
+
r, req = invoke(["cloud-account", "verify", "7"], reply(422, body))
|
|
503
|
+
assert r.exit_code == 1 and req.call_count == 1
|
|
504
|
+
assert "This Azure subscription is also used for other work." in r.stdout
|
|
505
|
+
assert "Multicloud changes only the resources it created." in r.stdout
|
|
506
|
+
assert "Recommended: use a new Azure subscription instead" in r.stdout
|
|
507
|
+
assert "mctl cloud-account accept-shared-account 7" in r.stdout
|
|
508
|
+
assert "apply the module again" not in r.stdout
|
|
509
|
+
|
|
510
|
+
|
|
511
|
+
def test_accept_shared_account_needs_the_typed_id():
|
|
512
|
+
verified = {**SHARED, "status": "verified", "approval_required": False,
|
|
513
|
+
"shared_risk_accepted_by": "bearer u-owner", "shared_risk_accepted_on": "2026-11-10T10:00:00Z"}
|
|
514
|
+
r, req = invoke_seq(["cloud-account", "accept-shared-account", "7"], [reply(200, SHARED), reply(200, verified)],
|
|
515
|
+
input=SUB.upper() + "\n")
|
|
516
|
+
assert r.exit_code == 0, r.output
|
|
517
|
+
assert "This Azure subscription is also used for other work." in r.stdout
|
|
518
|
+
assert "is connected as a shared account (approved by bearer u-owner)" in r.stdout
|
|
519
|
+
post = req.call_args_list[1]
|
|
520
|
+
assert post.args[:2] == ("POST", "https://api.multicloud.io/api/v1/orgs/acme/cloud-accounts/7/accept-shared-account")
|
|
521
|
+
assert post.kwargs["json"] == {"account_id": SUB.upper()}
|
|
522
|
+
for sent in req.call_args_list: # the sign-in, never the API key
|
|
523
|
+
assert sent.kwargs["headers"]["Authorization"] == "Bearer sso-token"
|
|
524
|
+
assert "X-API-Key" not in sent.kwargs["headers"]
|
|
525
|
+
|
|
526
|
+
|
|
527
|
+
def test_accept_shared_account_without_a_sign_in_names_the_login():
|
|
528
|
+
r, req = invoke_seq(["cloud-account", "accept-shared-account", "7"], [reply(200, SHARED)], sso=False)
|
|
529
|
+
assert r.exit_code == 3 and not req.called and "mctl auth login" in r.stderr
|
|
530
|
+
|
|
531
|
+
|
|
532
|
+
def test_accept_shared_account_wrong_id_approves_nothing():
|
|
533
|
+
r, req = invoke_seq(["cloud-account", "accept-shared-account", "7"], [reply(200, SHARED)], input="nope\n")
|
|
534
|
+
assert r.exit_code == 1 and req.call_count == 1
|
|
535
|
+
assert "Nothing approved" in r.stderr
|
|
536
|
+
|
|
537
|
+
|
|
538
|
+
def test_accept_shared_account_has_no_yes_and_needs_a_terminal():
|
|
539
|
+
r, _ = invoke_seq(["cloud-account", "accept-shared-account", "7", "--yes"], [])
|
|
540
|
+
assert r.exit_code == 2
|
|
541
|
+
r, req = invoke_seq(["cloud-account", "accept-shared-account", "7"], [reply(200, SHARED)], tty=False)
|
|
542
|
+
assert r.exit_code == 1 and req.call_count == 1 and "needs a person at a terminal" in r.stderr
|
|
543
|
+
|
|
544
|
+
|
|
545
|
+
def test_accept_shared_account_refuses_a_dedicated_account():
|
|
546
|
+
dedicated = {**SHARED, "status": "verified", "dedicated": True, "approval_required": False}
|
|
547
|
+
r, req = invoke_seq(["cloud-account", "accept-shared-account", "7"], [reply(200, dedicated)], input=SUB + "\n")
|
|
548
|
+
assert r.exit_code == 1 and req.call_count == 1 and "needs no approval" in r.stderr
|
|
549
|
+
|
|
550
|
+
|
|
551
|
+
def test_list_and_show_name_dedicated_and_the_approval():
|
|
552
|
+
approved = {**SHARED, "id": 8, "status": "verified", "approval_required": False,
|
|
553
|
+
"shared_risk_accepted_by": "bearer u-owner", "shared_risk_accepted_on": "2026-11-10T10:00:00Z"}
|
|
554
|
+
r, _ = invoke(["cloud-account", "list"], reply(200, {"cloud_accounts": [
|
|
555
|
+
{"id": 5, "cloud": "AWS", "status": "verified", "expected_native_id": ACCT, "dedicated": True},
|
|
556
|
+
SHARED, approved, {"id": 9, "cloud": "AWS", "status": "pending", "expected_native_id": ACCT}]}))
|
|
557
|
+
assert r.exit_code == 0
|
|
558
|
+
lines = r.stdout.splitlines()
|
|
559
|
+
assert lines[0].split() == ["ID", "CLOUD", "STATUS", "ACCOUNT", "DEDICATED"]
|
|
560
|
+
assert lines[1].endswith("yes") and lines[2].endswith("no (approval required)")
|
|
561
|
+
assert lines[3].endswith("no (approved)") and lines[4].endswith("-")
|
|
562
|
+
r, _ = invoke(["cloud-account", "show", "8"], reply(200, approved))
|
|
563
|
+
assert "Dedicated: no (approved)" in r.stdout
|
|
564
|
+
assert "Shared account approved by: bearer u-owner" in r.stdout
|
|
565
|
+
assert "Shared account approved on: 2026-11-10T10:00:00Z" in r.stdout
|
|
566
|
+
r, _ = invoke(["cloud-account", "show", "7"], reply(200, SHARED))
|
|
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.0"
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|