コード例 #1
1
ファイル: control.py プロジェクト: Greenun/KubeTestoy
def create_deployment(project_name: str,
                      images: list,
                      ports: dict = {},
                      envs: dict = {}):
    # parameter : project_name:str, images:list, ports:dict {image_name: port_list}, envs:dict (image_name: env)
    # label name --> project name + etc..
    # readinessProbe .. tcp or http
    # envs --> image_name : env --> env: list of dict ({name: xxx, value: xxx})
    containers = list()
    for image in images:
        name = image.split(":")[0]
        tag = image.split(":")[1]
        container_ports = [client.V1ContainerPort(p) for p in ports[image]
                           ] if ports and ports.get(image) else None
        # print(envs)
        container_envs = [client.V1EnvVar(name=e.get("name"), value=e.get("value")) for e in envs.get(image)]\
            if envs.get(image) else None
        image = REGISTRY_PREFIX + image

        containers.append(
            client.V1Container(
                name=name,
                image=image,
                # ports=container_ports,
                env=container_envs,
                readiness_probe=client.V1Probe(
                    initial_delay_seconds=10,
                    period_seconds=15,
                    tcp_socket=client.V1TCPSocketAction(
                        port=container_ports[0].container_port)),
                image_pull_policy="Always"
                if tag == "latest" else "IfNotPresent"))
    # print(containers)

    project_hash = hashlib.sha256(project_name.encode()).hexdigest()[:16]
    labels = {"identifier": project_hash}
    template = client.V1PodTemplateSpec(
        metadata=client.V1ObjectMeta(labels=labels),
        spec=client.V1PodSpec(containers=containers))

    spec = client.V1DeploymentSpec(
        replicas=1,  # default
        template=template,
        selector={'matchLabels': labels},
    )

    deployment = client.V1Deployment(
        api_version="apps/v1",
        kind="Deployment",
        metadata=client.V1ObjectMeta(name=project_hash + "-deployment"),
        spec=spec)

    v1 = client.AppsV1Api()
    resp = v1.create_namespaced_deployment(body=deployment,
                                           namespace="default")
    # print(resp)
    return resp
コード例 #2
0
def youTube_control_deployment_object_create(port_allocated):

    # define container
    container = client.V1Container(
        name="youtube-control",
        image="youtube-server",
        image_pull_policy="Never",
        ports=[client.V1ContainerPort(container_port=port_allocated)])

    # define template
    template = client.V1PodTemplateSpec(
        metadata=client.V1ObjectMeta(
            labels={"youtube-control": "youtube-control"}),
        spec=client.V1PodSpec(containers=[container]))

    # define spec
    spec = client.V1DeploymentSpec(
        replicas=1,
        template=template,
        selector={'matchLabels': {
            'youtube-control': 'youtube-control'
        }})

    # Instantiate the deployment object
    deployment_object = client.V1Deployment(
        api_version="apps/v1",
        kind="Deployment",
        metadata=client.V1ObjectMeta(name="youtube-control"),
        spec=spec)

    return deployment_object
コード例 #3
0
def create_deployment_object(data):
    # Configure Pod template container

    template_spec = common.create_pod_template_spec(data=data)

    labels_array = data["labels"].split(',')
    labels = dict(s.split('=') for s in labels_array)

    meta = client.V1ObjectMeta(labels=labels)

    annotations = None
    if "annotations" in data:
        annotations_array = data["annotations"].split(',')
        annotations = dict(s.split('=') for s in annotations_array)
        meta.annotations = annotations

    # Create and configure a spec section
    template = client.V1PodTemplateSpec(metadata=meta, spec=template_spec)
    # Create the specification of deployment
    spec = client.V1DeploymentSpec(replicas=int(data["replicas"]),
                                   selector={"matchLabels": labels},
                                   template=template)
    # Instantiate the deployment object
    deployment = client.V1Deployment(api_version=data["api_version"],
                                     kind="Deployment",
                                     metadata=client.V1ObjectMeta(
                                         labels=labels,
                                         namespace=data["namespace"],
                                         name=data["name"]),
                                     spec=spec)

    return deployment
コード例 #4
0
def patch_scale_deployment(deployment_name, namespace, replicas):
    appsv1 = client.AppsV1Api()
    return appsv1.patch_namespaced_deployment_scale(
        namespace=namespace,
        name=deployment_name,
        body=client.V1Deployment(spec=client.V1DeploymentSpec(
            replicas=replicas)))
