ci: trigger ping

This commit is contained in:
root authored and moham committed 2025-09-17 17:26:10 +02:00
1 parent 69568f545a
commit 795dc342d3
3 files changed
+80 -13

No files matched your search

+60 -13
View File
@@ -1,6 +1,6 @@
import os, subprocess, shlex, uuid, time, hashlib, pathlib, json
from datetime import datetime
from flask import Flask, render_template, request, redirect, url_for, flash, Response, jsonify, send_from_directory
from flask import Flask, render_template, request, redirect, url_for, flash, Response, jsonify
from werkzeug.utils import secure_filename
import yaml
import config
@@ -8,11 +8,20 @@ import config
app = Flask(__name__)
app.secret_key = config.SECRET_KEY
# Expose DRY_RUN in config and templates
app.config["DRY_RUN"] = config.DRY_RUN
@app.context_processor
def inject_flags():
# Available in templates: {{ DRY_RUN }}
return {"DRY_RUN": app.config["DRY_RUN"]}
JOBS = {}
def _human(n):
for u in ['B','KB','MB','GB','TB']:
if n < 1024: return f"{n:.0f} {u}"
if n < 1024:
return f"{n:.0f} {u}"
n /= 1024
return f"{n:.0f} PB"
@@ -21,7 +30,8 @@ def _sha256(fp, chunk=8192):
with open(fp, 'rb') as f:
while True:
b = f.read(chunk)
if not b: break
if not b:
break
h.update(b)
return h.hexdigest()
@@ -52,7 +62,11 @@ def _scan_playbooks(root, q=None, sort='mtime'):
"mtime_h": datetime.fromtimestamp(stat.st_mtime).strftime("%Y-%m-%d %H:%M"),
"sha256": _sha256(str(file))[:64],
})
key = {"mtime": lambda x: -x["mtime"], "name": lambda x: x["name"].lower(), "size": lambda x: -x["size"]}.get(sort, lambda x: -x["mtime"])
key = {
"mtime": lambda x: -x["mtime"],
"name": lambda x: x["name"].lower(),
"size": lambda x: -x["size"]
}.get(sort, lambda x: -x["mtime"])
grouped = {}
for row in sorted(rows, key=key):
grouped.setdefault(row["domain"], []).append(row)
@@ -112,34 +126,65 @@ def api_run_start(domain, name):
full = os.path.join(config.PLAYBOOK_ROOT, rel)
if not os.path.isfile(full):
return jsonify({"error": "not found"}), 404
# Params from UI
extra_vars = (request.form.get("extra_vars") or "").strip()
check = request.form.get("check") == "yes"
vvv = request.form.get("vvv") or "-vvv"
check_from_form = request.form.get("check") == "yes"
# Global DRY-RUN forces --check and adds --diff
is_check = config.DRY_RUN or check_from_form
diff_flag = " --diff" if is_check else ""
# Auto-start ansible service (canary) if stopped
try:
subprocess.run(
["docker", "compose", "-f", config.DOCKER_COMPOSE_FILE, "up", "-d", config.ANSIBLE_SERVICE],
check=False, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
)
except Exception:
pass
if config.RUN_MODE == "docker":
playbook_in_container = f"/runner/project/{rel}"
shell = f'ANSIBLE_CONFIG={shlex.quote(config.ANSIBLE_CONFIG_IN_CONTAINER)} ansible-playbook {shlex.quote(playbook_in_container)} {vvv}'
if check: shell += " --check"
shell = (
f'ANSIBLE_CONFIG={shlex.quote(config.ANSIBLE_CONFIG_IN_CONTAINER)} '
f'ansible-playbook {shlex.quote(playbook_in_container)} {vvv}'
)
if is_check:
shell += " --check" + diff_flag
if extra_vars:
shell += f" --extra-vars {shlex.quote(extra_vars)}"
cmd = ["docker","compose","-f",config.DOCKER_COMPOSE_FILE,"exec","-T",config.ANSIBLE_SERVICE,"bash","-lc", shell]
cmd = [
"docker", "compose", "-f", config.DOCKER_COMPOSE_FILE, "exec", "-T",
config.ANSIBLE_SERVICE, "bash", "-lc", shell
]
else:
shell = f'ansible-playbook {shlex.quote(full)} {vvv}'
if check: shell += " --check"
if is_check:
shell += " --check" + diff_flag
if extra_vars:
shell += f" --extra-vars {shlex.quote(extra_vars)}"
cmd = ["bash", "-lc", shell]
job_id = uuid.uuid4().hex[:12]
log_path = os.path.join(config.JOB_LOG_DIR, f"{job_id}.log")
with open(log_path, "w") as lf:
lf.write(f"$ {' '.join(cmd)}\n\n")
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1, universal_newlines=True)
prefix = "[DRY-RUN] " if config.DRY_RUN else ""
lf.write(f"$ {prefix}{' '.join(cmd)}\n\n")
proc = subprocess.Popen(
cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
text=True, bufsize=1, universal_newlines=True
)
JOBS[job_id] = {"proc": proc, "log_path": log_path, "started": time.time()}
return jsonify({"job_id": job_id})
@app.get("/api/stream/<job_id>")
def api_stream(job_id):
job = JOBS.get(job_id)
if not job: return Response("not found", status=404)
if not job:
return Response("not found", status=404)
def generate():
proc = job["proc"]
with open(job["log_path"], "a+") as lf:
@@ -149,10 +194,12 @@ def api_stream(job_id):
if proc.poll() is not None:
yield f"data: [Exit code {proc.returncode}]\n\n"
break
time.sleep(0.05); continue
time.sleep(0.05)
continue
lf.write(line)
lf.flush()
yield f"data: {line.rstrip()}\n\n"
return Response(generate(), mimetype="text/event-stream")
if __name__ == "__main__":
+12
View File
@@ -1,12 +1,24 @@
import os
# Emplacements / exécution
PLAYBOOK_ROOT = os.environ.get("PLAYBOOK_ROOT", "/runner/project")
RUN_MODE = os.environ.get("RUN_MODE", "docker")
DOCKER_COMPOSE_FILE = os.environ.get("DOCKER_COMPOSE_FILE", "/srv/clients/ephapoc/ansible/docker-compose.yml")
ANSIBLE_SERVICE = os.environ.get("ANSIBLE_SERVICE", "ansible")
ANSIBLE_CONFIG_IN_CONTAINER = os.environ.get("ANSIBLE_CONFIG_IN_CONTAINER", "/runner/ansible.cfg")
# Sécurité / admin
ADMIN_TOKEN = os.environ.get("ADMIN_TOKEN", "CHANGE_ME")
REQUIRE_ADMIN_TOKEN = os.environ.get("ADMIN_TOKEN_PROMPT", "1").lower() not in {"0", "false", "no", "off"}
# Filtres & logs
ALLOWED_EXT = {".yml", ".yaml"}
JOB_LOG_DIR = os.environ.get("JOB_LOG_DIR", "/tmp/ansible_jobs")
os.makedirs(JOB_LOG_DIR, exist_ok=True)
# Flask
SECRET_KEY = os.environ.get("FLASK_SECRET_KEY", "dev-key-not-secure")
# --- DRY-RUN global (canary/dev) ------------------------------------
# Active le mode "simulation" (ansible --check --diff) si IHM_DRY_RUN=1/true/on
DRY_RUN = str(os.environ.get("IHM_DRY_RUN", "0")).lower() in {"1", "true", "yes", "on"}
+8
View File
@@ -7,6 +7,14 @@
<link rel="stylesheet" href="{{ url_for('static', filename='app.css') }}">
</head>
<body>
{% if DRY_RUN %}
<div style="position:sticky;top:0;z-index:1000;background:#fff3cd;color:#664d03;
border-bottom:1px solid #ffe69c;padding:.5rem 1rem;font-weight:600;">
⚠️ Environnement CANARY — <strong>DRY-RUN activé</strong> (ansible exécuté avec <code>--check --diff</code>)
</div>
{% endif %}
<div class="header">
<h1>🧰 IHM Playbooks</h1>
<div class="nav">