# CLI のプロファイル、更新、待機

[コマンドラインツール](/docs/cli) を毎日またはスクリプトで使うようになったら役立つ 3 つのことです。それぞれ、[SDK](/docs/sdks) や API を使ってコードで同じことをする方法も示します。

## 複数のアカウント：プロファイル

`apidly login --profile NAME` は、既定のキーとは別に、名前を付けてキーを保存します。1 つのコマンドでプロファイルを選ぶには `--profile NAME` か環境変数 `APIDLY_PROFILE` を使い、既定にするには `apidly config use NAME` を使います。`apidly config profiles` でプロファイルを一覧表示し、`apidly config profiles rm NAME` で 1 つ削除します。`APIDLY_API_KEY` が設定されていると、保存済みのどのプロファイルよりも優先されます。

```bash
apidly login --profile work
apidly config profiles
apidly servers --profile work
APIDLY_PROFILE=work apidly balance
apidly config use work
apidly config profiles rm work
```

コードにはプロファイルはありません。キーごとに別のクライアントになります。キーはそれぞれ専用の環境変数に入れ、コードには書かないでください。

```bash
curl "https://apidly.com/api/v1/me" \
  -H "Authorization: Bearer $APIDLY_WORK_KEY"
```

```js
import { Apidly } from "@apidly/sdk";

const personal = new Apidly({ apiKey: process.env.APIDLY_API_KEY });
const work = new Apidly({ apiKey: process.env.APIDLY_WORK_KEY });
console.log((await work.billing.balance()).balance);
console.log((await personal.billing.balance()).balance);
```

```python
import os
from apidly import Client

personal = Client(api_key=os.environ["APIDLY_API_KEY"])
work = Client(api_key=os.environ["APIDLY_WORK_KEY"])
print(work.billing.balance()["balance"])
print(personal.billing.balance()["balance"])
```

## CLI を更新する

`apidly update` は新しいバージョンを探し、このサイトからダウンロードしてチェックサムを確認し、確認のうえ npm でインストールします。`--check` は報告だけを行い、新しいバージョンがあると終了コード `3` を返すので CI のステップに向いています。`--print` はコマンドを実行せずに表示します。現在のバージョンと各ファイルのチェックサムは `latest.json` にもあります。

```bash
apidly --version
apidly update --check
apidly update --print
apidly update --yes

curl -fsS "https://apidly.com/downloads/latest.json" | jq -r '.version'
```

```js
const res = await fetch("https://apidly.com/downloads/latest.json");
const latest = await res.json();
const cli = latest.files.find((f) => f.kind === "cli");
console.log(latest.version, cli.name, cli.sha256);
```

```python
import json
import urllib.request

with urllib.request.urlopen("https://apidly.com/downloads/latest.json") as res:
    latest = json.load(res)
cli = next(f for f in latest["files"] if f["kind"] == "cli")
print(latest["version"], cli["name"], cli["sha256"])
```

## スクリプトでサーバーを待つ

`apidly servers wait ID` は、サーバーが起動すると終了コード `0` で、起動できないとき（起動に失敗した場合など）は `1` で終了します。`--for stopped` や `--for destroyed` でそれらの状態を待ち、`--timeout` で指定した秒数が過ぎるとあきらめます（既定は 600）。`apidly deploy --wait` と `apidly stop --wait` は同じコマンド内で待ちます。Ctrl-C で待機を終えると終了コードは `130` で、サーバーはそのままです。API では、数秒ごとにサーバーの `status` を読み取ります。

```bash
apidly servers wait ins_ID
apidly servers wait ins_ID --for stopped --timeout 300
apidly deploy --plan rtx-4090-1x --template pytorch --yes --wait
apidly stop ins_ID --wait

until [ "$(curl -fsS "https://apidly.com/api/v1/servers/ins_ID" \
  -H "Authorization: Bearer $APIDLY_API_KEY" | jq -r '.server.status')" = running ]; do
  sleep 5
done
```

```js
import { Apidly } from "@apidly/sdk";

const apidly = new Apidly({ apiKey: process.env.APIDLY_API_KEY });
for (;;) {
  const { server } = await apidly.servers.get("ins_ID");
  if (server.status === "running") break;
  if (server.status === "error" || server.status === "destroyed") {
    throw new Error(server.statusMessage ?? server.status);
  }
  await new Promise((r) => setTimeout(r, 5000));
}
```

```python
import os
import time
from apidly import Client

client = Client(api_key=os.environ["APIDLY_API_KEY"])
while True:
    server = client.servers.get("ins_ID")["server"]
    if server["status"] == "running":
        break
    if server["status"] in ("error", "destroyed"):
        raise SystemExit(server.get("statusMessage") or server["status"])
    time.sleep(5)
```