コード例 #5
0
def create_deployment_object(
        no_replicas: int,
        deployment_images: str,
        deployment_name: str,
        container_port: int,
        external_port: bool,
) -> V1Deployment:
    """
    We create a deployment according to the specified arguments.
    :param no_replicas: Number of container in the pod.
    :param deployment_images: The image name in the docker environment for the moles.
    :param deployment_name: The name of the deployment.
    :param container_port: port of the web_server.
    :param external_port: whether the port should be an external port.
    :return: Deployment setup.
    """
    container = create_container_object(deployment_images, container_port, external_port)

    # Create and configure a spec section
    template = client.V1PodTemplateSpec(
        metadata=client.V1ObjectMeta(labels={"app": "molerelay"}),
        spec=client.V1PodSpec(containers=[container]))
    # Create the specification of deployment
    spec = client.V1DeploymentSpec(
        replicas=no_replicas,
        template=template,
        selector={'matchLabels': {'app': 'molerelay'}})
    # Instantiate the deployment object
    deployment = client.V1Deployment(
        api_version="apps/v1",
        kind="Deployment",
        metadata=client.V1ObjectMeta(name=deployment_name),
        spec=spec)

    return deployment
コード例 #6
0
def create_deployment(apps_v1_api):
    container = client.V1Container(
        name="deployment",
        image="gcr.io/google-appengine/fluentd-logger",
        image_pull_policy="Never",
        ports=[client.V1ContainerPort(container_port=5678)],
    )
    # Template
    template = client.V1PodTemplateSpec(
        metadata=client.V1ObjectMeta(labels={"app": "deployment"}),
        spec=client.V1PodSpec(containers=[container]))
    # Spec
    spec = client.V1DeploymentSpec(
        replicas=1,
        template=template)
    # Deployment
    deployment = client.V1Deployment(
        api_version="apps/v1",
        kind="Deployment",
        metadata=client.V1ObjectMeta(name="deployment"),
        spec=spec)
    # Creation of the Deployment in specified namespace
    # (Can replace "default" with a namespace you may have created)
    apps_v1_api.create_namespaced_deployment(
        namespace="default", body=deployment
    )
    def create_deployment(self, namespace=None, *args, **kwargs):
        deploy_name = kwargs.get("name")
        deployment_metadata = client.V1ObjectMeta(name=deploy_name)
        template_spec = self._generate_pod_template(*args, **kwargs)
        body = client.V1Deployment(
            api_version="apps/v1",
            kind="Deployment",
            metadata=deployment_metadata,
            spec=client.V1DeploymentSpec(
                selector=client.V1LabelSelector(match_labels={
                    "app": kwargs.get("name"),
                }),
                template=template_spec),
        )

        api_instance = client.AppsV1Api()

        try:
            api_instance.create_namespaced_deployment(namespace=namespace,
                                                      body=body,
                                                      pretty="true")
        except ApiException as e:
            LOG.error("Exception when call AppsV1beta1Api: %s", e)
            raise e

        return True
コード例 #8
0
ファイル: containerMaker.py プロジェクト: kitakou0313/Otamesi
def create_deployment_object(deployImage):
    # Configureate Pod template container
    container = client.V1Container(
        name="articleimg",
        image=deployImage,
    )

    ttydContainer = client.V1Container(
        name="ttyd",
        image="kitakou0313/ubuntuwithttyd:20.10",
        ports=[client.V1ContainerPort(container_port=7681)],
    )

    # Create and configurate a spec section
    template = client.V1PodTemplateSpec(
        metadata=client.V1ObjectMeta(labels={"app": "ttyd"}),
        spec=client.V1PodSpec(containers=[container, ttydContainer],
                              share_process_namespace=True))
    # Create the specification of deployment
    spec = client.V1DeploymentSpec(replicas=1,
                                   template=template,
                                   selector={'matchLabels': {
                                       'app': 'ttyd'
                                   }})
    # Instantiate the deployment object
    deployment = client.V1Deployment(
        api_version="apps/v1",
        kind="Deployment",
        metadata=client.V1ObjectMeta(name=DEPLOYMENT_NAME +
                                     randomStringGen.genRandomLowerString()),
        spec=spec)

    return deployment
