"""Добавляет сенсоры Proxmox в существующий блок rest: и секрет в secrets.yaml.""" import io import json import re CFG = "/opt/smart-lxc/homeassistant/config/configuration.yaml" SEC = "/opt/smart-lxc/homeassistant/config/secrets.yaml" TOK = open("/tmp/pve-token", encoding="utf-8").read().strip() # 1. секрет hdr = f"PVEAPIToken=monitoring@pve!ha-token={TOK}" sec = open(SEC, encoding="utf-8").read() if __import__("os").path.exists(SEC) else "" if "pve_token_header" not in sec: with open(SEC, "a", encoding="utf-8") as f: f.write(('' if sec.endswith("\n") or not sec else "\n") + f'pve_token_header: "{hdr}"\n') print(" секрет добавлен") else: print(" секрет уже есть") # 2. блок сенсоров block = ''' - resource: https://192.168.1.10:8006/api2/json/nodes/pve/status verify_ssl: false headers: Authorization: !secret pve_token_header scan_interval: 60 sensor: - name: "Proxmox CPU" unique_id: proxmox_node_cpu value_template: "{{ (value_json.data.cpu * 100) | round(1) }}" unit_of_measurement: "%" - name: "Proxmox RAM" unique_id: proxmox_node_ram value_template: "{{ ((value_json.data.memory.used / value_json.data.memory.total) * 100) | round(1) }}" unit_of_measurement: "%" - name: "Proxmox RAM занято" unique_id: proxmox_node_ram_gb value_template: "{{ (value_json.data.memory.used / 1073741824) | round(1) }}" unit_of_measurement: "ГБ" - name: "Proxmox Uptime" unique_id: proxmox_node_uptime value_template: "{{ (value_json.data.uptime / 3600) | round(1) }}" unit_of_measurement: "ч" - name: "Proxmox диск занято" unique_id: proxmox_storage_used value_template: "{{ (value_json.data.rootfs.used / 1073741824) | round(1) }}" unit_of_measurement: "ГБ" ''' lines = open(CFG, encoding="utf-8").read().splitlines() if False else open(CFG, encoding="utf-8").read().split("\n") if "proxmox_node_cpu" in "\n".join(lines): print(" сенсоры уже есть") raise SystemExit(0) # находим начало rest: start = None for i, line in enumerate(lines): if re.match(r"^rest:\s*$", line): start = i break if start is None: with open(CFG, "a", encoding="utf-8") as f: f.write("\nrest:\n" + block) print(" создан новый блок rest:") else: end = len(lines) for j in range(start + 1, len(lines)): if lines[j] and not lines[j].startswith((" ", "\t")) and not lines[j].startswith("#"): end = j break lines[end:end] = block.split("\n") open(CFG, "w", encoding="utf-8").write("\n".join(lines)) print(f" сенсоры вставлены в блок rest: (строки {start+1}..{end})") import yaml # noqa: E402 yaml.safe_load(open(CFG, encoding="utf-8").read().replace("!secret", "")) print(" YAML валиден")