我有一个项目需要读取发送到其他地方的Docker Compose服务并将其保存到compose.yaml
,然后通过kompose
将其转换为Kubernetes YAML并通过kubectl
执行,所有这些都需要Python自动化。
我该怎么做?
同意关于尽可能避免这种情况的评论,但有时你别无选择。我以前也做过类似的事情,强烈建议使用Python-Kube客户端来管理kubectl命令,它们有很棒的文档!
以下代码将读取docker-compose.yaml
文件字符串,并使用Kompose命令创建在Kube中运行所需的任何服务和部署。
import subprocess
import yaml
from kubernetes import client, config
def load_in_kube(compose_str):
COMPOSE_FILE_NAME = "compose.yaml"
with open(COMPOSE_FILE_NAME, "w") as text_file:
text_file.write(compose_str)
# Save the output to string, rather than a file.
output = subprocess.check_output(["kompose", "convert", "-f", COMPOSE_FILE_NAME, "--stdout"])
yaml_output = yaml.safe_load(output)
config.load_kube_config("service-controller/.kube/config")
for item in yaml_output["items"]:
if item["kind"] == "Service":
try:
kube_client = client.CoreV1Api()
namespace = "default"
kube_client.create_namespaced_service(namespace, item, pretty="true")
except Exception as e:
print(f"Exception when trying to create the service in Kube: {e}n")
elif item["kind"] == "Deployment":
try:
kube_client = client.AppsV1Api()
namespace = "default"
kube_client.create_namespaced_deployment(namespace, item, pretty="true")
except Exception as e:
print(f"Exception when trying to create the service in Kube: {e}n")
if __name__ == "__main__":
compose_str = """version: "3.1"
services:
hello-world:
build: .
image: hello-world-api
container_name: hello-world
ports:
- "5555:5555"
entrypoint: python api.py
environment:
- DEBUG=True
"""
load_in_kube(compose_str)