第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

使用 Python API 以編程方式克隆 Kubernetes 對(duì)象

使用 Python API 以編程方式克隆 Kubernetes 對(duì)象

呼喚遠(yuǎn)方 2022-07-12 15:29:51
Python API 可用于從集群中讀取對(duì)象。通過(guò)克隆,我們可以說(shuō):使用獲取現(xiàn)有 Kubernetes 對(duì)象的副本kubectl get更改對(duì)象的屬性應(yīng)用新對(duì)象直到最近,--exportapi 的選項(xiàng)在 1.14 中被棄用。我們?nèi)绾问褂?Python Kubernetes API 執(zhí)行上述 1-3 的步驟?關(guān)于如何將代碼從 Python API 提取到 YAML存在多個(gè)問(wèn)題,但不清楚如何轉(zhuǎn)換 Kubernetes API 對(duì)象。
查看完整描述

4 回答

?
繁花不似錦

TA貢獻(xiàn)1851條經(jīng)驗(yàn) 獲得超4個(gè)贊

只需使用to_dict()Kubernetes 客戶端對(duì)象現(xiàn)在提供的。請(qǐng)注意,它會(huì)創(chuàng)建部分深度副本。所以為了安全起見(jiàn):


copied_obj = copy.deepcopy(obj.to_dict())

字典可以傳遞給create*和patch*方法。


為方便起見(jiàn),您還可以將 dict 包裝在Prodict.


copied_obj = Prodict.from_dict(copy.deepcopy(obj.to_dict()))

最后一個(gè)問(wèn)題是去掉多余的字段。(不幸的是,Kubernetes 將它們散布在整個(gè)對(duì)象中。)我使用kopf的內(nèi)部工具來(lái)獲取對(duì)象的“本質(zhì)”。(它負(fù)責(zé)深層副本。)


copied_obj = kopf.AnnotationsDiffBaseStorage().build(body=kopf.Body(obj.to_dict()))

copied_obj = Prodic.from_dict(copied_obj)


查看完整回答
反對(duì) 回復(fù) 2022-07-12
?
喵喵時(shí)光機(jī)

TA貢獻(xiàn)1846條經(jīng)驗(yàn) 獲得超7個(gè)贊

在查看了需求之后,我花了幾個(gè)小時(shí)研究 Kubernetes Python API。問(wèn)題 340和其他人詢問(wèn)如何將 Kubernetes API 對(duì)象轉(zhuǎn)換為dict.,但我發(fā)現(xiàn)的唯一解決方法是檢索原始數(shù)據(jù),然后轉(zhuǎn)換為 JSON。

筆記:

  • 確保設(shè)置KUBECONFIG=config,以便您可以指向一個(gè)集群

  • 確保調(diào)整給定命名空間中要克隆的相應(yīng)對(duì)象的值origin_obj_name = "istio-ingressgateway"和名稱。origin_obj_namespace = "istio-system"

import os

import logging

import yaml

import json

logging.basicConfig(level = logging.INFO)


import crayons

from kubernetes import client, config

from kubernetes.client.rest import ApiException


LOGGER = logging.getLogger(" IngressGatewayCreator ")


class IngressGatewayCreator:


    @staticmethod

    def clone_default_ingress(clone_context):

        # Clone the deployment

        IngressGatewayCreator.clone_deployment_object(clone_context)


        # Clone the deployment's HPA

        IngressGatewayCreator.clone_hpa_object(clone_context)


    @staticmethod

    def clone_deployment_object(clone_context):

        kubeconfig = os.getenv('KUBECONFIG')

        config.load_kube_config(kubeconfig)

        v1apps = client.AppsV1beta1Api()


        deployment_name = clone_context.origin_obj_name

        namespace = clone_context.origin_obj_namespace


        try:

            # gets an instance of the api without deserialization to model

            # https://github.com/kubernetes-client/python/issues/574#issuecomment-405400414

            deployment = v1apps.read_namespaced_deployment(deployment_name, namespace, _preload_content=False)


        except ApiException as error:

            if error.status == 404:

                LOGGER.info("Deployment %s not found in namespace %s", deployment_name, namespace)

                return

            raise


        # Clone the object deployment as a dic

        cloned_dict = IngressGatewayCreator.clone_k8s_object(deployment, clone_context)


        # Change additional objects

        cloned_dict["spec"]["selector"]["matchLabels"]["istio"] = clone_context.name

        cloned_dict["spec"]["template"]["metadata"]["labels"]["istio"] = clone_context.name


        # Save the deployment template in the output dir

        context.save_clone_as_yaml(cloned_dict, "deployment")


    @staticmethod

    def clone_hpa_object(clone_context):

        kubeconfig = os.getenv('KUBECONFIG')

        config.load_kube_config(kubeconfig)

        hpas = client.AutoscalingV1Api()


        hpa_name = clone_context.origin_obj_name

        namespace = clone_context.origin_obj_namespace


        try:

            # gets an instance of the api without deserialization to model

            # https://github.com/kubernetes-client/python/issues/574#issuecomment-405400414

            hpa = hpas.read_namespaced_horizontal_pod_autoscaler(hpa_name, namespace, _preload_content=False)


        except ApiException as error:

            if error.status == 404:

                LOGGER.info("HPA %s not found in namespace %s", hpa_name, namespace)

                return

            raise


        # Clone the object deployment as a dic

        cloned_dict = IngressGatewayCreator.clone_k8s_object(hpa, clone_context)


        # Change additional objects

        cloned_dict["spec"]["scaleTargetRef"]["name"] = clone_context.name


        # Save the deployment template in the output dir

        context.save_clone_as_yaml(cloned_dict, "hpa")


    @staticmethod

    def clone_k8s_object(k8s_object, clone_context):

        # Manipilate in the dict level, not k8s api, but from the fetched raw object

        # https://github.com/kubernetes-client/python/issues/574#issuecomment-405400414

        cloned_obj = json.loads(k8s_object.data)


        labels = cloned_obj['metadata']['labels']

        labels['istio'] = clone_context.name


        cloned_obj['status'] = None


        # Scrub by removing the "null" and "None" values

        cloned_obj = IngressGatewayCreator.scrub_dict(cloned_obj)


        # Patch the metadata with the name and labels adjusted

        cloned_obj['metadata'] = {

            "name": clone_context.name,

            "namespace": clone_context.origin_obj_namespace,

            "labels": labels

        }


        return cloned_obj


    # https://stackoverflow.com/questions/12118695/efficient-way-to-remove-keys-with-empty-strings-from-a-dict/59959570#59959570

    @staticmethod

    def scrub_dict(d):

        new_dict = {}

        for k, v in d.items():

            if isinstance(v, dict):

                v = IngressGatewayCreator.scrub_dict(v)

            if isinstance(v, list):

                v = IngressGatewayCreator.scrub_list(v)

            if not v in (u'', None, {}):

                new_dict[k] = v

        return new_dict


    # https://stackoverflow.com/questions/12118695/efficient-way-to-remove-keys-with-empty-strings-from-a-dict/59959570#59959570

    @staticmethod

    def scrub_list(d):

        scrubbed_list = []

        for i in d:

            if isinstance(i, dict):

                i = IngressGatewayCreator.scrub_dict(i)

            scrubbed_list.append(i)

        return scrubbed_list