コード例 #9
0
 def create_iperf_deploy(self, name):
     self.apps_v1_api.create_namespaced_deployment(
         namespace='default',
         body=client.V1Deployment(
             api_version="apps/v1",
             kind="Deployment",
             metadata=client.V1ObjectMeta(
                 name=name,
                 namespace="default",
                 labels={'app': name}
             ),
             spec=client.V1DeploymentSpec(
                 replicas=10,
                 selector=client.V1LabelSelector(match_labels={'app': name}),
                 template=client.V1PodTemplateSpec(
                     metadata=client.V1ObjectMeta(labels={'app': name}),
                     spec=client.V1PodSpec(
                         containers=[
                             client.V1Container(
                                 name=name,
                                 tty=True,
                                 image="zhuangweikang/k8stc:latest",
                                 image_pull_policy="IfNotPresent",
                                 security_context=client.V1SecurityContext(
                                     capabilities=client.V1Capabilities(add=["NET_ADMIN"])),
                                 resources=client.V1ResourceRequirements(
                                     limits={"cpu": "100m", "memory": "1Gi"},
                                     requests={"cpu": "100m", "memory": "1Gi"})
                             )
                         ]
                     )
                 )
             )
         )
     )
コード例 #10
0
ファイル: k8s-api.py プロジェクト: lmdkfs/test
    def create_deployment_object(self, deployment_name: str, **kwargs: dict):
        """
        Configureate Deployment template container
        :return:
        """

        # Configureate Pod template container
        container = client.V1Container(
            name=kwargs['spec']['template']['spec']['containers'][0]['name'],
            image=kwargs['spec']['template']['spec']['containers'][0]['image'],
            ports=[client.V1ContainerPort(container_port=80)])

        # Create and configureate a spec section
        template = client.V1PodTemplateSpec(
            metadata=client.V1ObjectMeta(
                labels=kwargs['spec']['template']['metadata']['labels']),
            spec=client.V1PodSpec(containers=[container]))
        print()
        # Create the specification of deployment
        spec = client.V1DeploymentSpec(replicas=kwargs['spec']['replicas'],
                                       template=template,
                                       selector=kwargs['spec']['selector'])

        # Instantiate the deployment object
        deployment = client.V1Deployment(
            api_version='apps/v1',
            kind='Deployment',
            metadata=client.V1ObjectMeta(name=deployment_name),
            spec=spec)
        return deployment
コード例 #11
0
def create_deployment_object(deployment_name, deployment_image,
                             deployment_replicas):
    # Configureate Pod template container
    container = client.V1Container(
        name=deployment_name,
        image=deployment_image,
        #ports=[client.V1ContainerPort(container_port=80)],
        resources=client.V1ResourceRequirements(requests={
            "cpu": "100m",
            "memory": "200Mi"
        },
                                                limits={
                                                    "cpu": "500m",
                                                    "memory": "500Mi"
                                                }))
    # Create and configurate a spec section
    template = client.V1PodTemplateSpec(
        metadata=client.V1ObjectMeta(labels={"app": deployment_name}),
        spec=client.V1PodSpec(containers=[container]))
    # Create the specification of deployment
    spec = client.V1DeploymentSpec(
        replicas=deployment_replicas,
        template=template,
        selector={'matchLabels': {
            'app': deployment_name
        }})
    # Instantiate the deployment object
    deployment = client.V1Deployment(
        api_version="apps/v1",
        kind="Deployment",
        metadata=client.V1ObjectMeta(name=deployment_name),
        spec=spec)

    return deployment
コード例 #12
0
    def _build_deployment(self, metadata):
        """Build deployment Kubernetes object.

        :param metadata: Common Kubernetes metadata for the interactive
            deployment.
        """
        container = client.V1Container(name=self.deployment_name, image=self.image)
        pod_spec = client.V1PodSpec(
            containers=[container],
            node_selector=REANA_RUNTIME_SESSIONS_KUBERNETES_NODE_LABEL,
        )
        template = client.V1PodTemplateSpec(
            metadata=client.V1ObjectMeta(labels={"app": self.deployment_name}),
            spec=pod_spec,
        )
        spec = client.V1DeploymentSpec(
            selector=client.V1LabelSelector(match_labels={"app": self.deployment_name}),
            replicas=1,
            template=template,
        )
        deployment = client.V1Deployment(
            api_version="apps/v1", kind="Deployment", metadata=metadata, spec=spec,
        )

        return deployment
コード例 #13
0
def create_quick_deployment_definition(deploymentName, deployImage, deployPorts, serviceAccount):
    # Configureate Pod template container
        container = client.V1Container(
            name=deploymentName,
            image=deployImage,
            ports=[client.V1ContainerPort(container_port=deployPorts)]
        )
        # Create and configurate a spec section
        template = client.V1PodTemplateSpec(
            metadata=client.V1ObjectMeta(labels={"app": deploymentName}),
            spec=client.V1PodSpec(service_account=serviceAccount,
                                service_account_name=serviceAccount,
                                containers=[container]))

