2
from kubernetes import client, config
config.load_kube_config()
api = client.AppsV1Api()

deployment = api.read_namespaced_deployment(name='foo', namespace='bar')

我试图将关联对象添加到部署规范中我收到了这个错误

deployment.spec.affinity.nodeAffinity.requiredDuringSchedulingIgnoredDuringExecution.nodeSelectorTerms = [{'nodeSelectorTerms':[{'matchExpressions':[{'key': 'kubernetes.io/hostname','operator': 'NotIn','values': ["awesome-node"]}]}]}]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'V1DeploymentSpec' object has no attribute 'affinity'
4

1 回答 1

3

你看错地方了。deployment.spec.template.spec.affinity当您查看部署规范 ( ) 时,亲和力属于 pod 模板规范( deployment.spec.affinity)。

以下是如何完全替换现有的亲和力(即使它是无):

from kubernetes import client, config
config.load_kube_config()
api = client.AppsV1Api()

# read current state
deployment = api.read_namespaced_deployment(name='foo', namespace='bar')

# check current state
#print(deployment.spec.template.spec.affinity)

# create affinity objects
terms = client.models.V1NodeSelectorTerm(
    match_expressions=[
        {'key': 'kubernetes.io/hostname',
         'operator': 'NotIn',
         'values': ["awesome-node"]}
    ]
)
node_selector = client.models.V1NodeSelector(node_selector_terms=[terms])
node_affinity = client.models.V1NodeAffinity(
    required_during_scheduling_ignored_during_execution=node_selector
)
affinity = client.models.V1Affinity(node_affinity=node_affinity)

# replace affinity in the deployment object
deployment.spec.template.spec.affinity = affinity

# finally, push the updated deployment configuration to the API-server
api.replace_namespaced_deployment(name=deployment.metadata.name,
                                  namespace=deployment.metadata.namespace,
                                  body=deployment)
于 2022-02-02T15:19:57.017 回答