使用python创建kubernetes pod时如何传递安全上下文?

2024-06-01 04:37:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用kubernetes pod操作符,我需要在创建pod时传递一些安全上下文,以便有权装载s3fs,但是当我以下面的格式传递它时,它没有效果,我还能做什么

我尝试传递的安全上下文是:

security_context = {
            "privileged": True,  # I have tried to pass "true", not working too
            "capabilities": {
                "add": ["SYS_ADMIN"]
            }
        }

yaml中对应的配置为:

securityContext:
  privileged: true
  capabilities:
    add:
      - SYS_ADMIN

测试代码为:

#!/usr/bin/python
# -*- coding: utf-8 -*-
import datetime
from unittest import TestCase
from airflow.operators.kubernetes_pod_operator import KubernetesPodOperator


class TestKubernetesPodOperator(TestCase):
    def setUp(self):
        self.namespace = "airflow-test"
        self.image = "airflow-dc/airflow-dc:v6.12.34"
        self.name = "test"
        self.config_file = "/home/think/.kube/config.yml"

        self.cluster_context = "default"

        self.dag_id = "test_onoff"
        self.task_id = "root_test_onoff"
        self.execution_date = datetime.datetime.now()

        self.context = {"dag_id": self.dag_id,
                        "task_id": self.task_id,
                        "execution_date": self.execution_date}

        self.cmds = ["echo"]
        self.arguments = ["hello world"]

        self.resources = {
            "limits":
                {"memory": "512Mi",
                 "cpu": "500m"},
            "requests": {
                "memory": "512Mi",
                "cpu": "500m"}
        }

        # this is the security context that I passed to kubernetes, but it does not work
        self.security_context = {
            "privileged": True,  # I have tried to pass "true", not working too
            "capabilities": {
                "add": ["SYS_ADMIN"]
            }
        }

        self.operator = KubernetesPodOperator(
            namespace=self.namespace, image=self.image, name=self.name,
            cluster_context=self.cluster_context,
            config_file=self.config_file,
            cmds=self.cmds,
            arguments=self.arguments,
            startup_timeout_seconds=600,
            is_delete_operator_pod=True,
            resources=self.resources,
            security_context=self.security_context,
            **self.context)

    def test_execute(self):
        self.operator.execute(self.context)

我可以用kubectl以低于yaml的优先级启动pod,但是如果我用python启动pod,我就不能用privileged启动它,这对我来说是导入,因为我需要装载s3fs来保存一些数据

kind: Pod
apiVersion: v1
metadata:
  name: test-pod-3
spec:
  containers:
  - name: test-pod-3
    image: airflow-dc/airflow-dc:v6.12.34
    command:
    - "/bin/sh"
    args:
    - "-c"
    - "touch /mnt/SUCCESS && sleep 60000 || exit 1"
    resources:
      limits:
        memory: 512Mi
        cpu: 500m
      requests:
        memory: 512Mi
        cpu: 500m
    securityContext:
      privileged: true
      capabilities:
        add:
          - SYS_ADMIN

Tags: nametestselfaddidtrueadminsys