# # Create and configurate a spec section
#         template = client.V1PodTemplateSpec(
#             metadata=client.V1ObjectMeta(labels={"app": self.watcherApplicationName}),
#             spec=client.V1PodSpec(containers=[container]))            
        # Create the specification of deployment
        spec = client.V1DeploymentSpec(
            replicas=1,
            template=template,
            selector={'matchLabels': {'app':  deploymentName}})
        # Instantiate the deployment object
        deployment = client.V1Deployment(
            api_version="apps/v1",
            kind="Deployment",
            metadata=client.V1ObjectMeta(name= deploymentName),
            spec=spec)
        return deployment
コード例 #14
0
 def patch_namespaced_deployment(self, name, image, namespace="default"):
     """Scale deployment using name in namespace to replicas"""
     # Configureate Pod template container
     container = client.V1Container(name=name)
     # Create and configurate a spec section
     template = client.V1PodTemplateSpec(
         metadata=client.V1ObjectMeta(labels={"app": name}),
         spec=client.V1PodSpec(containers=[container]))
     # Create the specification of deployment
     spec = client.V1DeploymentSpec(template=template,
                                    selector={'matchLabels': {
                                        'app': name
                                    }})
     # Instantiate the deployment object
     deployment = client.V1Deployment(
         api_version="apps/v1",
         kind="Deployment",
         metadata=client.V1ObjectMeta(name=name),
         spec=spec)
     deployment.spec.template.spec.containers[0].image = image
     try:
         self.apps_cli.patch_namespaced_deployment(name, namespace,
                                                   deployment)
         logger.info(
             'Image of deployemnt {} in namespace {} has been updated to {}'
             .format(name, namespace, image))
         return
     except client.rest.ApiException as e:
         if e.status == 404 or not e.status:
             logger.info(
                 'Deployment {} in namespace {} is not found'.format(
                     name, namespace))
             return
         logger.exception(e)
         return False
コード例 #15
0
ファイル: deployment-worker.py プロジェクト: x0rb3l/skf-flask
def create_deployment_object(deployment):
    try:
        # Configureate Pod template container
        container = client.V1Container(
            name=deployment,
            image="blabla1337/owasp-skf-lab:"+deployment,
            ports=[client.V1ContainerPort(container_port=5000)])
        # Create and configurate a spec section
        template = client.V1PodTemplateSpec(
            metadata=client.V1ObjectMeta(labels={"app": deployment}),
            spec=client.V1PodSpec(containers=[container]))
        # Create the specification of deployment
        spec = client.V1DeploymentSpec(
            replicas=1,
            template=template,
            selector={'matchLabels': {'app': deployment}})
        # Instantiate the deployment object
        deployment = client.V1Deployment(
            api_version="apps/v1",
            kind="Deployment",
            metadata=client.V1ObjectMeta(name=deployment),
            spec=spec)
        return deployment
    except:
        return {'message': 'Failed to deploy, error creation deployment object!'} 
コード例 #16
0
    def _build_deployment(self, metadata):
        """Build deployment Kubernetes object.

        :param metadata: Common Kubernetes metadata for the interactive
            deployment.
        """
        container = client.V1Container(name=self.deployment_name,
                                       image=self.image)
        pod_spec = client.V1PodSpec(
            containers=[container],
            node_selector=REANA_RUNTIME_SESSIONS_KUBERNETES_NODE_LABEL,
            # Disable service discovery with env variables, so that the environment is
            # not polluted with variables like `REANA_SERVER_SERVICE_HOST`
            enable_service_links=False,
        )
        template = client.V1PodTemplateSpec(
            metadata=client.V1ObjectMeta(labels={"app": self.deployment_name}),
            spec=pod_spec,
        )
        spec = client.V1DeploymentSpec(
            selector=client.V1LabelSelector(
                match_labels={"app": self.deployment_name}),
            replicas=1,
            template=template,
        )
        deployment = client.V1Deployment(
            api_version="apps/v1",
            kind="Deployment",
            metadata=metadata,
            spec=spec,
        )

        return deployment
コード例 #17
0
    def create_deployment_object(deploymentName, containerName, imageName,
                                 containerLable, container_Port):
        # Configureate Pod template container
        container = client.V1Container(
            name=containerName,
            image=imageName
            # ports=[client.V1ContainerPort(containerPort=80)]
        )
        # Create and configurate a spec section
        template = client.V1PodTemplateSpec(
            metadata=client.V1ObjectMeta(labels={"app": containerLable}),
            spec=client.V1PodSpec(containers=[container]))
        # Create the specification of deployment
        spec = client.V1DeploymentSpec(
            replicas=1,
            template=template,
            selector={'matchLabels': {
                'app': containerLable
            }})
        # Instantiate the deployment object
        deployment = client.V1Deployment(
            api_version="apps/v1",
            kind="Deployment",
            metadata=client.V1ObjectMeta(name=deploymentName),
            spec=spec)

        return deployment
