0

我有一个项目需要读取发送到其他地方的 Docker Compose 服务并将其保存到compose.yaml,然后将其转换为 Kubernetes YAMLkompose并通过 执行kubectl,所有这些都需要 Python 自动化。

我怎样才能做到这一点?

4

1 回答 1

0

如果可能的话,同意关于避免这种情况的评论,但有时你没有那个选择。我之前不得不做类似的事情,强烈推荐Python Kube Client来管理 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)
于 2020-08-11T22:41:41.267 回答