How to use the kubernetes.client.V1ObjectMeta function in kubernetes

To help you get started, we’ve selected a few kubernetes examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github vapor-ware / kubetest / kubetest / objects / namespace.py View on Github external
def new(cls, name: str) -> 'Namespace':
        """Create a new Namespace with object backing.

        Args:
            name: The name of the new Namespace.

        Returns:
            A new Namespace instance.
        """
        return cls(client.V1Namespace(
            metadata=client.V1ObjectMeta(
                name=name
            )
github microsoft / pai / src / rest-server / deploy / legacy_user_migrate.py View on Github external
def create_secret_in_namespace_if_not_exist(self, payload, namespace):
        if self.in_cluster:
            config.load_incluster_config()
        else:
            config.load_kube_config(config_file="~/.kube/config")
        try:
            api_instance = client.CoreV1Api()
            api_instance.read_namespaced_secret(payload['metadata']['name'], namespace)
        except ApiException as e:
            if e.status == 404:
                try:
                    api_instance = client.CoreV1Api()
                    meta_data = client.V1ObjectMeta()
                    meta_data.name = payload['metadata']['name']
                    body = client.V1Secret(
                        metadata=meta_data,
                        data=payload['data']
                    )
                    api_instance.create_namespaced_secret(namespace, body)
                except ApiException as create_e:
                    logger.error("Exception when calling CoreV1Api->create_namespaced_secret: %s\n" % create_e)
                    sys.exit(1)
            else:
                logger.error("Exception when calling CoreV1Api->read_namespaced_secret: %s\n" % e)
                sys.exit(1)
github kubessh / kubessh / kubessh / serialization.py View on Github external
'If trying to pass a yaml filename then use '
               'KubeCluster.from_yaml')
        raise TypeError(msg % pod_template)

    if isinstance(pod_template, dict):
        msg = ('Expected a kubernetes.client.V1Pod object, got %s'
               'If trying to pass a dictionary specification then use '
               'KubeCluster.from_dict')
        raise TypeError(msg % str(pod_template))

    pod_template = copy.deepcopy(pod_template)

    # Make sure metadata / labels / env objects exist, so they can be modified
    # later without a lot of `is None` checks
    if pod_template.metadata is None:
        pod_template.metadata = client.V1ObjectMeta()
    if pod_template.metadata.labels is None:
        pod_template.metadata.labels = {}

    if pod_template.spec.containers[0].env is None:
        pod_template.spec.containers[0].env = []

    return pod_template
github IntelAI / nauta / applications / tensorboard-service / app / k8s / models.py View on Github external
tensorboard_image = dls4e_config.get_tensorboard_image()
        tensorboard_proxy_image = dls4e_config.get_activity_proxy_image()

        deployment = k8s.V1Deployment(api_version='apps/v1',
                                      kind='Deployment',
                                      metadata=k8s.V1ObjectMeta(
                                          name=k8s_name,
                                          labels=deployment_labels
                                      ),
                                      spec=k8s.V1DeploymentSpec(
                                          replicas=1,
                                          selector=k8s.V1LabelSelector(
                                              match_labels=deployment_labels
                                          ),
                                          template=k8s.V1PodTemplateSpec(
                                              metadata=k8s.V1ObjectMeta(
                                                  labels=deployment_labels
                                              ),
                                              spec=k8s.V1PodSpec(
                                                  priority_class_name="medium-priority",
                                                  containers=[
                                                      k8s.V1Container(
                                                          name='app',
                                                          image=tensorboard_image,
                                                          command=tensorboard_command,
                                                          volume_mounts=volume_mounts),
                                                      k8s.V1Container(
                                                          name='proxy',
                                                          image=tensorboard_proxy_image,
                                                          ports=[
                                                              k8s.V1ContainerPort(
                                                                  container_port=80
github wylok / sparrow / module / k8s_resource.py View on Github external
else:
                    if Rules_infos:
                        path, serviceName, servicePort = Rules_infos[0]
                        Rules.append(client.V1beta1IngressRule(host=domain,
                                                               http=client.V1beta1HTTPIngressRuleValue(
                                                                   paths=[client.V1beta1HTTPIngressPath(
                                                                       client.V1beta1IngressBackend(
                                                                           service_name=serviceName,
                                                                           service_port=int(servicePort)
                                                                       ))])
                                                               ))
            spec = client.V1beta1IngressSpec(rules=Rules)
            ingress = client.V1beta1Ingress(
                api_version='extensions/v1beta1',
                kind='Ingress',
                metadata=client.V1ObjectMeta(name='nginx-ingress',
                                             namespace=self.namespace,
                                             annotations={'kubernetes.io/ingress.class': 'nginx'}), spec=spec)
            api_instance.patch_namespaced_ingress(body=ingress, namespace=self.namespace, name='nginx-ingress')
            return True
        finally:
            db_op.DB.session.remove()
github jupyterhub / binderhub / binderhub / build.py View on Github external
client.V1VolumeMount(mount_path="/var/run/docker.sock", name="docker-socket")
        ]
        volumes = [client.V1Volume(
            name="docker-socket",
            host_path=client.V1HostPathVolumeSource(path=self.docker_api_url)
        )]

        if self.push_secret:
            volume_mounts.append(client.V1VolumeMount(mount_path="/root/.docker", name='docker-push-secret'))
            volumes.append(client.V1Volume(
                name='docker-push-secret',
                secret=client.V1SecretVolumeSource(secret_name=self.push_secret)
            ))

        self.pod = client.V1Pod(
            metadata=client.V1ObjectMeta(
                name=self.name,
                labels={
                    "name": self.name,
                    "component": "binderhub-build",
                },
            ),
            spec=client.V1PodSpec(
                containers=[
                    client.V1Container(
                        image=self.builder_image,
                        name="builder",
                        args=self.get_cmd(),
                        image_pull_policy='Always',
                        volume_mounts=volume_mounts,
                        resources=client.V1ResourceRequirements(
                            limits={'memory': self.memory_limit},
github IntelAI / inference-model-manager / management / management_api / tenants / tenants_utils.py View on Github external
def create_secret(name, cert, id_token):
    cert_secret_metadata = k8s_client.V1ObjectMeta(name=CERT_SECRET_NAME)
    cert_secret_data = {"ca.crt": cert}
    cert_secret = k8s_client.V1Secret(api_version="v1", data=cert_secret_data,
                                      kind="Secret", metadata=cert_secret_metadata,
                                      type="Opaque")
    api_instance = get_k8s_api_client(id_token)
    try:
        response = api_instance.create_namespaced_secret(namespace=name,
                                                         body=cert_secret)
    except ApiException as apiException:
        raise KubernetesCreateException('secret', apiException)

    logger.info('Secret {} created'.format(CERT_SECRET_NAME))
    return response
github funcx-faas / funcX / funcx / executor / parsl / providers / kubernetes / kube.py View on Github external
env=[environment_vars])
        # Create a secret to enable pulling images from secure repositories
        secret = None
        if self.secret:
            secret = client.V1LocalObjectReference(name=self.secret)

        # Create list of volumes from (pvc, mount) tuples
        volume_defs = []
        for volume in volumes:
            volume_defs.append(client.V1Volume(name=volume[0],
                                               persistent_volume_claim=client.V1PersistentVolumeClaimVolumeSource(
                                                   claim_name=volume[0])))

        # Create and configurate a spec section
        template = client.V1PodTemplateSpec(
            metadata=client.V1ObjectMeta(labels={"app": job_name}),
            spec=client.V1PodSpec(containers=[container],
                                  image_pull_secrets=[secret],
                                  volumes=volume_defs
                                  ))

        # Create the specification of deployment
        spec = client.ExtensionsV1beta1DeploymentSpec(replicas=replicas,
                                                      template=template)

        # Instantiate the deployment object
        deployment = client.ExtensionsV1beta1Deployment(
            api_version="extensions/v1beta1",
            kind="Deployment",
            metadata=client.V1ObjectMeta(name=deployment_name),
            spec=spec)
github noris-network / koris / koris / deploy / k8s.py View on Github external
token_secret = rand_string(16)
        data = {'description': get_token_description(),
                'token-id': tid,
                'token-secret': token_secret,
                'expiration':
                datetime.strftime(datetime.now() + timedelta(hours=2),
                                  "%Y-%m-%dT%H:%M:%SZ"),
                'usage-bootstrap-authentication': 'true',
                'usage-bootstrap-signing': 'true',
                'auth-extra-groups':
                'system:bootstrappers:kubeadm:default-node-token', }

        for k, val in data.items():
            data[k] = base64.b64encode(val.encode()).decode()
        sec = k8sclient.V1Secret(data=data)
        sec.metadata = k8sclient.V1ObjectMeta(
            **{'name': 'bootstrap-token-%s' % tid, 'namespace': 'kube-system'})
        sec.type = 'bootstrap.kubernetes.io/token'

        self.api.create_namespaced_secret(namespace="kube-system", body=sec)
        return ".".join((tid, token_secret))