# CLI 프로필, 업데이트, 기다리기

[명령줄 도구](/docs/cli)를 매일 또는 스크립트에서 쓸 때 도움이 되는 세 가지입니다. 각각 [SDK](/docs/sdks)나 API로 코드에서 같은 일을 하는 방법도 보여 줍니다.

## 여러 계정: 프로필

`apidly login --profile NAME`은 기본 키 옆에 이름을 붙여 키를 저장합니다. 명령 하나에 쓸 프로필은 `--profile NAME`이나 환경 변수 `APIDLY_PROFILE`로 고르고, 기본으로 만들려면 `apidly config use NAME`을 쓰세요. `apidly config profiles`는 프로필을 나열하고 `apidly config profiles rm NAME`은 하나를 지웁니다. `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)
```