class IngressGatewayContext:


    def __init__(self, manifest_dir, name, hostname, nats, type):

        self.manifest_dir = manifest_dir

        self.name = name

        self.hostname = hostname

        self.nats = nats

        self.ingress_type = type


        self.origin_obj_name = "istio-ingressgateway"

        self.origin_obj_namespace = "istio-system"


    def save_clone_as_yaml(self, k8s_object, kind):

        try:

            # Just try to create if it doesn't exist

            os.makedirs(self.manifest_dir)


        except FileExistsError:

            LOGGER.debug("Dir already exists %s", self.manifest_dir)


        full_file_path = os.path.join(self.manifest_dir, self.name + '-' + kind + '.yaml')


        # Store in the file-system with the name provided

        # https://stackoverflow.com/questions/12470665/how-can-i-write-data-in-yaml-format-in-a-file/18210750#18210750

        with open(full_file_path, 'w') as yaml_file:

            yaml.dump(k8s_object, yaml_file, default_flow_style=False)


        LOGGER.info(crayons.yellow("Saved %s '%s' at %s: \n%s"), kind, self.name, full_file_path, k8s_object)


try:

    k8s_clone_name = "http2-ingressgateway"

    hostname = "my-nlb-awesome.a.company.com"

    nats = ["123.345.678.11", "333.444.222.111", "33.221.444.23"]

    manifest_dir = "out/clones"


    context = IngressGatewayContext(manifest_dir, k8s_clone_name, hostname, nats, "nlb")


    IngressGatewayCreator.clone_default_ingress(context)


except Exception as err:

  print("ERROR: {}".format(err))


查看完整回答
反對(duì) 回復(fù) 2022-07-12
?
墨色風(fēng)雨

TA貢獻(xiàn)1853條經(jīng)驗(yàn) 獲得超6個(gè)贊

不是python,但我jq過(guò)去曾使用過(guò)每個(gè)用例所需的小定制來(lái)快速克隆一些東西(通常將秘密克隆到新的命名空間中)。


kc get pod whatever-85pmk -o json \

 | jq 'del(.status, .metadata ) | .metadata.name="newname"' \

 | kc apply -f - -o yaml --dry-run 


查看完整回答
反對(duì) 回復(fù) 2022-07-12
?
侃侃無(wú)極

TA貢獻(xiàn)2051條經(jīng)驗(yàn) 獲得超10個(gè)贊

這對(duì)Hikaru來(lái)說(shuō)真的很容易。


這是我自己的開(kāi)源項(xiàng)目中的一個(gè)示例:


def duplicate_without_fields(obj: HikaruBase, omitted_fields: List[str]):

    """

    Duplicate a hikaru object, omitting the specified fields

    This is useful when you want to compare two versions of an object and first "cleanup" fields that shouldn't be

    compared.

    :param HikaruBase obj: A kubernetes object

    :param List[str] omitted_fields: List of fields to be omitted. Field name format should be '.' separated

                                     For example: ["status", "metadata.generation"]

    """

    if obj is None:

        return None


    duplication = obj.dup()


    for field_name in omitted_fields:

        field_parts = field_name.split(".")

        try:

            if len(field_parts) > 1:

                parent_obj = duplication.object_at_path(field_parts[:-1])

            else:

                parent_obj = duplication


            setattr(parent_obj, field_parts[-1], None)

        except Exception:

            pass  # in case the field doesn't exist on this object


    return duplication

之后將對(duì)象轉(zhuǎn)儲(chǔ)到 yaml 或?qū)⑵渲匦聭?yīng)用到集群對(duì)于 Hikaru 來(lái)說(shuō)是微不足道的


我們使用它來(lái)清理對(duì)象,以便在對(duì)象更改時(shí)向用戶顯示 github 風(fēng)格的差異,而不會(huì)出現(xiàn)經(jīng)常更改的垃圾郵件字段,例如generation


查看完整回答
反對(duì) 回復(fù) 2022-07-12
  • 4 回答
  • 0 關(guān)注
  • 193 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)