如何通过Python编程暂停MongoDB Atlas集群?两种尝试均失败
如何用Python自动暂停MongoDB Atlas集群
需要实现MongoDB Atlas集群的自动暂停功能,已知Atlas CLI提供atlas clusters pause [options]命令,但希望通过Python完成该操作(PyMongo不支持此管理类操作),尝试以下两种方法均未成功:
尝试过的方法
方法一:调用Atlas CLI命令
import os os.system("atlas clusters pause Cluster0 --projectId 662b391615a47202d49f2fa0 --output json")
方法二:调用MongoDB Atlas API
import requests import json # Atlas API configuration base_url = "https://cloud.mongodb.com/api/atlas/v1.0" project_id = "662b391615a47202d49f2fa0" cluster_name = "Cluster0" # Your Atlas API credentials public_key = "YOUR_PUBLIC_KEY" #private_key = "YOUR_PRIVATE_KEY" # Endpoint for pausing a cluster endpoint = f"{base_url}/groups/{project_id}/clusters/{cluster_name}" # Request headers headers = { "Content-Type": "application/json", "Accept": "application/json" } # Request payload payload = { "paused": True } # Send the PATCH request response = requests.patch( endpoint, auth=(public_key), headers=headers, data=json.dumps(payload) ) # Check the response if response.status_code == 200: print(f"Cluster {cluster_name} paused successfully.") else: print(f"Failed to pause cluster. Status code: {response.status_code}") print(response.text)
问题分析与修正方案
方法一问题修正
os.system无法捕获详细错误信息,且依赖CLI的环境配置(需确保已通过atlas login完成认证),改用subprocess更便于调试和控制:
import subprocess try: # 执行CLI命令,捕获输出和错误 result = subprocess.run( ["atlas", "clusters", "pause", "Cluster0", "--projectId", "662b391615a47202d49f2fa0", "--output", "json"], capture_output=True, text=True, check=True ) print("集群暂停成功:", result.stdout) except subprocess.CalledProcessError as e: print("集群暂停失败:", e.stderr)
若未提前登录CLI,可直接在命令中传入凭证:
result = subprocess.run( ["atlas", "clusters", "pause", "Cluster0", "--projectId", "662b391615a47202d49f2fa0", "--publicKey", "你的公钥", "--privateKey", "你的私钥", "--output", "json"], capture_output=True, text=True, check=True )
方法二问题修正
原代码存在两个关键错误:
- API认证需同时传入公钥和私钥,
auth参数应为元组(public_key, private_key) - Atlas API修改集群状态为异步操作,响应状态码通常是
202 Accepted而非200
修正后的代码:
import requests base_url = "https://cloud.mongodb.com/api/atlas/v1.0" project_id = "662b391615a47202d49f2fa0" cluster_name = "Cluster0" # 补全私钥 public_key = "YOUR_PUBLIC_KEY" private_key = "YOUR_PRIVATE_KEY" endpoint = f"{base_url}/groups/{project_id}/clusters/{cluster_name}" headers = { "Content-Type": "application/json", "Accept": "application/json" } payload = { "paused": True } response = requests.patch( endpoint, auth=(public_key, private_key), # 传入完整密钥对 headers=headers, json=payload # 直接用json参数自动序列化,无需手动dumps ) if response.status_code in (200, 202): print(f"Cluster {cluster_name} 暂停请求已受理,正在处理中") else: print(f"暂停失败,状态码: {response.status_code}") print(response.text)
注意:需确保你的API密钥已被授予Cluster Manager角色权限,否则会返回权限不足的错误。
内容的提问来源于stack exchange,提问作者Arjan Vailly
相关产品推荐
相关产品推荐

