How to Update Nacos Service Instances Using a Python Script
This guide shows how to write a Python script that sends a PUT request to Nacos to register or deregister a service instance, parses the JSON response, and reports success or failure based on the returned code and weight parameter.
First, import the required modules:
import json
import requests
import sysDefine the target Nacos URL for instance management:
url = 'http://<em>nacos-address</em>:8848/nacos/v2/ns/instance'Read command‑line arguments for the service name, IP, port, weight, and namespace ID:
service_name = sys.argv[1]
ip = sys.argv[2]
port = sys.argv[3]
weight = sys.argv[4]
namespace_id = sys.argv[5]Build the request payload, marking the instance as ephemeral:
data = {
'serviceName': service_name,
'ip': ip,
'port': port,
'weight': weight,
'ephemeral': 'true',
'namespaceId': namespace_id
}Send the PUT request to Nacos and capture the response: response = requests.put(url, data=data) Print the raw response text and parse it as JSON:
print(response.text)
json_data = json.loads(response.text)
print(json_data)Check the response code; if it is not zero, raise an error:
response_code = json_data["code"]
if response_code != 0:
raise ValueError("下线异常")Finally, output a success message: if the weight is "0" the instance is considered offline, otherwise it is online:
if weight == "0":
print("服务:{} ip:{} 下线成功".format(service_name, ip))
else:
print("服务:{} ip:{} 上线成功".format(service_name, ip))Practical DevOps Architecture
Hands‑on DevOps operations using Docker, K8s, Jenkins, and Ansible—empowering ops professionals to grow together through sharing, discussion, knowledge consolidation, and continuous improvement.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
