diff --git a/examples/create_deployment_from_yaml.py b/examples/create_deployment_from_yaml.py new file mode 100644 index 0000000000..76452181b3 --- /dev/null +++ b/examples/create_deployment_from_yaml.py @@ -0,0 +1,32 @@ +# Copyright 2018 The Kubernetes Authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from os import path + +from kubernetes import client, config, utils + + +def main(): + # Configs can be set in Configuration class directly or using helper + # utility. If no argument provided, the config will be loaded from + # default location. + config.load_kube_config() + k8s_client = client.ApiClient() + k8s_api = utils.create_from_yaml(k8s_client, "nginx-deployment.yaml") + deps = k8s_api.read_namespaced_deployment("nginx-deployment", "default") + print("Deployment {0} created".format(deps.metadata.name)) + + +if __name__ == '__main__': + main() diff --git a/kubernetes/__init__.py b/kubernetes/__init__.py index 4dbe66f567..33c19ac878 100644 --- a/kubernetes/__init__.py +++ b/kubernetes/__init__.py @@ -20,3 +20,4 @@ import kubernetes.config import kubernetes.watch import kubernetes.stream +import kubernetes.utils diff --git a/kubernetes/e2e_test/test_utils.py b/kubernetes/e2e_test/test_utils.py new file mode 100644 index 0000000000..b43a77c432 --- /dev/null +++ b/kubernetes/e2e_test/test_utils.py @@ -0,0 +1,116 @@ +# -*- coding: utf-8 -*- + +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. + +import unittest + +from kubernetes import utils, client +from kubernetes.e2e_test import base + +class TestUtils(unittest.TestCase): + + @classmethod + def setUpClass(cls): + cls.config = base.get_e2e_configuration() + + def test_app_yaml(self): + k8s_client = client.api_client.ApiClient(configuration=self.config) + k8s_api = utils.create_from_yaml(k8s_client, + "kubernetes/e2e_test/test_yaml/apps-deployment.yaml") + self.assertEqual("apps/v1beta1", + k8s_api.get_api_resources().group_version) + dep = k8s_api.read_namespaced_deployment(name="nginx-app", + namespace="default") + self.assertIsNotNone(dep) + resp = k8s_api.delete_namespaced_deployment( + name="nginx-app", namespace="default", + body={}) + + def test_extension_yaml(self): + k8s_client = client.api_client.ApiClient(configuration=self.config) + k8s_api = utils.create_from_yaml(k8s_client, + "kubernetes/e2e_test/test_yaml/extensions-deployment.yaml") + self.assertEqual("extensions/v1beta1", + k8s_api.get_api_resources().group_version) + dep = k8s_api.read_namespaced_deployment(name="nginx-deployment", + namespace="default") + self.assertIsNotNone(dep) + resp = k8s_api.delete_namespaced_deployment( + name="nginx-deployment", namespace="default", + body={}) + + def test_core_pod_yaml(self): + k8s_client = client.api_client.ApiClient(configuration=self.config) + k8s_api = utils.create_from_yaml(k8s_client, + "kubernetes/e2e_test/test_yaml/core-pod.yaml") + self.assertEqual("v1", + k8s_api.get_api_resources().group_version) + pod = k8s_api.read_namespaced_pod(name="myapp-pod", + namespace="default") + self.assertIsNotNone(pod) + resp = k8s_api.delete_namespaced_pod( + name="myapp-pod", namespace="default", + body={}) + + def test_core_service_yaml(self): + k8s_client = client.api_client.ApiClient(configuration=self.config) + k8s_api = utils.create_from_yaml(k8s_client, + "kubernetes/e2e_test/test_yaml/core-service.yaml") + self.assertEqual("v1", + k8s_api.get_api_resources().group_version) + svc = k8s_api.read_namespaced_service(name="my-service", + namespace="default") + self.assertIsNotNone(svc) + resp = k8s_api.delete_namespaced_service( + name="my-service", namespace="default", + body={}) + + def test_core_namespace_yaml(self): + k8s_client = client.api_client.ApiClient(configuration=self.config) + k8s_api = utils.create_from_yaml(k8s_client, + "kubernetes/e2e_test/test_yaml/core-namespace.yaml") + self.assertEqual("v1", + k8s_api.get_api_resources().group_version) + nmsp = k8s_api.read_namespace(name="development") + self.assertIsNotNone(nmsp) + resp = k8s_api.delete_namespace(name="development", body={}) + + def test_deployment_in_namespace(self): + k8s_client = client.ApiClient(configuration=self.config) + core_api = utils.create_from_yaml(k8s_client, + "kubernetes/e2e_test/test_yaml/core-namespace-dep.yaml") + self.assertEqual("v1", + core_api.get_api_resources().group_version) + nmsp = core_api.read_namespace(name="dep") + self.assertIsNotNone(nmsp) + dep_api = utils.create_from_yaml(k8s_client, + "kubernetes/e2e_test/test_yaml/extensions-deployment-dep.yaml") + dep = dep_api.read_namespaced_deployment(name="nginx-deployment", + namespace="dep") + self.assertIsNotNone(dep) + resp = dep_api.delete_namespaced_deployment( + name="nginx-deployment", namespace="dep", + body={}) + resp = core_api.delete_namespace(name="dep", body={}) + + def test_api_service(self): + k8s_client = client.api_client.ApiClient(configuration=self.config) + k8s_api = utils.create_from_yaml(k8s_client, + "kubernetes/e2e_test/test_yaml/api-service.yaml") + self.assertEqual("apiregistration.k8s.io/v1beta1", + k8s_api.get_api_resources().group_version) + svc = k8s_api.read_api_service( + name="v1alpha1.wardle.k8s.io") + self.assertIsNotNone(svc) + resp = k8s_api.delete_api_service( + name="v1alpha1.wardle.k8s.io", body={}) \ No newline at end of file diff --git a/kubernetes/e2e_test/test_yaml/api-service.yaml b/kubernetes/e2e_test/test_yaml/api-service.yaml new file mode 100644 index 0000000000..29cb16b545 --- /dev/null +++ b/kubernetes/e2e_test/test_yaml/api-service.yaml @@ -0,0 +1,13 @@ +apiVersion: apiregistration.k8s.io/v1beta1 +kind: APIService +metadata: + name: v1alpha1.wardle.k8s.io +spec: + insecureSkipTLSVerify: true + group: wardle.k8s.io + groupPriorityMinimum: 1000 + versionPriority: 15 + service: + name: api + namespace: wardle + version: v1alpha1 \ No newline at end of file diff --git a/kubernetes/e2e_test/test_yaml/apps-deployment.yaml b/kubernetes/e2e_test/test_yaml/apps-deployment.yaml new file mode 100644 index 0000000000..a2ffa6b996 --- /dev/null +++ b/kubernetes/e2e_test/test_yaml/apps-deployment.yaml @@ -0,0 +1,21 @@ +apiVersion: apps/v1beta1 +kind: Deployment +metadata: + name: nginx-app + labels: + app: nginx +spec: + replicas: 3 + selector: + matchLabels: + app: nginx + template: + metadata: + labels: + app: nginx + spec: + containers: + - name: nginx + image: nginx:1.15.4 + ports: + - containerPort: 80 diff --git a/kubernetes/e2e_test/test_yaml/core-namespace-dep.yaml b/kubernetes/e2e_test/test_yaml/core-namespace-dep.yaml new file mode 100644 index 0000000000..38df99628c --- /dev/null +++ b/kubernetes/e2e_test/test_yaml/core-namespace-dep.yaml @@ -0,0 +1,6 @@ +apiVersion: v1 +kind: Namespace +metadata: + name: dep + labels: + name: dep \ No newline at end of file diff --git a/kubernetes/e2e_test/test_yaml/core-namespace.yaml b/kubernetes/e2e_test/test_yaml/core-namespace.yaml new file mode 100644 index 0000000000..dc475a757c --- /dev/null +++ b/kubernetes/e2e_test/test_yaml/core-namespace.yaml @@ -0,0 +1,6 @@ +apiVersion: v1 +kind: Namespace +metadata: + name: development + labels: + name: development \ No newline at end of file diff --git a/kubernetes/e2e_test/test_yaml/core-pod.yaml b/kubernetes/e2e_test/test_yaml/core-pod.yaml new file mode 100644 index 0000000000..8276a37fb5 --- /dev/null +++ b/kubernetes/e2e_test/test_yaml/core-pod.yaml @@ -0,0 +1,11 @@ +apiVersion: v1 +kind: Pod +metadata: + name: myapp-pod + labels: + app: myapp +spec: + containers: + - name: myapp-container + image: busybox + command: ['sh', '-c', 'echo Hello Kubernetes! && sleep 3600'] \ No newline at end of file diff --git a/kubernetes/e2e_test/test_yaml/core-service.yaml b/kubernetes/e2e_test/test_yaml/core-service.yaml new file mode 100644 index 0000000000..a805c9116c --- /dev/null +++ b/kubernetes/e2e_test/test_yaml/core-service.yaml @@ -0,0 +1,11 @@ +kind: Service +apiVersion: v1 +metadata: + name: my-service +spec: + selector: + app: MyApp + ports: + - protocol: TCP + port: 80 + targetPort: 9376 \ No newline at end of file diff --git a/kubernetes/e2e_test/test_yaml/extensions-deployment-dep.yaml b/kubernetes/e2e_test/test_yaml/extensions-deployment-dep.yaml new file mode 100644 index 0000000000..be9b281f20 --- /dev/null +++ b/kubernetes/e2e_test/test_yaml/extensions-deployment-dep.yaml @@ -0,0 +1,18 @@ +apiVersion: extensions/v1beta1 +kind: Deployment +metadata: + name: nginx-deployment + namespace: dep +spec: + replicas: 3 + template: + metadata: + labels: + app: nginx + spec: + containers: + - name: nginx + image: nginx:1.7.9 + ports: + - containerPort: 80 + diff --git a/kubernetes/e2e_test/test_yaml/extensions-deployment.yaml b/kubernetes/e2e_test/test_yaml/extensions-deployment.yaml new file mode 100644 index 0000000000..d05940d29b --- /dev/null +++ b/kubernetes/e2e_test/test_yaml/extensions-deployment.yaml @@ -0,0 +1,17 @@ +apiVersion: extensions/v1beta1 +kind: Deployment +metadata: + name: nginx-deployment +spec: + replicas: 3 + template: + metadata: + labels: + app: nginx + spec: + containers: + - name: nginx + image: nginx:1.7.9 + ports: + - containerPort: 80 + diff --git a/kubernetes/utils/__init__.py b/kubernetes/utils/__init__.py new file mode 100644 index 0000000000..4e6d6846a6 --- /dev/null +++ b/kubernetes/utils/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2018 The Kubernetes Authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .create_from_yaml import create_from_yaml diff --git a/kubernetes/utils/create_from_yaml.py b/kubernetes/utils/create_from_yaml.py new file mode 100644 index 0000000000..696a3abccd --- /dev/null +++ b/kubernetes/utils/create_from_yaml.py @@ -0,0 +1,74 @@ +# Copyright 2018 The Kubernetes Authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from os import path +import re +import sys + +from six import iteritems + +import yaml + +from kubernetes import client + +def create_from_yaml(k8s_client, yaml_file, verbose=False, **kwargs): + """ + Perform an action from a yaml file. Pass True for verbose to + print confirmation information. + + Input: + yaml_file: string. Contains the path to yaml file. + k8s_cline: an ApiClient object, initialized with the client args. + + Available parameters for performing the subsequent action: + :param async_req bool + :param bool include_uninitialized: If true, partially initialized resources are included in the response. + :param str pretty: If 'true', then the output is pretty printed. + :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed + """ + + with open(path.abspath(yaml_file)) as f: + yml_object = yaml.load(f) + #TODO: case of yaml file containing multiple objects + group, _, version = yml_object["apiVersion"].partition("/") + if version == "": + version = group + group = "core" + # Take care for the case e.g. api_type is "apiextensions.k8s.io" + # Only replace the last instance + group = "".join(group.rsplit(".k8s.io", 1)) + fcn_to_call = "{0}{1}Api".format(group.capitalize(), + version.capitalize()) + k8s_api = getattr(client, fcn_to_call)(k8s_client) + # Replace CamelCased action_type into snake_case + kind = yml_object["kind"] + kind = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', kind) + kind = re.sub('([a-z0-9])([A-Z])', r'\1_\2', kind).lower() + # Decide which namespace we are going to put the object in, + # if any + if "namespace" in yml_object["metadata"]: + namespace = yml_object["metadata"]["namespace"] + else: + namespace = "default" + # Expect the user to create namespaced objects more often + if hasattr(k8s_api, "create_namespaced_{0}".format(kind)): + resp = getattr(k8s_api, "create_namespaced_{0}".format(kind))( + body=yml_object, namespace=namespace, **kwargs) + else: + resp = getattr(k8s_api, "create_{0}".format(kind))( + body=yml_object, **kwargs) + if verbose: + print("{0} created. status='{1}'".format(kind, str(resp.status))) + return k8s_api + \ No newline at end of file diff --git a/setup.py b/setup.py index 9624448903..85ad8d17a9 100644 --- a/setup.py +++ b/setup.py @@ -57,7 +57,8 @@ extras_require=EXTRAS, packages=['kubernetes', 'kubernetes.client', 'kubernetes.config', 'kubernetes.watch', 'kubernetes.client.apis', - 'kubernetes.stream', 'kubernetes.client.models'], + 'kubernetes.stream', 'kubernetes.client.models', + 'kubernetes.utils'], include_package_data=True, long_description="""\ Python client for kubernetes http://kubernetes.io/