来源仓库:jxc/ai-fresh-delivery 来源提交:f0b1a180e2deb7e4673b9d1c8542619f7bc0f73d 快照树: 09f679334ff38f0ff25e907961c94a8223bcaedd(与来源 HEAD 工作树逐字节一致,3801 个文件) 按约定本仓库不带任何历史提交:来源仓库的历史中含真实凭据 (生产 SSH 私钥 deploy/id_rsa_tencent、server/.env、.env.tencent/.env.production/.env.gitea、 deploy/小程序AppSecret.txt,其中 MP_APPSECRET / S3 AccessKey 经哈希比对与线上同值), 整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。 供应商系统后续开发自本提交开始。
192 lines
6.1 KiB
Python
192 lines
6.1 KiB
Python
#!/usr/bin/env python3
|
|
"""Create Semaphore project + inventory + templates via API."""
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import os
|
|
import sys
|
|
import urllib.error
|
|
import urllib.request
|
|
from pathlib import Path
|
|
|
|
BASE = os.environ.get("SEMAPHORE_URL", "http://127.0.0.1:3010").rstrip("/")
|
|
ENV_FILE = Path(os.environ.get("SEMAPHORE_ENV", "/opt/semaphore/.env"))
|
|
SSH_KEY_PATH = Path(os.environ.get("SEMAPHORE_SSH_KEY", "/opt/semaphore/ssh/id_rsa"))
|
|
INV_PATH = Path(os.environ.get("SEMAPHORE_INV", "/opt/semaphore/ansible/inventory/hosts.ini"))
|
|
|
|
|
|
def load_password() -> str:
|
|
for line in ENV_FILE.read_text(encoding="utf-8").splitlines():
|
|
if line.startswith("SEMAPHORE_ADMIN_PASSWORD="):
|
|
return line.split("=", 1)[1].strip()
|
|
raise SystemExit(f"SEMAPHORE_ADMIN_PASSWORD not found in {ENV_FILE}")
|
|
|
|
|
|
class Client:
|
|
def __init__(self, base: str):
|
|
self.base = base
|
|
self.cookie = ""
|
|
|
|
def request(self, method: str, path: str, body: dict | None = None):
|
|
data = None
|
|
headers = {"Content-Type": "application/json"}
|
|
if self.cookie:
|
|
headers["Cookie"] = self.cookie
|
|
if body is not None:
|
|
data = json.dumps(body).encode("utf-8")
|
|
req = urllib.request.Request(self.base + path, data=data, headers=headers, method=method)
|
|
try:
|
|
with urllib.request.urlopen(req, timeout=60) as resp:
|
|
raw = resp.read().decode("utf-8") or "null"
|
|
set_cookie = resp.headers.get("Set-Cookie")
|
|
if set_cookie:
|
|
self.cookie = set_cookie.split(";", 1)[0]
|
|
if raw == "null" or not raw.strip():
|
|
return None
|
|
return json.loads(raw)
|
|
except urllib.error.HTTPError as e:
|
|
err = e.read().decode("utf-8", errors="replace")
|
|
raise SystemExit(f"{method} {path} -> HTTP {e.code}: {err}") from e
|
|
|
|
def login(self, password: str):
|
|
self.request("POST", "/api/auth/login", {"auth": "admin", "password": password})
|
|
|
|
|
|
def find_by_name(items: list, name: str):
|
|
for it in items or []:
|
|
if it.get("name") == name:
|
|
return it
|
|
return None
|
|
|
|
|
|
def main() -> int:
|
|
password = load_password()
|
|
c = Client(BASE)
|
|
print(f"Login {BASE}")
|
|
c.login(password)
|
|
|
|
projects = c.request("GET", "/api/projects") or []
|
|
proj = find_by_name(projects, "canteen-prod")
|
|
if not proj:
|
|
proj = c.request(
|
|
"POST",
|
|
"/api/projects",
|
|
{"name": "canteen-prod", "alert": False},
|
|
)
|
|
print("Created project", proj["id"])
|
|
else:
|
|
print("Using project", proj["id"])
|
|
pid = proj["id"]
|
|
|
|
keys = c.request("GET", f"/api/project/{pid}/keys") or []
|
|
key = find_by_name(keys, "prod-ssh")
|
|
if not key:
|
|
priv = SSH_KEY_PATH.read_text(encoding="utf-8")
|
|
key = c.request(
|
|
"POST",
|
|
f"/api/project/{pid}/keys",
|
|
{
|
|
"name": "prod-ssh",
|
|
"type": "ssh",
|
|
"project_id": pid,
|
|
"ssh": {"login": "", "passphrase": "", "private_key": priv},
|
|
},
|
|
)
|
|
print("Created ssh key", key.get("id"))
|
|
else:
|
|
print("Using ssh key", key["id"])
|
|
kid = key["id"]
|
|
|
|
invs = c.request("GET", f"/api/project/{pid}/inventory") or []
|
|
inv = find_by_name(invs, "prod-hosts")
|
|
inventory_text = INV_PATH.read_text(encoding="utf-8")
|
|
if not inv:
|
|
inv = c.request(
|
|
"POST",
|
|
f"/api/project/{pid}/inventory",
|
|
{
|
|
"name": "prod-hosts",
|
|
"project_id": pid,
|
|
"type": "static",
|
|
"inventory": inventory_text,
|
|
"ssh_key_id": kid,
|
|
},
|
|
)
|
|
print("Created inventory", inv["id"])
|
|
else:
|
|
print("Using inventory", inv["id"])
|
|
iid = inv["id"]
|
|
|
|
repos = c.request("GET", f"/api/project/{pid}/repositories") or []
|
|
repo = find_by_name(repos, "local-ansible")
|
|
if not repo:
|
|
repo = c.request(
|
|
"POST",
|
|
f"/api/project/{pid}/repositories",
|
|
{
|
|
"name": "local-ansible",
|
|
"project_id": pid,
|
|
"git_url": "file:///ansible",
|
|
"git_branch": "master",
|
|
"ssh_key_id": kid,
|
|
},
|
|
)
|
|
print("Created repository", repo["id"])
|
|
else:
|
|
print("Using repository", repo["id"])
|
|
rid = repo["id"]
|
|
|
|
envs = c.request("GET", f"/api/project/{pid}/environment") or []
|
|
env = find_by_name(envs, "default")
|
|
if not env:
|
|
env = c.request(
|
|
"POST",
|
|
f"/api/project/{pid}/environment",
|
|
{
|
|
"name": "default",
|
|
"project_id": pid,
|
|
"json": "{}",
|
|
"env": "{}",
|
|
},
|
|
)
|
|
print("Created environment", env["id"])
|
|
else:
|
|
print("Using environment", env["id"])
|
|
eid = env["id"]
|
|
|
|
templates = [
|
|
("\u5065\u5eb7\u5de1\u68c0", "playbooks/health_check.yml"),
|
|
("\u91cd\u542f API", "playbooks/restart_api.yml"),
|
|
("\u91cd\u542f Nginx", "playbooks/restart_nginx.yml"),
|
|
("\u90e8\u7f72\u540e\u7aef", "playbooks/deploy_backend.yml"),
|
|
("\u90e8\u7f72\u524d\u7aef", "playbooks/deploy_frontend.yml"),
|
|
("\u67e5\u770b\u8def\u5f84", "playbooks/inspect_path.yml"),
|
|
]
|
|
existing = c.request("GET", f"/api/project/{pid}/templates") or []
|
|
for name, playbook in templates:
|
|
if find_by_name(existing, name):
|
|
print("Template exists:", name)
|
|
continue
|
|
c.request(
|
|
"POST",
|
|
f"/api/project/{pid}/templates",
|
|
{
|
|
"name": name,
|
|
"project_id": pid,
|
|
"inventory_id": iid,
|
|
"repository_id": rid,
|
|
"environment_id": eid,
|
|
"playbook": playbook,
|
|
"app": "ansible",
|
|
"type": "",
|
|
},
|
|
)
|
|
print("Created template:", name)
|
|
|
|
print("Done. Open", BASE)
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|