コード例 #18
0
def create_k8s_deployment(namespace: str, name: str, replicas: int,
                          match_labels: dict, template: dict, user):
    """
    Create a Kubernetes deployment in the cluster.

    Returns the new deployment.
    """
    apps_v1 = get_user_apps_v1(user)
    logger.info(f"Creating Kubernetes deployment '{name}'")
    k8s_containers = [
        client.V1Container(name=c["name"], image=c["image"])
        for c in template["containers"]
    ]
    k8s_labels = {item['key']: item['value'] for item in template['labels']}
    k8s_pod_template = client.V1PodTemplateSpec(
        metadata=client.V1ObjectMeta(name=template['name'], labels=k8s_labels),
        spec=client.V1PodSpec(containers=k8s_containers))
    k8s_match_labels = {item['key']: item['value'] for item in match_labels}
    k8s_deployment = client.V1Deployment(
        metadata=client.V1ObjectMeta(name=name),
        spec=client.V1DeploymentSpec(
            replicas=replicas,
            selector=client.V1LabelSelector(match_labels=k8s_match_labels),
            template=k8s_pod_template))
    apps_v1.create_namespaced_deployment(namespace, k8s_deployment)
コード例 #19
0
ファイル: test_base.py プロジェクト: trapier/node
    def deploy(self, image, name, ns, port, replicas=1, svc_type="NodePort", traffic_policy="Local", cluster_ip=None, ipv6=False):
        """
        Creates a deployment and corresponding service with the given
        parameters.
        """
        # Run a deployment with <replicas> copies of <image>, with the
        # pods labelled with "app": <name>.
        deployment = client.V1Deployment(
            api_version="apps/v1",
            kind="Deployment",
            metadata=client.V1ObjectMeta(name=name),
            spec=client.V1DeploymentSpec(
                replicas=replicas,
                selector={'matchLabels': {'app': name}},
                template=client.V1PodTemplateSpec(
                    metadata=client.V1ObjectMeta(labels={"app": name}),
                    spec=client.V1PodSpec(containers=[
                        client.V1Container(name=name,
                                           image=image,
                                           ports=[client.V1ContainerPort(container_port=port)]),
                    ]))))
        api_response = client.AppsV1Api().create_namespaced_deployment(
            body=deployment,
            namespace=ns)
        logger.debug("Deployment created. status='%s'" % str(api_response.status))

        # Create a service called <name> whose endpoints are the pods
        # with "app": <name>; i.e. those just created above.
        self.create_service(name, name, ns, port, svc_type, traffic_policy, ipv6=ipv6)
コード例 #20
0
ファイル: deployment_crud.py プロジェクト: jstang9527/captain
    def get_deployment_template(self, deployment_name, image,
                                replicas):  # 获取模板
        # Configureate Pod template container
        container = client.V1Container(
            name=deployment_name,
            image=image,
            # command=['tail','-f','/dev/null'],
            ports=[client.V1ContainerPort(container_port=80)])
        # Create and configurate a spec section
        template = client.V1PodTemplateSpec(
            metadata=client.V1ObjectMeta(labels={"app": "nginx"}),
            spec=client.V1PodSpec(containers=[container]))
        # Create the specification of deployment
        spec = client.V1DeploymentSpec(
            replicas=replicas,
            template=template,
            selector={'matchLabels': {
                'app': 'nginx'
            }})
        # Instantiate the deployment object
        deployment = client.V1Deployment(
            api_version="apps/v1",
            kind="Deployment",
            metadata=client.V1ObjectMeta(name=deployment_name),
            spec=spec)

        return deployment
コード例 #21
0
ファイル: hello_world.py プロジェクト: interuss/dss
def _define_webserver_deployment() -> k8s.V1Deployment:
    # Define Pod container template
    container = k8s.V1Container(
        name='echo',
        image='hashicorp/http-echo',
        command=['/http-echo', '-listen=:{}'.format(CONTAINER_PORT), '-text="Echo server on port {}"'.format(CONTAINER_PORT)],
        ports=[k8s.V1ContainerPort(container_port=CONTAINER_PORT)],
        resources=k8s.V1ResourceRequirements(
            requests={'cpu': '100m', 'memory': '200Mi'},
            limits={'cpu': '500m', 'memory': '500Mi'},
        ),
    )

    # Create and configure a spec section
    template = k8s.V1PodTemplateSpec(
        metadata=k8s.V1ObjectMeta(labels={'app': APP_NAME}),
        spec=k8s.V1PodSpec(containers=[container]),
    )

    # Create the specification of deployment
    spec = k8s.V1DeploymentSpec(
        replicas=1, template=template, selector=k8s.V1LabelSelector(match_labels={'app': APP_NAME}))

    # Instantiate the deployment object
    deployment = k8s.V1Deployment(
        metadata=k8s.V1ObjectMeta(name=DEPLOYMENT_NAME),
        spec=spec,
    )

    return deployment
