-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
1096 lines (997 loc) · 53 KB
/
main.py
File metadata and controls
1096 lines (997 loc) · 53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
import os
import io
import time
import socket
from datetime import datetime, timezone
from typing import List, Optional, Dict, Any, Tuple
from flask import Flask, request, jsonify, Response
import boto3
from botocore.exceptions import ClientError, NoCredentialsError, ProfileNotFound
import paramiko # SSH backend
# ========= Config =========
FORCED_REGION = "us-east-1"
APP_PORT = int(os.getenv("PORT", "8080"))
SSH_CONNECT_TIMEOUT = 20
SSH_COMMAND_TIMEOUT = 3600 # 1h
DEFAULT_VOLUME_GB = 20
UBUNTU_OWNER = "099720109477" # Canonical
AMAZON_OWNER = "137112412989" # Amazon Linux
app = Flask(__name__)
# ========= Helpers Boto3 =========
def make_session(profile: Optional[str] = None):
try:
return boto3.Session(profile_name=profile, region_name=FORCED_REGION)
except ProfileNotFound as e:
raise e
def ec2_client(session):
return session.client("ec2")
def get_name_tag(tags: Optional[List[Dict[str, str]]]) -> str:
if not tags:
return ""
for t in tags:
if t.get("Key") == "Name":
return t.get("Value", "")
return ""
def fmt_time_utc(dt: Any) -> str:
if isinstance(dt, datetime):
return dt.astimezone(timezone.utc).strftime("%Y-%m-%d %H:%M:%S %Z")
return ""
def list_instances(session, states: Optional[List[str]] = None) -> List[Dict[str, Any]]:
client = ec2_client(session)
filters = []
if states:
filters.append({"Name": "instance-state-name", "Values": states})
paginator = client.get_paginator("describe_instances")
out: List[Dict[str, Any]] = []
for page in paginator.paginate(Filters=filters) if filters else paginator.paginate():
for r in page.get("Reservations", []):
for i in r.get("Instances", []):
out.append({
"InstanceId": i["InstanceId"],
"State": i["State"]["Name"],
"Name": get_name_tag(i.get("Tags")),
"Type": i.get("InstanceType", ""),
"AZ": i.get("Placement", {}).get("AvailabilityZone", ""),
"PublicIp": i.get("PublicIpAddress", "") or "",
"PrivateIp": i.get("PrivateIpAddress", "") or "",
"LaunchTime": fmt_time_utc(i.get("LaunchTime")),
"Region": FORCED_REGION,
"Platform": i.get("Platform", "") or i.get("PlatformDetails", ""),
})
state_order = {"running": 0, "pending": 1, "stopping": 2, "stopped": 3, "shutting-down": 4, "terminated": 5}
out.sort(key=lambda x: (state_order.get(x["State"], 99), (x["Name"] or "").lower(), x["InstanceId"]))
return out
def get_instance_public_ip(session, instance_id: str) -> Tuple[str, str]:
client = ec2_client(session)
resp = client.describe_instances(InstanceIds=[instance_id])
resv = resp.get("Reservations", [])
if not resv or not resv[0].get("Instances"):
raise ValueError("Instance not found")
inst = resv[0]["Instances"][0]
state = inst["State"]["Name"]
ip = inst.get("PublicIpAddress") or ""
return ip, state
def apply_action(session, action: str, ids: List[str], wait: bool = False) -> Dict[str, Any]:
client = ec2_client(session)
if not ids:
raise ValueError("No instance IDs provided")
if action == "start":
client.start_instances(InstanceIds=ids)
if wait:
client.get_waiter("InstanceRunning").wait(InstanceIds=ids)
elif action == "stop":
client.stop_instances(InstanceIds=ids)
if wait:
client.get_waiter("InstanceStopped").wait(InstanceIds=ids)
elif action == "reboot":
client.reboot_instances(InstanceIds=ids)
elif action == "terminate":
client.terminate_instances(InstanceIds=ids)
if wait:
client.get_waiter("InstanceTerminated").wait(InstanceIds=ids)
else:
raise ValueError("Unknown action")
return {"status": "ok", "action": action, "ids": ids}
# ========= AMI helpers (latest) =========
def latest_ami(session, os_family: str) -> str:
"""
os_family: 'al2023' or 'ubuntu-24-04'
Returns AMI ID string.
"""
client = ec2_client(session)
if os_family == "al2023":
owners = [AMAZON_OWNER]
filters = [
{"Name": "name", "Values": ["al2023-ami-*-x86_64"]},
{"Name": "state", "Values": ["available"]},
{"Name": "architecture", "Values": ["x86_64"]},
{"Name": "root-device-type", "Values": ["ebs"]},
{"Name": "virtualization-type", "Values": ["hvm"]},
]
elif os_family == "ubuntu-24-04":
owners = [UBUNTU_OWNER]
filters = [
{"Name": "name", "Values": ["ubuntu/images/hvm-ssd/ubuntu-noble-24.04-amd64-server-*"]},
{"Name": "state", "Values": ["available"]},
{"Name": "architecture", "Values": ["x86_64"]},
{"Name": "root-device-type", "Values": ["ebs"]},
{"Name": "virtualization-type", "Values": ["hvm"]},
]
else:
raise ValueError("Unsupported os_family")
imgs = client.describe_images(Owners=owners, Filters=filters).get("Images", [])
if not imgs:
raise ValueError("No AMI found for requested OS")
imgs.sort(key=lambda x: x.get("CreationDate", ""), reverse=True)
return imgs[0]["ImageId"]
# ========= KeyPair helpers =========
def list_key_pairs(session) -> List[Dict[str, Any]]:
client = ec2_client(session)
resp = client.describe_key_pairs()
out = []
for kp in resp.get("KeyPairs", []):
out.append({
"KeyName": kp.get("KeyName"),
"KeyPairId": kp.get("KeyPairId"),
"KeyType": kp.get("KeyType"),
})
out.sort(key=lambda x: (x["KeyName"] or "").lower())
return out
@app.get("/api/keypairs")
def api_keypairs_list():
try:
session = make_session()
items = list_key_pairs(session)
return jsonify({"region": FORCED_REGION, "keypairs": items})
except (ClientError, NoCredentialsError, ProfileNotFound) as e:
return jsonify({"error": str(e)}), 400
@app.post("/api/keypairs/import")
def api_keypairs_import():
try:
data = request.get_json(force=True)
except Exception:
return jsonify({"error": "Invalid JSON"}), 400
key_name = (data.get("key_name") or "").strip()
pub = (data.get("public_key_material") or "").strip()
if not key_name or not pub:
return jsonify({"error": "key_name and public_key_material required"}), 400
try:
session = make_session()
client = ec2_client(session)
resp = client.import_key_pair(KeyName=key_name, PublicKeyMaterial=pub.encode("utf-8"))
return jsonify({
"status": "ok",
"key_name": resp.get("KeyName"),
"key_pair_id": resp.get("KeyPairId"),
"key_type": resp.get("KeyType"),
})
except ClientError as e:
return jsonify({"error": str(e)}), 400
# ========= Security Group helpers =========
def list_security_groups(session, vpc_id: Optional[str] = None) -> List[Dict[str, Any]]:
client = ec2_client(session)
filters = []
if vpc_id:
filters.append({"Name": "vpc-id", "Values": [vpc_id]})
resp = client.describe_security_groups(Filters=filters) if filters else client.describe_security_groups()
out = []
for sg in resp.get("SecurityGroups", []):
out.append({
"GroupId": sg.get("GroupId"),
"GroupName": sg.get("GroupName"),
"Description": sg.get("Description"),
"VpcId": sg.get("VpcId"),
})
out.sort(key=lambda x: (x["GroupName"] or "").lower())
return out
@app.get("/api/security-groups")
def api_security_groups():
vpc_id = request.args.get("vpc_id") or None
try:
session = make_session()
items = list_security_groups(session, vpc_id=vpc_id)
return jsonify({"region": FORCED_REGION, "security_groups": items})
except (ClientError, NoCredentialsError, ProfileNotFound) as e:
return jsonify({"error": str(e)}), 400
# ========= SSH helpers =========
def _load_private_key(pem_text: str) -> paramiko.PKey:
pem = pem_text.strip().encode()
exc = None
for cls in (paramiko.RSAKey, paramiko.Ed25519Key, paramiko.ECDSAKey):
try:
return cls.from_private_key(io.StringIO(pem.decode()))
except Exception as e:
exc = e
raise ValueError(f"Invalid or unsupported private key format: {exc}")
def ssh_run_command(host: str, username: str, key_pem: str, command: str) -> Dict[str, Any]:
key = _load_private_key(key_pem)
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
client.connect(
hostname=host,
username=username,
pkey=key,
timeout=SSH_CONNECT_TIMEOUT,
banner_timeout=SSH_CONNECT_TIMEOUT,
auth_timeout=SSH_CONNECT_TIMEOUT,
)
stdin, stdout, stderr = client.exec_command(
f"bash -lc 'cat <<\"EOF\" | bash\n{command}\nEOF'",
timeout=SSH_COMMAND_TIMEOUT
)
out = stdout.read()
err = stderr.read()
if isinstance(out, bytes): out = out.decode("utf-8", errors="replace")
if isinstance(err, bytes): err = err.decode("utf-8", errors="replace")
exit_code = stdout.channel.recv_exit_status()
return {"stdout": out, "stderr": err, "exit_code": exit_code}
except (paramiko.SSHException, socket.error, socket.timeout) as e:
raise RuntimeError(f"SSH error: {e}")
finally:
try: client.close()
except Exception: pass
def build_git_script(git_url: str, workdir: str, post_cmd: str) -> str:
workdir = workdir or "/opt/app"
post_cmd = post_cmd or ""
return """set -e
GIT_URL="{git_url}"
WORKDIR="{workdir}"
POST_CMD="{post_cmd}"
if command -v apt-get >/dev/null 2>&1; then sudo apt-get update -y && sudo apt-get install -y git;
elif command -v yum >/dev/null 2>&1; then sudo yum install -y git;
elif command -v dnf >/dev/null 2>&1; then sudo dnf install -y git;
elif command -v microdnf >/dev/null 2>&1; then sudo microdnf install -y git;
else echo "No known package manager found" >&2; fi
sudo mkdir -p "$WORKDIR"
sudo chown $(whoami):$(id -gn) "$WORKDIR"
cd "$WORKDIR"
REPO_NAME="$(basename -s .git "$GIT_URL")"; [ -z "$REPO_NAME" ] && REPO_NAME="app"
if [ -d "$REPO_NAME/.git" ]; then
cd "$REPO_NAME" && git pull --rebase
else
rm -rf "$REPO_NAME"
git clone "$GIT_URL" "$REPO_NAME"
cd "$REPO_NAME"
fi
[ -n "$POST_CMD" ] && eval "$POST_CMD"
""".format(git_url=git_url.replace('"', '\\"'),
workdir=workdir.replace('"', '\\"'),
post_cmd=post_cmd.replace('"', '\\"'))
# ========= cloud-init (user-data) =========
def build_user_data(os_family: str, git_url: str, workdir: str, post_cmd: str) -> str:
"""
Cloud-init minimal, pas d'injection de clé publique.
Installe git si URL fournie, clone et exécute post_cmd en root (ou sudo -u vers user par défaut détecté).
"""
workdir = workdir or "/opt/app"
git_url = git_url or ""
post_cmd = post_cmd or ""
boot_script = f"""#!/bin/bash
set -euxo pipefail
# Détecte l'utilisateur système par défaut (ec2-user / ubuntu), fallback root
OS_USER="root"
if id -u ec2-user >/dev/null 2>&1; then OS_USER="ec2-user";
elif id -u ubuntu >/dev/null 2>&1; then OS_USER="ubuntu"; fi
# Paquets
if command -v apt-get >/dev/null 2>&1; then
export DEBIAN_FRONTEND=noninteractive
apt-get update -y
apt-get install -y git
elif command -v yum >/dev/null 2>&1; then
yum install -y git
elif command -v dnf >/dev/null 2>&1; then
dnf install -y git
fi
mkdir -p "{workdir}"
chown "$OS_USER":"$OS_USER" "{workdir}"
if [ -n "{git_url}" ]; then
sudo -u "$OS_USER" bash -lc '
cd "{workdir}";
REPO_NAME="$(basename -s .git "{git_url}")"; [ -z "$REPO_NAME" ] && REPO_NAME="app";
if [ -d "$REPO_NAME/.git" ]; then
cd "$REPO_NAME" && git pull --rebase;
else
rm -rf "$REPO_NAME";
git clone "{git_url}" "$REPO_NAME";
cd "$REPO_NAME";
fi
[ -n "{post_cmd}" ] && eval "{post_cmd}"
'
fi
"""
cloud_cfg = f"""#cloud-config
write_files:
- path: /var/local/bootstrap.sh
permissions: '0755'
owner: root:root
content: |
{chr(10).join(' ' + line for line in boot_script.splitlines())}
runcmd:
- /var/local/bootstrap.sh
"""
return cloud_cfg
# ========= API =========
@app.get("/api/instances")
def api_instances():
states_raw = request.args.get("states")
q = (request.args.get("q") or "").strip().lower()
states = [s.strip() for s in states_raw.split(",")] if states_raw else None
try:
session = make_session()
items = list_instances(session, states=states)
if q:
def match(it):
return (q in (it["InstanceId"] or "").lower()
or q in (it["Name"] or "").lower()
or q in (it["PublicIp"] or "").lower()
or q in (it["PrivateIp"] or "").lower())
items = [it for it in items if match(it)]
return jsonify({"region": FORCED_REGION, "instances": items})
except (ClientError, NoCredentialsError, ProfileNotFound) as e:
return jsonify({"error": str(e)}), 400
@app.post("/api/action")
def api_action():
try:
data = request.get_json(force=True)
action = data.get("action")
ids = data.get("ids") or []
wait = bool(data.get("wait", False))
session = make_session()
result = apply_action(session, action, ids, wait=wait)
return jsonify(result)
except (ClientError, NoCredentialsError, ProfileNotFound, ValueError) as e:
return jsonify({"error": str(e)}), 400
@app.post("/api/ssh/git")
def api_ssh_git():
try:
data = request.get_json(force=True)
except Exception:
return jsonify({"error": "Invalid JSON"}), 400
instance_id = (data.get("instance_id") or "").strip()
username = (data.get("username") or "").strip() or "ec2-user"
key_pem = (data.get("private_key_pem") or "").strip()
git_url = (data.get("git_url") or "").strip()
workdir = (data.get("workdir") or "/opt/app").strip()
post_cmd = (data.get("post_cmd") or "").strip()
if not instance_id or not key_pem or not git_url:
return jsonify({"error": "Missing required fields: instance_id, private_key_pem, git_url"}), 400
try:
session = make_session()
ip, state = get_instance_public_ip(session, instance_id)
if state != "running":
return jsonify({"error": f"Instance state is '{state}', must be 'running'"}), 400
if not ip:
return jsonify({"error": "Instance has no public IP"}), 400
script = build_git_script(git_url, workdir, post_cmd)
res = ssh_run_command(ip, username, key_pem, script)
return jsonify({
"status": "ok",
"host": ip,
"exit_code": res["exit_code"],
"stdout": res["stdout"][-8000:],
"stderr": res["stderr"][-8000:]
})
except ValueError as e:
return jsonify({"error": str(e)}), 400
except RuntimeError as e:
return jsonify({"error": str(e)}), 502
except (ClientError, NoCredentialsError, ProfileNotFound) as e:
return jsonify({"error": str(e)}), 400
# --- Create instance (avec SSH post-création optionnel) ---
@app.post("/api/instances/create")
def api_instances_create():
"""
Payload JSON:
{
"name": "my-app",
"os_family": "al2023" | "ubuntu-24-04",
"instance_type": "t3.micro",
"volume_gb": 20,
"subnet_id": "subnet-...",
"security_group_ids": ["sg-..."],
"associate_public_ip": true,
"key_name": "my-keypair", # optionnel (accès SSH)
"ssh_username": "ec2-user|ubuntu", # optionnel (déduit de l'OS sinon)
"git_url": "https://...repo.git", # optionnel
"workdir": "/opt/app",
"post_cmd": "bash setup.sh",
"ssh_after_create": true, # optionnel
"private_key_pem": "-----BEGIN PRIVATE KEY-----...", # requis si ssh_after_create
"wait": true
}
"""
try:
data = request.get_json(force=True)
except Exception:
return jsonify({"error": "Invalid JSON"}), 400
name = (data.get("name") or "").strip() or "ec2-app"
os_family = (data.get("os_family") or "al2023").strip()
instance_type = (data.get("instance_type") or "t3.micro").strip()
volume_gb = int(data.get("volume_gb") or DEFAULT_VOLUME_GB)
subnet_id = (data.get("subnet_id") or "").strip() or None
sg_ids = data.get("security_group_ids") or []
associate_public_ip = bool(data.get("associate_public_ip", True))
key_name = (data.get("key_name") or "").strip() or None
ssh_username = (data.get("ssh_username") or "").strip()
git_url = (data.get("git_url") or "").strip()
workdir = (data.get("workdir") or "/opt/app").strip()
post_cmd = (data.get("post_cmd") or "").strip()
ssh_after_create = bool(data.get("ssh_after_create", False))
private_key_pem = (data.get("private_key_pem") or "").strip()
wait_flag = bool(data.get("wait", True))
# Si on veut SSH post-création, il faut la clé privée
if ssh_after_create and not private_key_pem:
return jsonify({"error": "private_key_pem required when ssh_after_create is true"}), 400
try:
session = make_session()
ami_id = latest_ami(session, os_family=os_family)
user_data = build_user_data(os_family, git_url, workdir, post_cmd)
client = ec2_client(session)
block_device_mappings = [{
"DeviceName": "/dev/xvda",
"Ebs": {
"DeleteOnTermination": True,
"VolumeSize": volume_gb,
"VolumeType": "gp3",
"Encrypted": True
}
}]
network_interfaces = [{
"DeviceIndex": 0,
"AssociatePublicIpAddress": associate_public_ip,
"DeleteOnTermination": True,
}]
if subnet_id:
network_interfaces[0]["SubnetId"] = subnet_id
if sg_ids:
network_interfaces[0]["Groups"] = sg_ids
run_kwargs = dict(
ImageId=ami_id,
InstanceType=instance_type,
MinCount=1, MaxCount=1,
BlockDeviceMappings=block_device_mappings,
NetworkInterfaces=network_interfaces,
TagSpecifications=[{
"ResourceType": "instance",
"Tags": [{"Key": "Name", "Value": name}]
}],
UserData=user_data
)
if key_name:
run_kwargs["KeyName"] = key_name
resp = client.run_instances(**run_kwargs)
iid = resp["Instances"][0]["InstanceId"]
if wait_flag:
client.get_waiter("instance_running").wait(InstanceIds=[iid])
time.sleep(20) # Attente additionnelle pour le boot et cloud-init
ip, state = get_instance_public_ip(session, iid)
else:
ip, state = "", "pending"
ssh_result = None
if ssh_after_create and private_key_pem:
# Détermine l'utilisateur SSH si non fourni
default_user = "ec2-user" if os_family == "al2023" else "ubuntu"
ssh_user = (ssh_username or default_user).strip() or default_user
if state != "running" or not ip:
return jsonify({"error": "Instance not ready for SSH (no public IP or not running).", "instance_id": iid}), 400
script = build_git_script(git_url, workdir, post_cmd or "")
try:
ssh_result = ssh_run_command(ip, ssh_user, private_key_pem, script)
except RuntimeError as e:
ssh_result = {"error": str(e)}
return jsonify({
"status": "ok",
"instance_id": iid,
"state": state,
"public_ip": ip,
"ami_id": ami_id,
"ssh_post_create": ssh_after_create,
"ssh_result": ssh_result
})
except (ClientError, NoCredentialsError, ProfileNotFound, ValueError) as e:
return jsonify({"error": str(e)}), 400
# ========= Frontend (Tailwind + Flowbite) =========
INDEX_HTML = """<!doctype html>
<html lang="fr" class="h-full">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>EC2 Control · us-east-1</title>
<meta name="color-scheme" content="light dark" />
<script src="https://cdn.tailwindcss.com"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/flowbite/2.5.2/flowbite.min.css" rel="stylesheet" />
<script>
tailwind.config = {
theme: { extend: { boxShadow: { 'soft': '0 8px 30px rgba(0,0,0,0.06)' } } }
}
</script>
</head>
<body class="h-full bg-slate-50 text-slate-900">
<header class="sticky top-0 z-20 bg-white/80 backdrop-blur border-b border-slate-200">
<div class="max-w-7xl mx-auto px-4 py-3 flex items-center gap-3">
<div class="flex items-center gap-2">
<div class="h-8 w-8 rounded-xl bg-slate-900 text-white grid place-items-center font-bold">EC2</div>
<div class="text-xl font-semibold tracking-tight">Control Panel</div>
</div>
<div class="ml-auto flex items-center gap-2 text-sm text-slate-500">
<span>Region</span>
<span class="inline-flex items-center px-2 py-0.5 rounded-lg border border-slate-200 bg-white">us-east-1</span>
<button id="btn-create" type="button" class="ml-3 px-3 py-2 rounded-xl bg-emerald-600 text-white text-sm hover:bg-emerald-700">Créer une instance</button>
</div>
</div>
</header>
<main class="max-w-7xl mx-auto px-4 py-6 space-y-4">
<!-- Toolbar -->
<section class="grid md:grid-cols-12 gap-3">
<div class="md:col-span-4 bg-white shadow-soft border border-slate-200 rounded-2xl p-4">
<label class="block text-xs font-medium text-slate-500 mb-1">Recherche</label>
<div class="relative">
<input id="q" class="w-full rounded-xl bg-white border-slate-300 border p-2 pr-10" placeholder="ID, Name, IP..." />
<span class="absolute right-3 top-1/2 -translate-y-1/2 text-slate-400">⌘K</span>
</div>
<p class="mt-2 text-xs text-slate-500">Tape et appuie sur Entrée pour filtrer.</p>
</div>
<div class="md:col-span-3 bg-white shadow-soft border border-slate-200 rounded-2xl p-4">
<label class="block text-xs font-medium text-slate-500 mb-1">État</label>
<select id="states" class="w-full bg-white rounded-xl border-slate-300 border p-2">
<option value="">Tous</option>
<option value="running">running</option>
<option value="stopped">stopped</option>
<option value="pending">pending</option>
<option value="stopping">stopping</option>
<option value="shutting-down">shutting-down</option>
<option value="terminated">terminated</option>
</select>
</div>
<div class="md:col-span-5 bg-white shadow-soft border border-slate-200 rounded-2xl p-4">
<label class="block text-xs font-medium text-slate-500 mb-1">Actions groupées</label>
<div class="flex flex-wrap gap-2">
<button id="btn-start" type="button" class="px-3 py-2 rounded-xl bg-emerald-600 text-white text-sm hover:bg-emerald-700 disabled:opacity-40">Start</button>
<button id="btn-stop" type="button" class="px-3 py-2 rounded-xl bg-amber-600 text-white text-sm hover:bg-amber-700 disabled:opacity-40">Stop</button>
<button id="btn-reboot" type="button" class="px-3 py-2 rounded-xl bg-indigo-600 text-white text-sm hover:bg-indigo-700 disabled:opacity-40">Reboot</button>
<button id="btn-terminate" type="button" class="px-3 py-2 rounded-xl bg-rose-600 text-white text-sm hover:bg-rose-700 disabled:opacity-40">Terminate</button>
<div id="selection-count" class="text-sm text-slate-500 self-center">(0 sélection)</div>
<button id="refresh" type="button" class="ml-auto px-3 py-2 rounded-xl bg-slate-900 text-white text-sm hover:bg-slate-800">Rafraîchir</button>
</div>
</div>
</section>
<!-- Table -->
<section class="bg-white shadow-soft border border-slate-200 rounded-2xl overflow-hidden">
<div class="overflow-x-auto">
<table class="min-w-full text-sm">
<thead class="bg-slate-50 border-b border-slate-200">
<tr class="text-left">
<th class="px-4 py-3"><input id="check-all" type="checkbox" class="w-4 h-4"></th>
<th class="px-3 py-3 font-semibold">Name</th>
<th class="px-3 py-3 font-semibold">InstanceId</th>
<th class="px-3 py-3 font-semibold">State</th>
<th class="px-3 py-3 font-semibold">Type</th>
<th class="px-3 py-3 font-semibold">AZ</th>
<th class="px-3 py-3 font-semibold">Public IP</th>
<th class="px-3 py-3 font-semibold">Private IP</th>
<th class="px-3 py-3 font-semibold">Launch (UTC)</th>
<th class="px-3 py-3 font-semibold text-right">Git</th>
</tr>
</thead>
<tbody id="tbody"></tbody>
</table>
</div>
<div id="empty" class="hidden p-8 text-center text-slate-500">Aucune instance trouvée.</div>
</section>
<!-- Debug -->
<details class="bg-white border border-slate-200 rounded-2xl shadow-soft p-4">
<summary class="cursor-pointer text-sm text-slate-600">Debug</summary>
<pre id="debug" class="mt-2 bg-slate-50 border border-slate-200 rounded-xl p-3 text-xs overflow-x-auto max-h-64"></pre>
</details>
</main>
<!-- Modal SSH/Git -->
<div id="sshModal" tabindex="-1" aria-hidden="true" class="hidden fixed inset-0 z-50 overflow-y-auto overflow-x-hidden">
<div class="fixed inset-0 bg-black/50"></div>
<div class="relative p-4 w-full max-w-3xl mx-auto">
<div class="relative bg-white rounded-2xl shadow-2xl border border-slate-200">
<div class="flex items-start justify-between p-4 border-b rounded-t">
<div>
<h3 class="text-lg font-semibold">Détails de l’instance</h3>
<p class="text-xs text-slate-500">Exécution via SSH (clé privée requise)</p>
</div>
<button id="ssh-close" type="button" class="text-slate-400 hover:text-slate-600"><span class="text-2xl leading-none">×</span></button>
</div>
<div class="p-6 space-y-4">
<div class="grid md:grid-cols-2 gap-3 text-sm">
<div><span class="text-slate-500">Name:</span> <span id="m-name" class="font-medium"></span></div>
<div><span class="text-slate-500">InstanceId:</span> <span id="m-id" class="font-mono"></span></div>
<div><span class="text-slate-500">State:</span> <span id="m-state"></span></div>
<div><span class="text-slate-500">Type:</span> <span id="m-type"></span></div>
<div><span class="text-slate-500">AZ:</span> <span id="m-az"></span></div>
<div><span class="text-slate-500">Public IP:</span> <span id="m-pub"></span></div>
<div><span class="text-slate-500">Private IP:</span> <span id="m-priv"></span></div>
<div><span class="text-slate-500">Platform:</span> <span id="m-platform"></span></div>
</div>
<hr class="my-2">
<div class="space-y-2">
<div class="text-sm font-medium">Cloner un dépôt Git et exécuter une commande</div>
<div class="grid md:grid-cols-3 gap-3">
<div>
<label class="block text-xs text-slate-500">User SSH</label>
<input id="ssh-user" class="w-full rounded-xl border-slate-300 bg-white border p-2 text-sm" value="ec2-user">
<p class="text-[11px] text-slate-500 mt-1">Amazon Linux: ec2-user · Ubuntu: ubuntu</p>
</div>
<div class="md:col-span-2">
<label class="block text-xs text-slate-500">Clé privée (PEM)</label>
<textarea id="ssh-key" class="w-full rounded-xl border-slate-300 bg-white border p-2 text-xs font-mono" rows="5" placeholder="-----BEGIN PRIVATE KEY----- ... -----END PRIVATE KEY-----"></textarea>
</div>
</div>
<label class="block text-xs text-slate-500 mt-2">URL du dépôt (https://... .git)</label>
<input id="git-url" class="w-full rounded-xl border-slate-300 bg-white border p-2 text-sm" placeholder="https://github.com/owner/repo.git">
<div class="grid md:grid-cols-2 gap-3">
<div>
<label class="block text-xs text-slate-500 mt-2">Répertoire de travail</label>
<input id="git-workdir" class="w-full rounded-xl border-slate-300 bg-white border p-2 text-sm" value="/opt/app">
</div>
<div>
<label class="block text-xs text-slate-500 mt-2">Commande post-clone</label>
<input id="git-postcmd" class="w-full rounded-xl border-slate-300 bg-white border p-2 text-sm" placeholder="bash setup.sh && docker compose up -d">
</div>
</div>
<div class="flex flex-wrap gap-2 mt-3">
<button id="git-run-now" type="button" class="px-3 py-2 rounded-xl bg-slate-900 text-white text-sm hover:bg-slate-800">Exécuter maintenant</button>
<span class="text-xs text-slate-500 self-center">Port 22 ouvert depuis votre IP, instance en <em>running</em>.</span>
</div>
<pre id="git-output" class="mt-2 bg-slate-50 border border-slate-200 rounded-xl p-3 text-xs overflow-x-auto max-h-64"></pre>
</div>
</div>
</div>
</div>
</div>
<!-- Create Instance Modal -->
<div id="createModal" tabindex="-1" aria-hidden="true" class="hidden fixed inset-0 z-50 overflow-y-auto overflow-x-hidden">
<div class="fixed inset-0 bg-black/50"></div>
<div class="relative p-4 w-full max-w-3xl mx-auto">
<div class="relative bg-white rounded-2xl shadow-2xl border border-slate-200">
<div class="flex items-start justify-between p-4 border-b rounded-t">
<h3 class="text-lg font-semibold">Créer une instance EC2</h3>
<button id="create-close" type="button" class="text-slate-400 hover:text-slate-600"><span class="text-2xl leading-none">×</span></button>
</div>
<div class="p-6 space-y-6 text-sm">
<!-- Section: Base -->
<section class="space-y-2">
<div class="text-sm font-medium">Base</div>
<div class="grid md:grid-cols-2 gap-3">
<div>
<label class="block text-xs text-slate-500">Nom (tag Name)</label>
<input id="c-name" class="w-full rounded-xl border-slate-300 bg-white border p-2" value="ec2-app">
</div>
<div>
<label class="block text-xs text-slate-500">Type d’instance</label>
<input id="c-type" class="w-full rounded-xl border-slate-300 bg-white border p-2" value="t3.micro">
</div>
</div>
<div class="grid md:grid-cols-3 gap-3">
<div>
<label class="block text-xs text-slate-500">OS</label>
<select id="c-os" class="w-full rounded-xl border-slate-300 bg-white border p-2">
<option value="al2023">Amazon Linux 2023</option>
<option value="ubuntu-24-04">Ubuntu 24.04 LTS</option>
</select>
</div>
<div>
<label class="block text-xs text-slate-500">Disque (GiB)</label>
<input id="c-disk" type="number" min="8" class="w-full rounded-xl border-slate-300 bg-white border p-2" value="20">
</div>
<div class="grid gap-1">
<label class="block text-xs text-slate-500">IP Publique</label>
<label class="inline-flex items-center gap-2">
<input id="c-pubip" type="checkbox" class="w-4 h-4" checked>
<span>Associer une IP publique</span>
</label>
</div>
</div>
</section>
<!-- Section: Réseau -->
<section class="space-y-2">
<div class="text-sm font-medium">Réseau</div>
<div class="grid md:grid-cols-2 gap-3">
<div>
<label class="block text-xs text-slate-500">Subnet ID (optionnel)</label>
<input id="c-subnet" class="w-full rounded-xl border-slate-300 bg-white border p-2" placeholder="subnet-...">
</div>
<div>
<label class="block text-xs text-slate-500">Security Groups</label>
<select id="c-sg" multiple class="w-full rounded-xl border-slate-300 bg-white border p-2 text-sm h-32"></select>
<p class="text-[11px] text-slate-500 mt-1">Maintenir Ctrl / Cmd pour en sélectionner plusieurs.</p>
<button id="c-sg-refresh" type="button" class="mt-2 px-3 py-2 rounded-xl border border-slate-300 text-sm">Rafraîchir</button>
</div>
</div>
</section>
<!-- Section: Accès & Post-provisioning -->
<section class="space-y-2">
<div class="text-sm font-medium">Accès & Post-provisioning</div>
<div class="grid md:grid-cols-3 gap-3 items-end">
<div class="md:col-span-2">
<label class="block text-xs text-slate-500">Key Pair AWS (optionnel)</label>
<div class="flex gap-2">
<select id="c-keyname" class="w-full rounded-xl border-slate-300 bg-white border p-2">
<option value="">— Aucun —</option>
</select>
<button id="c-kp-refresh" type="button" class="px-3 py-2 rounded-xl border border-slate-300">Rafraîchir</button>
</div>
<p class="text-[11px] text-slate-500 mt-1">Le Key Pair permet l’accès SSH manuel et/ou via la PEM ci-dessous.</p>
</div>
<div>
<label class="block text-xs text-slate-500">Importer une clé</label>
<button id="c-kp-import" type="button" class="w-full px-3 py-2 rounded-xl bg-slate-900 text-white text-sm hover:bg-slate-800">Importer…</button>
</div>
</div>
<div class="grid md:grid-cols-3 gap-3">
<div>
<label class="inline-flex items-center gap-2">
<input id="c-ssh-after" type="checkbox" class="w-4 h-4">
<span class="text-sm">Exécuter Git par SSH après création</span>
</label>
<p class="text-[11px] text-slate-500 mt-1">Nécessite TCP/22 autorisé depuis cet outil.</p>
</div>
<div>
<label class="block text-xs text-slate-500">Utilisateur SSH (défaut auto)</label>
<input id="c-sshuser" class="w-full rounded-xl border-slate-300 bg-white border p-2" placeholder="ec2-user ou ubuntu">
</div>
<div class="">
<label class="block text-xs text-slate-500">Clé privée (PEM)</label>
<textarea id="c-privpem" class="w-full rounded-xl border-slate-300 bg-white border p-2 text-xs font-mono" rows="4" placeholder="-----BEGIN PRIVATE KEY----- ... -----END PRIVATE KEY-----"></textarea>
</div>
</div>
</section>
<!-- Section: Déploiement Git -->
<section class="space-y-2">
<div class="text-sm font-medium">Déploiement Git</div>
<div>
<label class="block text-xs text-slate-500">URL dépôt Git (optionnel)</label>
<input id="c-git" class="w-full rounded-xl border-slate-300 bg-white border p-2" placeholder="https://github.com/owner/repo.git">
</div>
<div class="grid md:grid-cols-2 gap-3">
<div>
<label class="block text-xs text-slate-500">Répertoire de travail</label>
<input id="c-workdir" class="w-full rounded-xl border-slate-300 bg-white border p-2" value="/opt/app">
</div>
<div>
<label class="block text-xs text-slate-500">Commande post-clone</label>
<input id="c-postcmd" class="w-full rounded-xl border-slate-300 bg-white border p-2" placeholder="bash setup.sh && docker compose up -d">
</div>
</div>
</section>
<div class="flex items-center gap-3">
<button id="c-create" type="button" class="px-3 py-2 rounded-xl bg-emerald-600 text-white text-sm hover:bg-emerald-700">Créer</button>
</div>
<pre id="c-output" class="bg-slate-50 border border-slate-200 rounded-xl p-3 text-xs overflow-x-auto max-h-64"></pre>
</div>
</div>
</div>
</div>
<div id="toast" class="fixed bottom-4 right-4 hidden bg-slate-900 text-white text-sm px-4 py-3 rounded-xl shadow-lg"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/flowbite/2.5.2/flowbite.min.js"></script>
<script>
// Refs
const el = {
q: document.getElementById('q'), states: document.getElementById('states'), refresh: document.getElementById('refresh'),
tbody: document.getElementById('tbody'), empty: document.getElementById('empty'),
btnStart: document.getElementById('btn-start'), btnStop: document.getElementById('btn-stop'),
btnReboot: document.getElementById('btn-reboot'), btnTerminate: document.getElementById('btn-terminate'),
checkAll: document.getElementById('check-all'), selectionCount: document.getElementById('selection-count'),
toast: document.getElementById('toast'),
sshModal: document.getElementById('sshModal'), sshClose: document.getElementById('ssh-close'),
mName: document.getElementById('m-name'), mId: document.getElementById('m-id'), mState: document.getElementById('m-state'),
mType: document.getElementById('m-type'), mAz: document.getElementById('m-az'), mPub: document.getElementById('m-pub'),
mPriv: document.getElementById('m-priv'), mPlatform: document.getElementById('m-platform'),
gitUrl: document.getElementById('git-url'), gitWorkdir: document.getElementById('git-workdir'),
gitPostcmd: document.getElementById('git-postcmd'), sshUser: document.getElementById('ssh-user'),
sshKey: document.getElementById('ssh-key'), gitRunNow: document.getElementById('git-run-now'),
gitOutput: document.getElementById('git-output'), debug: document.getElementById('debug'),
btnCreate: document.getElementById('btn-create'), createModal: document.getElementById('createModal'),
createClose: document.getElementById('create-close'),
cName: document.getElementById('c-name'), cType: document.getElementById('c-type'), cOS: document.getElementById('c-os'),
cDisk: document.getElementById('c-disk'), cPubIP: document.getElementById('c-pubip'),
cSubnet: document.getElementById('c-subnet'), cSG: document.getElementById('c-sg'),
cKeyName: document.getElementById('c-keyname'), cKpRefresh: document.getElementById('c-kp-refresh'), cKpImport: document.getElementById('c-kp-import'),
cSSHAfter: document.getElementById('c-ssh-after'), cSSHUser: document.getElementById('c-sshuser'), cPrivPEM: document.getElementById('c-privpem'),
cGit: document.getElementById('c-git'), cWorkdir: document.getElementById('c-workdir'), cPostcmd: document.getElementById('c-postcmd'),
cCreate: document.getElementById('c-create'), cOutput: document.getElementById('c-output'),
};
const elSG = el.cSG, elSGRefresh = document.getElementById('c-sg-refresh');
const elKeyName = el.cKeyName, elKpRefresh = el.cKpRefresh, elKpImport = el.cKpImport;
function showToast(msg){ el.toast.textContent = msg; el.toast.classList.remove('hidden'); setTimeout(()=>el.toast.classList.add('hidden'), 2200); }
function ensureModal(node, inst){ if (inst) return inst; if (window.flowbite && typeof window.flowbite.Modal==='function') return new window.flowbite.Modal(node);
return { show(){node.classList.remove('hidden')}, hide(){node.classList.add('hidden')} }; }
let rows = [], sshModal=null, createModal=null, current=null;
document.addEventListener('DOMContentLoaded', () => {
sshModal = ensureModal(el.sshModal, sshModal);
createModal = ensureModal(el.createModal, createModal);
el.sshClose?.addEventListener('click', ()=>sshModal.hide());
el.createClose?.addEventListener('click', ()=>createModal.hide());
document.addEventListener('keydown', (e)=>{ if(e.key==='Escape'){sshModal.hide(); createModal.hide();} });
el.btnCreate?.addEventListener('click', () => {
el.cOutput.textContent = '';
loadSecurityGroups(); loadKeyPairs();
createModal.show();
});
});
function badgeClass(s){ return s==='running'?'border-emerald-200 text-emerald-700 bg-emerald-50':
s==='stopped'?'border-slate-300 text-slate-600 bg-slate-50':
s==='pending'?'border-blue-200 text-blue-700 bg-blue-50':
s==='stopping'?'border-amber-200 text-amber-700 bg-amber-50':
s==='shutting-down'?'border-rose-200 text-rose-700 bg-rose-50':
s==='terminated'?'border-rose-300 text-rose-700 bg-rose-50':'border-slate-300 text-slate-600 bg-slate-50'; }
function updateSelectionInfo(){
const count = Array.from(document.querySelectorAll('.row-check:checked')).length;
el.selectionCount.textContent = '(' + count + ' sélection)';
const on = count>0; el.btnStart&&(el.btnStart.disabled=!on); el.btnStop&&(el.btnStop.disabled=!on);
el.btnReboot&&(el.btnReboot.disabled=!on); el.btnTerminate&&(el.btnTerminate.disabled=!on);
}
function renderTable(items){
rows = Array.isArray(items)?items:[];
el.tbody.innerHTML=''; if (el.checkAll) el.checkAll.checked=false; updateSelectionInfo();
if (rows.length===0){ el.empty.classList.remove('hidden'); return; } el.empty.classList.add('hidden');
const frag=document.createDocumentFragment();
for (const it of rows){
const tr=document.createElement('tr'); tr.className='border-b border-slate-100 hover:bg-slate-50';
const tdC=document.createElement('td'); tdC.className='px-4 py-2';
const cb=document.createElement('input'); cb.type='checkbox'; cb.className='row-check w-4 h-4'; cb.dataset.id=it.InstanceId; tdC.appendChild(cb); tr.appendChild(tdC);
const td=(t,x='')=>{ const d=document.createElement('td'); d.className='px-3 py-2 '+x; d.textContent=t||''; return d; };
tr.appendChild(td(it.Name)); tr.appendChild(td(it.InstanceId,'font-mono'));
const tds=document.createElement('td'); tds.className='px-3 py-2'; const b=document.createElement('span');
b.className='inline-flex items-center px-2 py-0.5 rounded-full text-xs border '+badgeClass(it.State); b.textContent=it.State||''; tds.appendChild(b); tr.appendChild(tds);
tr.appendChild(td(it.Type)); tr.appendChild(td(it.AZ)); tr.appendChild(td(it.PublicIp)); tr.appendChild(td(it.PrivateIp)); tr.appendChild(td(it.LaunchTime));
const tdAct=document.createElement('td'); tdAct.className='px-3 py-2 text-right';
const btn=document.createElement('button'); btn.type='button'; btn.className='btn-git inline-flex items-center gap-1 px-2 py-1 rounded-lg border border-slate-300 text-slate-700 hover:bg-slate-50'; btn.dataset.id=it.InstanceId; btn.title='Ouvrir Git/SSH';
btn.innerHTML=`<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="6" cy="5" r="2"></circle><circle cx="6" cy="19" r="2"></circle><circle cx="18" cy="12" r="2"></circle><path d="M8 5h6a4 4 0 0 1 4 4"></path><path d="M8 19h6a4 4 0 0 0 4-4"></path><path d="M6 7v10"></path></svg><span class="sr-only">Git</span>`;
tdAct.appendChild(btn); tr.appendChild(tdAct);
tr.addEventListener('click', (ev)=>{ if(ev.target?.matches('input[type="checkbox"]')) return; if(ev.target?.closest('.btn-git')) return; openModal(it); });
frag.appendChild(tr);
}
el.tbody.appendChild(frag);
}
async function loadInstances(){
const params=new URLSearchParams(); const s=(el.states.value||'').trim(); const q=(el.q.value||'').trim();
if (s) params.set('states', s); if (q) params.set('q', q);
const url='/api/instances'+(params.toString()?('?'+params.toString()):''); let status=0, head='';
try{
const r=await fetch(url,{headers:{'Accept':'application/json'}}); status=r.status; const raw=await r.text(); head=raw.slice(0,300);
let data; try{ data=JSON.parse(raw);}catch(e){ el.debug.textContent='URL: '+url+'\\nHTTP: '+status+'\\nPARSE ERROR: '+e+'\\nHEAD(300):\\n'+head; renderTable([]); return; }
const items=Array.isArray(data.instances)?data.instances:[]; el.debug.textContent='URL: '+url+'\\nHTTP: '+status+'\\nCount: '+items.length+(data.error?('\\nERROR: '+data.error):''); renderTable(items);
}catch(e){ el.debug.textContent='URL: '+url+'\\nFETCH ERROR: '+e+'\\nHEAD(300):\\n'+head; renderTable([]); }
}
async function doAction(action){
const ids=Array.from(document.querySelectorAll('.row-check:checked')).map(cb=>cb.dataset.id);
if(!ids.length) return; if(action==='terminate' && !confirm('⚠️ Confirmer la SUPPRESSION DÉFINITIVE des instances sélectionnées ?')) return;
try{
const r=await fetch('/api/action',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({action,ids,wait:false})});
const data=await r.json().catch(()=>({})); if(!r.ok||data.error){ showToast('Erreur action: '+(data.error||r.status)); } else { showToast(action+' OK: '+ids.length+' instance(s)'); await loadInstances(); }
}catch(e){ showToast('Erreur réseau action'); console.error(e); }
}
function openModal(it){
current=it; el.mName.textContent=it.Name||''; el.mId.textContent=it.InstanceId; el.mState.textContent=it.State; el.mType.textContent=it.Type;
el.mAz.textContent=it.AZ; el.mPub.textContent=it.PublicIp||''; el.mPriv.textContent=it.PrivateIp||''; el.mPlatform.textContent=it.Platform||'';
el.gitUrl.value=''; el.gitWorkdir.value='/opt/app'; el.gitPostcmd.value=''; el.gitOutput.textContent=''; sshModal.show();
}
async function runGitNow(){
try{
if(!current){ showToast('Aucune instance sélectionnée.'); return; }
const payload={ instance_id: current.InstanceId, username: (el.sshUser.value||'ec2-user').trim(),
private_key_pem: (el.sshKey.value||'').trim(), git_url: (el.gitUrl.value||'').trim(),
workdir: (el.gitWorkdir.value||'/opt/app').trim(), post_cmd: (el.gitPostcmd.value||'').trim() };
if(!payload.private_key_pem || !payload.git_url){ showToast('Renseigne la clé privée et l’URL du dépôt.'); return; }
if(current.State!=='running'){ showToast('L’instance doit être en état running.'); return; }
const btn=el.gitRunNow, prev=btn.textContent; btn.disabled=true; btn.textContent='Exécution…'; el.gitOutput.textContent='Connexion SSH et exécution du script...\\n';
const r=await fetch('/api/ssh/git',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload)});
let data; try{ data=await r.json(); }catch(e){ el.gitOutput.textContent+='\\n❌ Erreur de parsing JSON: '+e; btn.disabled=false; btn.textContent=prev; return; }
if(!r.ok || data.error){ el.gitOutput.textContent+='\\n❌ Erreur: '+(data.error||r.status); showToast('Échec de l’exécution.'); }
else{
el.gitOutput.textContent=['Hôte: '+(data.host||''),'Code retour: '+(data.exit_code??''),'','----- STDOUT -----',(data.stdout||'').trim(),'','----- STDERR -----',(data.stderr||'').trim(),'','✓ Terminé.'].join('\\n');
showToast('Commande exécutée !');
}
btn.disabled=false; btn.textContent=prev;
}catch(e){ el.gitOutput.textContent+='\\n❌ Erreur JS: '+e; el.gitRunNow.disabled=false; el.gitRunNow.textContent='Exécuter maintenant'; }
}
// Load SGs
async function loadSecurityGroups(){
try{
const r=await fetch('/api/security-groups',{headers:{'Accept':'application/json'}});
const data=await r.json(); const items=Array.isArray(data.security_groups)?data.security_groups:[];
elSG.innerHTML=''; for (const sg of items){ const opt=document.createElement('option'); opt.value=sg.GroupId; opt.textContent=`${sg.GroupName} (${sg.GroupId})`; elSG.appendChild(opt); }
}catch(e){ showToast('Erreur chargement SGs'); console.error(e); }
}
elSGRefresh?.addEventListener('click', loadSecurityGroups);
// Load KeyPairs
async function loadKeyPairs(){
try{
const r=await fetch('/api/keypairs',{headers:{'Accept':'application/json'}});
const data=await r.json(); const items=Array.isArray(data.keypairs)?data.keypairs:[];
elKeyName.options.length=1; for (const kp of items){ const opt=document.createElement('option'); opt.value=kp.KeyName; opt.textContent=kp.KeyName+(kp.KeyType?` (${kp.KeyType})`:'' ); elKeyName.appendChild(opt); }
}catch(e){ showToast('Erreur chargement key pairs'); console.error(e); }
}