Skip to content

Commit

Permalink
create from yaml file
Browse files Browse the repository at this point in the history
  • Loading branch information
micw523 committed Oct 27, 2018
1 parent 8b3391f commit 763b0fe
Show file tree
Hide file tree
Showing 9 changed files with 223 additions and 39 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -16,16 +16,15 @@

import yaml

from kubernetes import utils, config
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, resp = utils.create_deployment_from_yaml("./nginx-deployment.yaml")
print("Deployment created. status='%s'" % str(resp.status))
k8s_api = utils.create_from_yaml("nginx-deployment.yaml")


if __name__ == '__main__':
Expand Down
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

2 changes: 1 addition & 1 deletion kubernetes/utils/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,4 @@
# See the License for the specific language governing permissions and
# limitations under the License.

from .create_deployment_from_yaml import create_deployment_from_yaml
from .create_from_yaml import create_from_yaml
35 changes: 0 additions & 35 deletions kubernetes/utils/create_deployment_from_yaml.py

This file was deleted.

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

0 comments on commit 763b0fe

Please sign in to comment.