コード例 #22
0
def create_deployment_object():
    # Configureate Pod template container
    container = client.V1Container(
        name="zaproxy",
        image="owasp/zap2docker-stable",
        command=["zap.sh"],
        args=["-daemon", "-host", "0.0.0.0", "-port", "8090", "-config", "api.disablekey=true", "-config",
              "api.addrs.addr.name=.*", "-config", "api.addrs.addr.regex=true"],
        ports=[client.V1ContainerPort(container_port=8090)],
        resources=client.V1ResourceRequirements(
            requests={"cpu": "100m", "memory": "200Mi"},
            limits={"cpu": "500m", "memory": "500Mi"}
        )
    )
    # Create and configurate a spec section
    template = client.V1PodTemplateSpec(
        metadata=client.V1ObjectMeta(labels={'app': 'zap-app', 'name': 'zap-application'}),
        spec=client.V1PodSpec(containers=[container]))
    # Create the specification of deployment
    spec = client.V1DeploymentSpec(
        replicas=1,
        template=template,
        selector={'matchLabels': {'app': 'zap-app', 'name': 'zap-application'}})
    # Instantiate the deployment object
    deployment = client.V1Deployment(
        api_version="apps/v1",
        kind="Deployment",
        metadata=client.V1ObjectMeta(name=DEPLOYMENT_NAME, labels={'app': 'archerysec-app'}),
        spec=spec)

    return deployment
コード例 #23
0
def run_deployment(pod_spec,
                   replicas,
                   deploy_name,
                   template_label,
                   config_path=None):

    template = client.V1PodTemplateSpec(
        metadata=client.V1ObjectMeta(labels=template_label), spec=pod_spec)

    spec = client.V1DeploymentSpec(replicas=replicas,
                                   template=template,
                                   selector={'matchLabels': template_label})

    deployment_metadata = client.V1ObjectMeta(name=deploy_name,
                                              labels=template_label)

    deployment = client.V1Deployment(api_version="apps/v1",
                                     kind="Deployment",
                                     metadata=deployment_metadata,
                                     spec=spec)

    if config_path is None:
        base_dir = os.getcwd()
        config_path = os.path.join(base_dir, 'k3s_config.yaml')
    kube_config.load_kube_config(config_file=config_path)
    appsv1_client = client.AppsV1Api()
    appsv1_client.create_namespaced_deployment(body=deployment,
                                               namespace="default")
コード例 #24
0
def create_nginx_deployment(blogpost_name):
    container = client.V1Container(
        name="nginx",
        image="nginx:alpine",
        ports=[client.V1ContainerPort(container_port=80)],
        volume_mounts=[
            client.V1VolumeMount(name="config", mount_path="/etc/nginx/conf.d")
        ],
    )
    volume = client.V1Volume(
        name="config",
        config_map=client.V1ConfigMapVolumeSource(name=f"{blogpost_name}"),
    )
    template = client.V1PodTemplateSpec(
        metadata=client.V1ObjectMeta(labels={"app": f"nginx-{blogpost_name}"}),
        spec=client.V1PodSpec(containers=[container], volumes=[volume]),
    )
    spec = client.V1DeploymentSpec(
        replicas=1,
        template=template,
        selector={"matchLabels": {"app": f"nginx-{blogpost_name}"}},
    )

    return client.V1Deployment(
        api_version="apps/v1",
        kind="Deployment",
        metadata=client.V1ObjectMeta(name=f"nginx-{blogpost_name}"),
        spec=spec,
    )
