首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python执行kompose命令和kubectl命令

Python执行kompose命令和kubectl命令
EN

Stack Overflow用户
提问于 2020-05-06 10:02:11
回答 1查看 101关注 0票数 0

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

我该怎么做呢?

EN

回答 1

Stack Overflow用户

发布于 2020-08-12 06:41:41

如果可能的话,同意关于避免这种情况的评论,但有时你没有这样的选择。我以前也做过类似的事情,强烈推荐使用Python Kube Client来管理kubectl命令,他们有很棒的文档!

以下代码将读取docker-compose.yaml文件字符串,并使用Kompose命令创建在Kube中运行所需的任何服务和部署。

代码语言:javascript
复制
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)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61626119

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档