Skip to content

Commit

Permalink
Squashed commits: create from yaml
Browse files Browse the repository at this point in the history
  • Loading branch information
micw523 committed Oct 27, 2018
1 parent 3fb2be1 commit 9e5a5b1
Show file tree
Hide file tree
Showing 10 changed files with 269 additions and 1 deletion.
31 changes: 31 additions & 0 deletions examples/create_deployment_from_yaml.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# Copyright 2016 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 yaml

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_api = utils.create_from_yaml("nginx-deployment.yaml")


if __name__ == '__main__':
main()
1 change: 1 addition & 0 deletions kubernetes/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,4 @@
import kubernetes.config
import kubernetes.watch
import kubernetes.stream
import kubernetes.utils
86 changes: 86 additions & 0 deletions kubernetes/e2e_test/test_utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
# -*- 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_api = utils.create_from_yaml(
"kubernetes/e2e_test/test_yaml/app.yaml",
configuration=self.config)
self.assertEqual("apps/v1beta1",
k8s_api.get_api_resources().group_version)
deployments = k8s_api.list_namespaced_deployment(
namespace="default").items
deployment_name = []
for item in deployments:
deployment_name.append(item.metadata.name)
self.assertIn("nginx-app", deployment_name)
resp = k8s_api.delete_namespaced_deployment(
name="nginx-app", namespace="default",
body={})

def test_extension_yaml(self):
k8s_api = utils.create_from_yaml(
"kubernetes/e2e_test/test_yaml/extension.yaml",
configuration=self.config)
self.assertEqual("extensions/v1beta1",
k8s_api.get_api_resources().group_version)
deployments = k8s_api.list_namespaced_deployment(
namespace="default").items
deployment_name = []
for item in deployments:
deployment_name.append(item.metadata.name)
self.assertIn("nginx-deployment", deployment_name)
resp = k8s_api.delete_namespaced_deployment(
name="nginx-deployment", namespace="default",
body={})

def test_core_pod_yaml(self):
k8s_api = utils.create_from_yaml(
"kubernetes/e2e_test/test_yaml/core-pod.yaml",
configuration=self.config)
self.assertEqual("v1",
k8s_api.get_api_resources().group_version)
pods = k8s_api.list_namespaced_pod(namespace="default").items
pod_name = []
for item in pods:
pod_name.append(item.metadata.name)
self.assertIn("myapp-pod", pod_name)
resp = k8s_api.delete_namespaced_pod(
name="myapp-pod", namespace="default",
body={})

def test_core_service_yaml(self):
k8s_api = utils.create_from_yaml(
"kubernetes/e2e_test/test_yaml/core-service.yaml",
configuration=self.config)
self.assertEqual("v1",
k8s_api.get_api_resources().group_version)
svcs = k8s_api.list_namespaced_service(namespace="default").items
svc_name = []
for item in svcs:
svc_name.append(item.metadata.name)
self.assertIn("my-service", svc_name)
resp = k8s_api.delete_namespaced_service(
name="my-service", namespace="default",
body={})
21 changes: 21 additions & 0 deletions kubernetes/e2e_test/test_yaml/app.yaml
Original file line number Diff line number Diff line change
@@ -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
11 changes: 11 additions & 0 deletions kubernetes/e2e_test/test_yaml/core-pod.yaml
Original file line number Diff line number Diff line change
@@ -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']
11 changes: 11 additions & 0 deletions kubernetes/e2e_test/test_yaml/core-service.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
kind: Service
apiVersion: v1
metadata:
name: my-service
spec:
selector:
app: MyApp
ports:
- protocol: TCP
port: 80
targetPort: 9376
17 changes: 17 additions & 0 deletions kubernetes/e2e_test/test_yaml/extension.yaml
Original file line number Diff line number Diff line change
@@ -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

15 changes: 15 additions & 0 deletions kubernetes/utils/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# Copyright 2016 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
74 changes: 74 additions & 0 deletions kubernetes/utils/create_from_yaml.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
# Copyright 2016 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 sys

from six import iteritems

import yaml

from kubernetes import client

def create_from_yaml(yaml_file, verbose=0, **kwargs):
"""
Perform an action from a yaml file. Pass 1 for verbose to
print confirmation information.
Available parameters for generating the client:
:param configuration: Configuration for the client.
:param host: The base path for the server to call.
:param header_name: a header to pass when making calls to the API.
:param header_value: a header value to pass when making calls to the API.
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
"""

client_params = ["configuration", "host", "header_name", "header_value"]
action_params = ["async_req", "include_unitialized", "pretty", "dry_run",
'_return_http_data_only', '_preload_content', '_request_timeout']
client_args = {}
action_args = {}
params = locals()
for key, val in iteritems(params["kwargs"]):
if key in client_params:
client_args[key] = val
elif key in action_params:
action_args[key] = val

k8s_client = client.api_client.ApiClient(**client_args)
with open(path.abspath(yaml_file)) as f:
dep = yaml.load(f)
api_type, _, api_version = dep["apiVersion"].partition("/")
if api_version == "":
api_version = api_type
api_type = "core"
fcn_to_call = "{0}{1}Api".format(api_type.capitalize(),
api_version.capitalize())
k8s_api = getattr(client, fcn_to_call)(k8s_client)
action_type = dep["kind"]
if "namespace" in dep["metadata"]:
dep_namespace = dep["metadata"]["namespace"]
else:
dep_namespace = "default"
resp = getattr(k8s_api, "create_namespaced_{0}".format(action_type.lower()))(
body=dep, namespace=dep_namespace, **action_args)
if verbose:
print("{0} created. status='{1}'".format(action_type, str(resp.status)))
return k8s_api

3 changes: 2 additions & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -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/
Expand Down

0 comments on commit 9e5a5b1

Please sign in to comment.