コード例 #25
0
def create_deployment(api_instance,namespacename,dockerhost,imagename,buildtag,resourceid,portnumber):
  try:
    container =[] 
    imagetag=dockerhost+imagename+":"+buildtag
    containerdef={
        "name": resourceid,
        "image": imagetag,
        "ports": [client.V1ContainerPort(container_port=int(portnumber))]
      }
    container = []
    containeritem = client.V1Container( **containerdef )
    container.append(containeritem)
    # Create and configurate a spec section
    template = client.V1PodTemplateSpec(
        metadata=client.V1ObjectMeta(labels={'resourceid': resourceid}),
        spec=client.V1PodSpec(containers=container))
    # Create the specification of deployment
    spec = client.V1DeploymentSpec(
        replicas=1,
        template=template,
        selector={'matchLabels': {'resourceid': resourceid}})
    # Instantiate the deployment object
    deployment = client.V1Deployment(
        api_version="apps/v1",
        kind="Deployment",
        metadata=client.V1ObjectMeta(name=resourceid),
        spec=spec)
    api_response = api_instance.create_namespaced_deployment(
      body=deployment,
      namespace=namespacename)
    return("success", "Deployment_Intiated", api_response)
  except Exception as Error:
    return("error", "Deployment_Intiation_Failed", Error)
コード例 #26
0
def create_deployment_object(deployment_name, image_name):
    # Configurate Pod template container
    container = client.V1Container(
        name=image_name,
        image="lizhengjie/hcp-re:" + image_name,
        image_pull_policy="Always",
        ports=[client.V1ContainerPort(container_port=8888)])
    image_pull_secret = client.V1LocalObjectReference(name='regcred')
    # Create and configurate a spec section
    template = client.V1PodTemplateSpec(
        metadata=client.V1ObjectMeta(labels={"k8s-app": deployment_name}),
        spec=client.V1PodSpec(image_pull_secrets=[image_pull_secret],
                              containers=[container]))
    # Create the specification of deployment
    spec = client.V1DeploymentSpec(
        replicas=1,
        template=template,
        selector={'matchLabels': {
            'k8s-app': deployment_name
        }})
    # Instantiate the deployment object
    deployment = client.V1Deployment(
        api_version="apps/v1",
        kind="Deployment",
        metadata=client.V1ObjectMeta(name=deployment_name),
        spec=spec)
    return deployment
コード例 #27
0
def create_deployment(namespace, name, cpulim, memlim, podlim,priorityclass):
    try:
        config.load_kube_config()
    except:
        config.load_incluster_config()

    api = client.ExtensionsV1beta1Api()

    container = client.V1Container(
        name=name,
        image="ansi/lookbusy",
        resources=client.V1ResourceRequirements(
                  requests={'memory': memlim, 'cpu': cpulim}))

    body = client.ExtensionsV1beta1Deployment(
            api_version="extensions/v1beta1",
            kind="Deployment",
            metadata=client.V1ObjectMeta(name=name, namespace=namespace),
            spec = client.V1DeploymentSpec(
                selector=client.V1LabelSelector(match_labels={"app":name}),
                template = client.V1PodTemplateSpec(
                       metadata=client.V1ObjectMeta(name=name, namespace=namespace,labels={"app": name}),
                       spec=client.V1PodSpec(containers=[container],priority_class_name=priorityclass)
                       )
            )
        )
    pretty = 'true'

    try:
        api_response = api.create_namespaced_deployment(namespace, body, pretty=pretty)
    except ApiException as e:
        pprint("Exception when calling AppsV1Api->create_namespaced_deployment: %s\n" % e)
コード例 #28
0
    def _create_deployment(self):
        REPLICAS = 1

        container_port = k8s.V1ContainerPort(name=self.uid[-14:],
                                             container_port=os.getenv(
                                                 "OPENVAS_OMP_PORT", 9390))
        resources = k8s.V1ResourceRequirements(
            limits={
                "cpu": KubernetesDeployer.CONTAINER_USE_CPU_LIMIT,
                "memory": KubernetesDeployer.CONTAINER_USE_MEMORY_LIMIT,
            })
        readiness_probe = k8s.V1Probe(
            _exec=k8s.V1ExecAction(
                command=KubernetesDeployer.OPENVAS_HEALTHCHECK_COMMAND),
            initial_delay_seconds=300,
            period_seconds=30,
        )
        liveness_probe = k8s.V1Probe(
            tcp_socket=k8s.V1TCPSocketAction(
                port=container_port.container_port),
            initial_delay_seconds=180,
            period_seconds=30,
            failure_threshold=3,
            timeout_seconds=5,
        )
        container = k8s.V1Container(
            image=KubernetesDeployer.OPENVAS_CONTAINER_IMAGE,
            name=self.uid,
            image_pull_policy="IfNotPresent",
            ports=[container_port],
            resources=resources,
            readiness_probe=readiness_probe,
            liveness_probe=liveness_probe,
        )
        toleration = k8s.V1Toleration(effect="NoSchedule",
                                      key="Scanners",
                                      operator="Exists")
        pod_spec = k8s.V1PodSpec(containers=[container],
                                 tolerations=[toleration])
        pod_metadata = k8s.V1ObjectMeta(
            name=self.uid,
            labels={"app.kubernetes.io/name": self.uid},
            annotations={
                "cluster-autoscaler.kubernetes.io/safe-to-evict": "false"
            },
        )
        pod_template = k8s.V1PodTemplateSpec(spec=pod_spec,
                                             metadata=pod_metadata)
        selector = k8s.V1LabelSelector(
            match_labels={"app.kubernetes.io/name": self.uid})
        deployment_spec = k8s.V1DeploymentSpec(replicas=REPLICAS,
                                               selector=selector,
                                               template=pod_template)
        deployment_metadata = k8s.V1ObjectMeta(
            name=self.uid, labels={"app.kubernetes.io/name": self.uid})
        deployment = k8s.V1Deployment(spec=deployment_spec,
                                      metadata=deployment_metadata)
        return k8s.AppsV1Api(self.client).create_namespaced_deployment(
            self.namespace, deployment)
