Le SDK Python officiel simplifie l’intégration avec l’API M2S Cloud. Il gère l’authentification, les requêtes HTTP et le parsing JSON pour vous concentrer sur votre logique métier.
# Installer depuis PyPI
pip install m2s-cloud-sdk
# Ou avec une version spécifique
pip install m2s-cloud-sdk==1.0.0
# Vérifier l'installation
python -c "import m2s; print(m2s.__version__)"
Définissez votre clé API comme variable d’environnement :
# Linux/Mac
export M2S_API_KEY="m2s_api_xxxxxxxxxxxxx"
# Windows (PowerShell)
$env:M2S_API_KEY = "m2s_api_xxxxxxxxxxxxx"
# Windows (CMD)
set M2S_API_KEY=m2s_api_xxxxxxxxxxxxx
# Ou dans un fichier .env
M2S_API_KEY=m2s_api_xxxxxxxxxxxxx
from m2s import M2SClient
# Initialiser le client
client = M2SClient() # Lit M2S_API_KEY automatiquement
# Ou avec clé explicite
# client = M2SClient(api_key="m2s_api_xxx")
# Lister les instances
instances = client.instances.list()
for instance in instances:
print(f"{instance.name} - {instance.status}")
# Créer une instance
instance = client.instances.create(
name="web-prod-01",
plan="business",
region="fr-par-1",
image="ubuntu-22.04"
)
print(f"Instance créée: {instance.id}")
# Attendre qu'elle soit prête
instance.wait_until("running")
print(f"Instance running avec IP: {instance.ip_address}")
from m2s import M2SClient
client = M2SClient()
# GET - Lister avec filtres
instances = client.instances.list(
status="running",
region="fr-par-1",
tags=["production"]
)
# GET - Détails d'une instance
instance = client.instances.get("i-abc123")
print(f"CPU: {instance.vcpu}, RAM: {instance.memory}MB")
# PATCH - Modifier
instance.update(plan="performance")
instance.update(tags=["production", "web"])
# POST - Actions
instance.start()
instance.stop()
instance.reboot()
# POST - Rebuild avec nouvelle image
instance.rebuild(image="debian-12")
# DELETE - Supprimer
instance.delete()
# Ou directement
client.instances.delete("i-abc123")
# Obtenir les métriques
metrics = instance.metrics()
print(f"CPU: {metrics.cpu_usage}%")
print(f"RAM: {metrics.memory_usage}%")
print(f"Disque: {metrics.disk_usage}%")
# Historique des métriques
history = instance.metrics_history(
metric="cpu_usage",
start="2024-01-01T00:00:00Z",
end="2024-01-31T23:59:59Z",
interval="1h"
)
for point in history:
print(f"{point.timestamp}: {point.value}%")
# Activer les backups
instance.enable_backups(
schedule="0 2 * * *", # Tous les jours à 2h
retention_days=7
)
# Créer un snapshot manuel
snapshot = instance.create_snapshot(
name="pre-maintenance",
description="Avant mise à jour système"
)
# Lister les snapshots
snapshots = instance.list_snapshots()
for snap in snapshots:
print(f"{snap.name} - {snap.created_at}")
# Restaurer depuis un snapshot
instance.restore_from_snapshot("snap-abc123")
# Restaurer vers une nouvelle instance
new_instance = client.instances.create_from_snapshot(
snapshot_id="snap-abc123",
name="restored-instance",
plan="business"
)
# Supprimer un snapshot
snapshot.delete()
from m2s import M2SClient
from m2s.exceptions import (
M2SError,
AuthenticationError,
NotFoundError,
RateLimitError,
ServerError
)
client = M2SClient()
try:
instance = client.instances.get("i-inexistant")
except NotFoundError as e:
print(f"Instance non trouvée: {e}")
except AuthenticationError as e:
print(f"Problème d'authentification: {e}")
except RateLimitError as e:
print(f"Rate limit atteint, réessayez dans {e.retry_after}s")
except ServerError as e:
print(f"Erreur serveur: {e}")
except M2SError as e:
print(f"Erreur M2S générique: {e}")
Le SDK gère automatiquement le retry pour les erreurs 429 (Rate Limit) et 5xx (Server Error) avec backoff exponentiel.
#!/usr/bin/env python3
"""
Script de déploiement automatique d'instance web
"""
from m2s import M2SClient
from m2s.exceptions import NotFoundError
import time
def deploy_web_instance(name, plan="business", region="fr-par-1"):
client = M2SClient()
# Vérifier si l'instance existe déjà
try:
instance = client.instances.get_by_name(name)
print(f"Instance '{name}' existe déjà (ID: {instance.id})")
return instance
except NotFoundError:
pass
# Créer l'instance
print(f"Création de l'instance '{name}'...")
instance = client.instances.create(
name=name,
plan=plan,
region=region,
image="ubuntu-22.04",
tags=["web", "production"],
backup_enabled=True,
monitoring_enabled=True
)
print(f"Instance créée: {instance.id}")
# Attendre qu'elle soit running
print("Attente du boot de l'instance...")
instance.wait_until("running", timeout=300)
print(f"Instance prête ! IP: {instance.ip_address}")
# Activer les backups
instance.enable_backups(schedule="0 2 * * *", retention_days=7)
print("Backups activés")
return instance
if __name__ == "__main__":
instance = deploy_web_instance("web-prod-01")
print(f"\nDéploiement terminé !")
print(f"IP publique: {instance.ip_address}")
print(f"SSH: ssh root@{instance.ip_address}")
| SDK | Installation | Description |
|---|---|---|
| Node.js | npm install m2s-cloud-sdk | Support complet, async/await |
| Go | go get github.com/m2s/sdk-go | Idiomatique, context support |
| PHP | composer require m2s/cloud-sdk | PSR-4, Guzzle HTTP |