コード例 #29
0
    def create_deployment_sample(self, api_instance, deployment_sample_data):
        labels = {
            'alicek106_love_is_you': 'ls'
        }  # Default Label for matching ReplicaSets
        labels.update(deployment_sample_data.labels)

        env_vars = [
            client.V1EnvVar(name=env['name'], value=env['value'])
            for env in deployment_sample_data.env_vars
        ]
        publish_ports = [
            client.V1ContainerPort(name=port['name'],
                                   container_port=int(port['port']))
            for port in deployment_sample_data.publish_ports
        ]

        metadata = client.V1ObjectMeta(
            namespace=deployment_sample_data.namespace,
            name=deployment_sample_data.deployment_name,
            labels=labels)

        spec_pod = client.V1PodSpec(containers=[
            client.V1Container(
                name=deployment_sample_data.deployment_name,
                image=deployment_sample_data.image,
                env=env_vars,
                ports=publish_ports,
                image_pull_policy="Always",
                resources=client.V1ResourceRequirements(
                    limits=deployment_sample_data.resources['limit'],
                    requests=deployment_sample_data.resources['request']))
        ])

        spec_deployment = client.V1DeploymentSpec(
            replicas=deployment_sample_data.replicas,
            selector=client.V1LabelSelector(
                match_labels={'alicek106_love_is_you':
                              'ls'},  # Default Label for matching ReplicaSets
            ),
            template=client.V1PodTemplateSpec(
                metadata=client.V1ObjectMeta(labels=labels), spec=spec_pod))

        deployment_body = client.AppsV1beta1Deployment(kind='Deployment',
                                                       metadata=metadata,
                                                       spec=spec_deployment)

        try:
            api_instance.create_namespaced_deployment(
                namespace=deployment_sample_data.namespace,
                body=deployment_body)
            return GeneralError(200, 'success').serialize(), 200
        except ApiException as e:
            error = json.loads(e.body)
            return GeneralError(
                409, 'Reason: %s, %s' %
                (error['reason'], error['message'])).serialize(), 409
コード例 #30
0
def deployment_template(
    service_name,
    image_name,
    image_version,
    container_ports=None,
    container_args=None,
    container_env_from=None,
    container_resources=None,
    container_volume_mounts=None,
    volumes=None,
    startup_probe=None,
    liveness_probe=None,
    lifecycle=None,
    security_context=None,
    host_network=False,
    container_replicas=1,
):
    # Configure Pod template container
    container = client.V1Container(
        name=service_name,
        image="{}:{}".format(image_name, image_version),
        ports=container_ports,
        args=container_args,
        env_from=container_env_from,
        resources=container_resources,
        volume_mounts=container_volume_mounts,
        startup_probe=startup_probe,
        liveness_probe=liveness_probe,
        lifecycle=lifecycle,
        security_context=security_context,
    )
    # Create and configurate a spec section
    template = client.V1PodTemplateSpec(
        metadata=client.V1ObjectMeta(labels={"io.service": service_name}, ),
        spec=client.V1PodSpec(
            containers=[container],
            volumes=volumes,
            host_network=host_network,
        ),
    )
    # Create the specification of the deployment
    spec = client.V1DeploymentSpec(
        replicas=container_replicas,
        template=template,
        selector={"matchLabels": {
            "io.service": service_name
        }},
        strategy=client.V1DeploymentStrategy(type="Recreate"),
    )
    deployment = client.V1Deployment(
        api_version="apps/v1",
        kind="Deployment",
        metadata=client.V1ObjectMeta(name=service_name),
        spec=spec,
    )
    return deployment